Skip to content
This repository was archived by the owner on Jan 12, 2024. It is now read-only.

Commit 7b36d44

Browse files
authored
Enable C# nullable reference types in test projects (#656)
* Enable C# nullable reference types in test projects * Remove ArgumentNullException * Remove unnecessary Assert.IsNotNull * Remove nullable from Q# projects
1 parent 3d9c192 commit 7b36d44

File tree

11 files changed

+61
-57
lines changed

11 files changed

+61
-57
lines changed

src/QsCompiler/CompilationManager/ProjectManager.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -738,7 +738,7 @@ public bool ManagerTask(Uri file, Action<CompilationUnitManager> executeTask, ID
738738
/// <summary>
739739
/// used to log exceptions raised during processing -> may be null!
740740
/// </summary>
741-
private readonly Action<Exception> logException;
741+
private readonly Action<Exception>? logException;
742742

743743
/// <summary>
744744
/// general purpose logging routine used for major loading events -> may be null!
@@ -750,7 +750,7 @@ public bool ManagerTask(Uri file, Action<CompilationUnitManager> executeTask, ID
750750
/// that action is called whenever diagnostics for the project have changed and are ready for publishing.
751751
/// Any exceptions caught during processing are logged using the given exception logger.
752752
/// </summary>
753-
public ProjectManager(Action<Exception> exceptionLogger, Action<string, MessageType>? log = null, Action<PublishDiagnosticParams>? publishDiagnostics = null)
753+
public ProjectManager(Action<Exception>? exceptionLogger, Action<string, MessageType>? log = null, Action<PublishDiagnosticParams>? publishDiagnostics = null)
754754
{
755755
this.load = new ProcessingQueue(exceptionLogger);
756756
this.projects = new ConcurrentDictionary<Uri, Project>();

src/QsCompiler/LanguageServer/EditorState.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ internal class EditorState : IDisposable
3030

3131
private readonly Action<PublishDiagnosticParams> publish;
3232
private readonly Action<string, Dictionary<string, string?>, Dictionary<string, int>> sendTelemetry;
33-
private readonly Action<Uri> onTemporaryProjectLoaded;
33+
private readonly Action<Uri>? onTemporaryProjectLoaded;
3434

3535
/// <summary>
3636
/// needed to determine if the reality of a source file that has changed on disk is indeed given by the content on disk,
@@ -58,11 +58,11 @@ internal class EditorState : IDisposable
5858
/// </summary>
5959
internal EditorState(
6060
ProjectLoader projectLoader,
61-
Action<PublishDiagnosticParams> publishDiagnostics,
62-
Action<string, Dictionary<string, string?>, Dictionary<string, int>> sendTelemetry,
63-
Action<string, MessageType> log,
64-
Action<Exception> onException,
65-
Action<Uri> onTemporaryProjectLoaded)
61+
Action<PublishDiagnosticParams>? publishDiagnostics,
62+
Action<string, Dictionary<string, string?>, Dictionary<string, int>>? sendTelemetry,
63+
Action<string, MessageType>? log,
64+
Action<Exception>? onException,
65+
Action<Uri>? onTemporaryProjectLoaded)
6666
{
6767
this.ignoreEditorUpdatesForFiles = new ConcurrentDictionary<Uri, byte>();
6868
this.sendTelemetry = sendTelemetry ?? ((eventName, properties, measurements) => { });
@@ -258,7 +258,7 @@ internal Task OpenFileAsync(
258258
{
259259
var projectUri = this.QsTemporaryProjectLoader(textDocument.Uri, sdkVersion: null); // null means the Sdk version will be set to the extension version
260260
this.projects.ProjectChangedOnDiskAsync(projectUri, this.QsProjectLoader, this.GetOpenFile);
261-
this.onTemporaryProjectLoaded(projectUri);
261+
this.onTemporaryProjectLoaded?.Invoke(projectUri);
262262
createdTemporaryProject = true;
263263
}
264264
catch (Exception ex)

src/QsCompiler/TestTargets/Simulation/Target/Driver.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@ static void Main(string[] args)
3232

3333
using (var qsim = new QuantumSimulator())
3434
{
35-
Task task = entryPoint.Invoke(null, new[] { qsim }) as Task<QVoid>;
35+
var task = entryPoint.Invoke(null, new[] { qsim }) as Task<QVoid>;
3636
task?.Wait();
3737
}
3838
}
3939
}
40-
}
40+
}

src/QsCompiler/TestTargets/Simulation/Target/Program.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ public CsharpGeneration() =>
3131
public IDictionary<string, string> AssemblyConstants { get; }
3232

3333
/// <inheritdoc/>
34-
public IEnumerable<IRewriteStep.Diagnostic> GeneratedDiagnostics { get; private set; }
34+
public IEnumerable<IRewriteStep.Diagnostic> GeneratedDiagnostics { get; private set; } =
35+
Enumerable.Empty<IRewriteStep.Diagnostic>();
3536

3637
/// <inheritdoc/>
3738
public bool ImplementsTransformation => true;

src/QsCompiler/TestTargets/Simulation/Target/Simulation.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
<TargetFramework>netstandard2.1</TargetFramework>
77
<PlatformTarget>x64</PlatformTarget>
88
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
9+
<Nullable>enable</Nullable>
10+
<WarningsAsErrors>nullable</WarningsAsErrors>
911
</PropertyGroup>
1012

1113
<ItemGroup>

src/QsCompiler/Tests.DocGenerator/Tests.DocGenerator.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
<IsPackable>false</IsPackable>
77
<RootNamespace>Microsoft.Quantum.QsCompiler.Documentation.Testing</RootNamespace>
88
<AssemblyName>Tests.Microsoft.Quantum.QsDocumentationParser</AssemblyName>
9+
<Nullable>enable</Nullable>
10+
<WarningsAsErrors>nullable</WarningsAsErrors>
911
</PropertyGroup>
1012

1113
<ItemGroup>

src/QsCompiler/Tests.LanguageServer/ProjectLoaderTests.cs

Lines changed: 35 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ private static string ProjectFileName(string project) =>
3838
private static string SourceFileName(string project, string fileName) =>
3939
Path.Combine("TestProjects", project, fileName);
4040

41-
private (string, ProjectInformation) Context(string project)
41+
private (string, ProjectInformation?) Context(string project)
4242
{
4343
var relativePath = ProjectFileName(project);
4444
var uri = new Uri(Path.GetFullPath(relativePath));
@@ -73,18 +73,18 @@ public void SupportedTargetFrameworks()
7373
[TestMethod]
7474
public void FindProjectTargetFramework()
7575
{
76-
void CompareFramework(string project, string expected)
76+
void CompareFramework(string project, string? expected)
7777
{
7878
var projectFileName = ProjectFileName(project);
7979
var props = new ProjectLoader().DesignTimeBuildProperties(projectFileName, out var _, (x, y) => (y.Contains('.') ? 1 : 0) - (x.Contains('.') ? 1 : 0));
80-
if (!props.TryGetValue("TargetFramework", out string actual))
80+
if (!props.TryGetValue("TargetFramework", out var actual))
8181
{
8282
actual = null;
8383
}
8484
Assert.AreEqual(expected, actual);
8585
}
8686

87-
var testProjects = new (string, string)[]
87+
var testProjects = new (string, string?)[]
8888
{
8989
("test1", "netcoreapp2.1"),
9090
("test2", "netstandard2.0"),
@@ -129,10 +129,10 @@ public void LoadNonQsharpProjects()
129129
public void LoadOutdatedQsharpProject()
130130
{
131131
var (projectFile, context) = this.Context("test9");
132-
var projDir = Path.GetDirectoryName(projectFile);
132+
var projDir = Path.GetDirectoryName(projectFile) ?? "";
133133
Assert.IsNotNull(context);
134-
Assert.AreEqual("test9.dll", Path.GetFileName(context.Properties.OutputPath));
135-
Assert.IsTrue(Path.GetDirectoryName(context.Properties.OutputPath).StartsWith(projDir));
134+
Assert.AreEqual("test9.dll", Path.GetFileName(context!.Properties.OutputPath));
135+
Assert.IsTrue((Path.GetDirectoryName(context.Properties.OutputPath) ?? "").StartsWith(projDir));
136136

137137
var qsFiles = new string[]
138138
{
@@ -149,10 +149,10 @@ public void LoadOutdatedQsharpProject()
149149
public void LoadQsharpCoreLibraries()
150150
{
151151
var (projectFile, context) = this.Context("test3");
152-
var projDir = Path.GetDirectoryName(projectFile);
152+
var projDir = Path.GetDirectoryName(projectFile) ?? "";
153153
Assert.IsNotNull(context);
154-
Assert.AreEqual("test3.dll", Path.GetFileName(context.Properties.OutputPath));
155-
Assert.IsTrue(Path.GetDirectoryName(context.Properties.OutputPath).StartsWith(projDir));
154+
Assert.AreEqual("test3.dll", Path.GetFileName(context!.Properties.OutputPath));
155+
Assert.IsTrue((Path.GetDirectoryName(context.Properties.OutputPath) ?? "").StartsWith(projDir));
156156

157157
var qsFiles = new string[]
158158
{
@@ -168,10 +168,10 @@ public void LoadQsharpCoreLibraries()
168168
CollectionAssert.AreEquivalent(qsFiles, context.SourceFiles.ToArray());
169169

170170
(projectFile, context) = this.Context("test12");
171-
projDir = Path.GetDirectoryName(projectFile);
171+
projDir = Path.GetDirectoryName(projectFile) ?? "";
172172
Assert.IsNotNull(context);
173-
Assert.AreEqual("test12.dll", Path.GetFileName(context.Properties.OutputPath));
174-
Assert.IsTrue(Path.GetDirectoryName(context.Properties.OutputPath).StartsWith(projDir));
173+
Assert.AreEqual("test12.dll", Path.GetFileName(context!.Properties.OutputPath));
174+
Assert.IsTrue((Path.GetDirectoryName(context.Properties.OutputPath) ?? "").StartsWith(projDir));
175175

176176
qsFiles = new string[]
177177
{
@@ -191,10 +191,10 @@ public void LoadQsharpCoreLibraries()
191191
public void LoadQsharpFrameworkLibrary()
192192
{
193193
var (projectFile, context) = this.Context("test7");
194-
var projDir = Path.GetDirectoryName(projectFile);
194+
var projDir = Path.GetDirectoryName(projectFile) ?? "";
195195
Assert.IsNotNull(context);
196-
Assert.AreEqual("test7.dll", Path.GetFileName(context.Properties.OutputPath));
197-
Assert.IsTrue(Path.GetDirectoryName(context.Properties.OutputPath).StartsWith(projDir));
196+
Assert.AreEqual("test7.dll", Path.GetFileName(context!.Properties.OutputPath));
197+
Assert.IsTrue((Path.GetDirectoryName(context.Properties.OutputPath) ?? "").StartsWith(projDir));
198198

199199
var qsFiles = new string[]
200200
{
@@ -211,10 +211,10 @@ public void LoadQsharpFrameworkLibrary()
211211
public void LoadQsharpConsoleApps()
212212
{
213213
var (projectFile, context) = this.Context("test4");
214-
var projDir = Path.GetDirectoryName(projectFile);
214+
var projDir = Path.GetDirectoryName(projectFile) ?? "";
215215
Assert.IsNotNull(context);
216-
Assert.AreEqual("test4.dll", Path.GetFileName(context.Properties.OutputPath));
217-
Assert.IsTrue(Path.GetDirectoryName(context.Properties.OutputPath).StartsWith(projDir));
216+
Assert.AreEqual("test4.dll", Path.GetFileName(context!.Properties.OutputPath));
217+
Assert.IsTrue((Path.GetDirectoryName(context.Properties.OutputPath) ?? "").StartsWith(projDir));
218218

219219
var qsFiles = new string[]
220220
{
@@ -228,10 +228,10 @@ public void LoadQsharpConsoleApps()
228228
CollectionAssert.AreEquivalent(qsFiles, context.SourceFiles.ToArray());
229229

230230
(projectFile, context) = this.Context("test10");
231-
projDir = Path.GetDirectoryName(projectFile);
231+
projDir = Path.GetDirectoryName(projectFile) ?? "";
232232
Assert.IsNotNull(context);
233-
Assert.AreEqual("test10.dll", Path.GetFileName(context.Properties.OutputPath));
234-
Assert.IsTrue(Path.GetDirectoryName(context.Properties.OutputPath).StartsWith(projDir));
233+
Assert.AreEqual("test10.dll", Path.GetFileName(context!.Properties.OutputPath));
234+
Assert.IsTrue((Path.GetDirectoryName(context.Properties.OutputPath) ?? "").StartsWith(projDir));
235235

236236
qsFiles = new string[]
237237
{
@@ -243,10 +243,10 @@ public void LoadQsharpConsoleApps()
243243
CollectionAssert.AreEquivalent(qsFiles, context.SourceFiles.ToArray());
244244

245245
(projectFile, context) = this.Context("test11");
246-
projDir = Path.GetDirectoryName(projectFile);
246+
projDir = Path.GetDirectoryName(projectFile) ?? "";
247247
Assert.IsNotNull(context);
248-
Assert.AreEqual("test11.dll", Path.GetFileName(context.Properties.OutputPath));
249-
Assert.IsTrue(Path.GetDirectoryName(context.Properties.OutputPath).StartsWith(projDir));
248+
Assert.AreEqual("test11.dll", Path.GetFileName(context!.Properties.OutputPath));
249+
Assert.IsTrue((Path.GetDirectoryName(context.Properties.OutputPath) ?? "").StartsWith(projDir));
250250

251251
qsFiles = new string[]
252252
{
@@ -262,10 +262,10 @@ public void LoadQsharpConsoleApps()
262262
public void LoadQsharpUnitTest()
263263
{
264264
var (projectFile, context) = this.Context("test5");
265-
var projDir = Path.GetDirectoryName(projectFile);
265+
var projDir = Path.GetDirectoryName(projectFile) ?? "";
266266
Assert.IsNotNull(context);
267-
Assert.AreEqual("test5.dll", Path.GetFileName(context.Properties.OutputPath));
268-
Assert.IsTrue(Path.GetDirectoryName(context.Properties.OutputPath).StartsWith(projDir));
267+
Assert.AreEqual("test5.dll", Path.GetFileName(context!.Properties.OutputPath));
268+
Assert.IsTrue((Path.GetDirectoryName(context.Properties.OutputPath) ?? "").StartsWith(projDir));
269269

270270
var qsFiles = new string[]
271271
{
@@ -286,10 +286,10 @@ public void LoadQsharpUnitTest()
286286
public void LoadQsharpMultiFrameworkLibrary()
287287
{
288288
var (projectFile, context) = this.Context("test6");
289-
var projDir = Path.GetDirectoryName(projectFile);
289+
var projDir = Path.GetDirectoryName(projectFile) ?? "";
290290
Assert.IsNotNull(context);
291-
Assert.AreEqual("test6.dll", Path.GetFileName(context.Properties.OutputPath));
292-
Assert.IsTrue(Path.GetDirectoryName(context.Properties.OutputPath).StartsWith(projDir));
291+
Assert.AreEqual("test6.dll", Path.GetFileName(context!.Properties.OutputPath));
292+
Assert.IsTrue((Path.GetDirectoryName(context.Properties.OutputPath) ?? "").StartsWith(projDir));
293293

294294
var qsFiles = new string[]
295295
{
@@ -314,8 +314,9 @@ public void LoadQsharpTemporaryProject()
314314

315315
var qsFiles = new string[] { sourceFile };
316316
var projectInformation = CompilationContext.Load(projectUri);
317-
Assert.IsTrue(projectInformation.UsesCanon());
318-
CollectionAssert.AreEquivalent(qsFiles, projectInformation.SourceFiles.ToArray());
317+
Assert.IsNotNull(projectInformation);
318+
Assert.IsTrue(projectInformation!.UsesCanon());
319+
CollectionAssert.AreEquivalent(qsFiles, projectInformation!.SourceFiles.ToArray());
319320
}
320321
}
321322

@@ -324,7 +325,7 @@ internal static class CompilationContext
324325
private static void LogOutput(string msg, MessageType level) =>
325326
Console.WriteLine($"[{level}]: {msg}");
326327

327-
internal static ProjectInformation Load(Uri projectFile) =>
328+
internal static ProjectInformation? Load(Uri projectFile) =>
328329
new EditorState(new ProjectLoader(LogOutput), null, null, null, null, null)
329330
.QsProjectLoader(projectFile, out var loaded) ? loaded : null;
330331

src/QsCompiler/Tests.LanguageServer/TestSetup.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ public sealed partial class BasicFunctionality : IDisposable
1818
{
1919
// basic setup
2020

21-
private Connection connection;
22-
private JsonRpc rpc;
21+
private Connection? connection;
22+
private JsonRpc rpc = null!; // Initialized in SetupServerConnectionAsync.
2323
private readonly RandomInput inputGenerator = new RandomInput();
2424
private readonly Stack<PublishDiagnosticParams> receivedDiagnostics = new Stack<PublishDiagnosticParams>();
2525

@@ -28,7 +28,7 @@ public Task<string[]> GetFileContentInMemoryAsync(string filename) =>
2828
Methods.WorkspaceExecuteCommand.Name,
2929
TestUtils.ServerCommand(CommandIds.FileContentInMemory, TestUtils.GetTextDocumentIdentifier(filename)));
3030

31-
public Task<Diagnostic[]> GetFileDiagnosticsAsync(string filename = null) =>
31+
public Task<Diagnostic[]> GetFileDiagnosticsAsync(string? filename = null) =>
3232
this.rpc.InvokeWithParameterObjectAsync<Diagnostic[]>(
3333
Methods.WorkspaceExecuteCommand.Name,
3434
TestUtils.ServerCommand(CommandIds.FileDiagnostics, filename == null ? new TextDocumentIdentifier { Uri = null } : TestUtils.GetTextDocumentIdentifier(filename)));

src/QsCompiler/Tests.LanguageServer/TestUtils.cs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -107,16 +107,12 @@ internal static int GetRangeLength(VisualStudio.LanguageServer.Protocol.Range ra
107107

108108
internal static void ApplyEdit(TextDocumentContentChangeEvent change, ref List<string> content)
109109
{
110-
if (content == null)
111-
{
112-
throw new ArgumentNullException(nameof(content));
113-
}
114110
if (!content.Any())
115111
{
116112
throw new ArgumentException("the given content has to have at least on line");
117113
}
118114

119-
Assert.IsTrue(IsValidRange(change?.Range) && change.Text != null);
115+
Assert.IsTrue(IsValidRange(change.Range) && change.Text != null);
120116
Assert.IsTrue(change.Range.End.Line < content.Count());
121117
Assert.IsTrue(change.Range.Start.Character <= content[change.Range.Start.Line].Length);
122118
Assert.IsTrue(change.Range.End.Character <= content[change.Range.End.Line].Length);
@@ -143,7 +139,7 @@ internal static void ApplyEdit(TextDocumentContentChangeEvent change, ref List<s
143139
content.InsertRange(startLine, lineChanges);
144140
}
145141

146-
internal static bool IsValidRange(Range range)
142+
internal static bool IsValidRange(Range? range)
147143
{
148144
static bool IsValidPosition(Position position) => position.Line >= 0 && position.Character >= 0;
149145

src/QsCompiler/Tests.LanguageServer/Tests.LanguageServer.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
<PlatformTarget>x64</PlatformTarget>
99
<OutputType>Library</OutputType>
1010
<NoWarn>NU1701</NoWarn>
11+
<Nullable>enable</Nullable>
12+
<WarningsAsErrors>nullable</WarningsAsErrors>
1113
</PropertyGroup>
1214

1315
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">

0 commit comments

Comments
 (0)