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

Commit edc3d15

Browse files
authored
Remove null argument checks and thrown ArgumentNullExceptions (#657)
* Remove ArgumentNullExceptions from CommandLineTool * Remove ArgumentNullExceptions from CompilationManager * Remove ArgumentNullExceptions from Compiler * Remove ArgumentNullExceptions from LanguageServer * Remove ArgumentNullExceptions in Transformations * Fix null error * Revert API change
1 parent 7b36d44 commit edc3d15

39 files changed

+191
-1858
lines changed

src/QsCompiler/CommandLineTool/Commands/Build.cs

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -152,14 +152,9 @@ private static IEnumerable<string> SplitCommandLineArguments(string commandLine)
152152
/// <summary>
153153
/// Reads the content off all given response files and tries to parse their concatenated content as command line arguments.
154154
/// Logs a suitable exceptions and returns null if the parsing fails.
155-
/// Throws an ArgumentNullException if the given sequence of responseFiles is null.
156155
/// </summary>
157156
private static BuildOptions? FromResponseFiles(IEnumerable<string> responseFiles)
158157
{
159-
if (responseFiles == null)
160-
{
161-
throw new ArgumentNullException(nameof(responseFiles));
162-
}
163158
var commandLine = string.Join(" ", responseFiles.Select(File.ReadAllText));
164159
var args = SplitCommandLineArguments(commandLine);
165160
var parsed = Parser.Default.ParseArguments<BuildOptions>(args);
@@ -177,18 +172,9 @@ private static IEnumerable<string> SplitCommandLineArguments(string commandLine)
177172
/// <summary>
178173
/// Builds the compilation for the Q# code or Q# snippet and referenced assemblies defined by the given options.
179174
/// Returns a suitable error code if one of the compilation or generation steps fails.
180-
/// Throws an ArgumentNullException if any of the given arguments is null.
181175
/// </summary>
182176
public static int Run(BuildOptions options, ConsoleLogger logger)
183177
{
184-
if (options == null)
185-
{
186-
throw new ArgumentNullException(nameof(options));
187-
}
188-
if (logger == null)
189-
{
190-
throw new ArgumentNullException(nameof(logger));
191-
}
192178
if (!BuildOptions.IncorporateResponseFiles(options, out var incorporated))
193179
{
194180
logger.Log(ErrorCode.InvalidCommandLineArgsInResponseFiles, Array.Empty<string>());

src/QsCompiler/CommandLineTool/Commands/Diagnose.cs

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -78,14 +78,9 @@ public static IEnumerable<Example> UsageExamples
7878
/// Logs the content of each file in the given compilation as Information using the given logger.
7979
/// If the id of a file is consistent with the one assigned to a code snippet,
8080
/// strips the lines of code that correspond to the wrapping defined by WrapSnippet.
81-
/// Throws an ArgumentNullException if the given compilation is null.
8281
/// </summary>
8382
private static void PrintFileContentInMemory(Compilation compilation, ILogger logger)
8483
{
85-
if (compilation == null)
86-
{
87-
throw new ArgumentNullException(nameof(compilation));
88-
}
8984
foreach (var file in compilation.SourceFiles)
9085
{
9186
IEnumerable<string> inMemory = compilation.FileContent[file];
@@ -110,14 +105,9 @@ private static void PrintFileContentInMemory(Compilation compilation, ILogger lo
110105
/// Logs the tokenization of each file in the given compilation as Information using the given logger.
111106
/// If the id of a file is consistent with the one assigned to a code snippet,
112107
/// strips the tokens that correspond to the wrapping defined by WrapSnippet.
113-
/// Throws an ArgumentNullException if the given compilation is null.
114108
/// </summary>
115109
private static void PrintContentTokenization(Compilation compilation, ILogger logger)
116110
{
117-
if (compilation == null)
118-
{
119-
throw new ArgumentNullException(nameof(compilation));
120-
}
121111
foreach (var file in compilation.SourceFiles)
122112
{
123113
var tokenization = compilation.Tokenization[file].Select(tokens => tokens.Select(token => token.Kind));
@@ -152,14 +142,9 @@ private static void PrintContentTokenization(Compilation compilation, ILogger lo
152142
/// If the id of a file is consistent with the one assigned to a code snippet,
153143
/// strips the lines of code that correspond to the wrapping defined by WrapSnippet.
154144
/// Throws an ArgumentException if this is not possible because the given syntax tree is inconsistent with that wrapping.
155-
/// Throws an ArgumentNullException if the given compilation is null.
156145
/// </summary>
157146
private static void PrintSyntaxTree(IEnumerable<QsNamespace>? evaluatedTree, Compilation compilation, ILogger logger)
158147
{
159-
if (compilation == null)
160-
{
161-
throw new ArgumentNullException(nameof(compilation));
162-
}
163148
evaluatedTree ??= compilation.SyntaxTree.Values;
164149

165150
foreach (var file in compilation.SourceFiles)
@@ -191,14 +176,9 @@ void PrintTree(string serialization) => logger.Log(
191176
/// If the id of a file is consistent with the one assigned to a code snippet,
192177
/// strips the lines of code that correspond to the wrapping defined by WrapSnippet.
193178
/// Throws an ArgumentException if this is not possible because the given syntax tree is inconsistent with that wrapping.
194-
/// Throws an ArgumentNullException if the given compilation is null.
195179
/// </summary>
196180
private static void PrintGeneratedQs(IEnumerable<QsNamespace>? evaluatedTree, Compilation compilation, ILogger logger)
197181
{
198-
if (compilation == null)
199-
{
200-
throw new ArgumentNullException(nameof(compilation));
201-
}
202182
evaluatedTree ??= compilation.SyntaxTree.Values;
203183

204184
foreach (var file in compilation.SourceFiles)
@@ -224,14 +204,9 @@ private static void PrintGeneratedQs(IEnumerable<QsNamespace>? evaluatedTree, Co
224204
/// <summary>
225205
/// Strips the namespace and callable declaration that is consistent with the wrapping defined by WrapSnippet.
226206
/// Throws an ArgumentException if this is not possible because the given syntax tree is inconsistent with that wrapping.
227-
/// Throws an ArgumentNullException if the given syntaxTree is null.
228207
/// </summary>
229208
public static IEnumerable<QsStatement> StripSnippetWrapping(IEnumerable<QsNamespace> syntaxTree)
230209
{
231-
if (syntaxTree == null)
232-
{
233-
throw new ArgumentNullException(nameof(syntaxTree));
234-
}
235210
var incorrectWrapperException = new ArgumentException("syntax tree does not reflect the expected wrapper");
236211
if (syntaxTree.Count() != 1 || syntaxTree.Single().Elements.Count() != 1)
237212
{
@@ -253,19 +228,9 @@ public static IEnumerable<QsStatement> StripSnippetWrapping(IEnumerable<QsNamesp
253228
/// Builds the compilation for the Q# code or Q# snippet and referenced assemblies defined by the given options.
254229
/// Prints the data structures requested by the given options using the given logger.
255230
/// Returns a suitable error code if one of the compilation or generation steps fails.
256-
/// Throws an ArgumentNullException if any of the given arguments is null.
257231
/// </summary>
258232
public static int Run(DiagnoseOptions options, ConsoleLogger logger)
259233
{
260-
if (options == null)
261-
{
262-
throw new ArgumentNullException(nameof(options));
263-
}
264-
if (logger == null)
265-
{
266-
throw new ArgumentNullException(nameof(logger));
267-
}
268-
269234
if (!options.ParseAssemblyProperties(out var assemblyConstants))
270235
{
271236
logger.Log(WarningCode.InvalidAssemblyProperties, Array.Empty<string>());

src/QsCompiler/CommandLineTool/Commands/Format.cs

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -71,14 +71,9 @@ public static string UpdateArrayLiterals(string fileContent)
7171
/// If the id of a file is consistent with the one assigned to a code snippet,
7272
/// strips the lines of code that correspond to the wrapping defined by WrapSnippet.
7373
/// Throws an ArgumentException if this is not possible because the given syntax tree is inconsistent with that wrapping.
74-
/// Throws an ArgumentNullException if the given compilation is null.
7574
/// </summary>
7675
private static IEnumerable<string> GenerateQsCode(Compilation compilation, NonNullable<string> file, ILogger logger)
7776
{
78-
if (compilation == null)
79-
{
80-
throw new ArgumentNullException(nameof(compilation));
81-
}
8277
if (Options.IsCodeSnippet(file))
8378
{
8479
var subtree = compilation.SyntaxTree.Values.Select(ns => FilterBySourceFile.Apply(ns, file)).Where(ns => ns.Elements.Any());
@@ -119,15 +114,9 @@ string FormatComments(IEnumerable<string> comments) =>
119114
/// logs the generated code using the given logger.
120115
/// Creates a file containing the generated code in the given output folder otherwise.
121116
/// Returns true if the generation succeeded, and false if an exception was thrown.
122-
/// Throws an ArgumentNullException if the given compilation, the file uri or its absolute path are null.
123117
/// </summary>
124118
private static bool GenerateFormattedQsFile(Compilation compilation, NonNullable<string> fileName, string? outputFolder, ILogger logger)
125119
{
126-
if (compilation == null)
127-
{
128-
throw new ArgumentNullException(nameof(compilation));
129-
}
130-
131120
var code = Enumerable.Empty<string>();
132121
try
133122
{
@@ -158,19 +147,9 @@ private static bool GenerateFormattedQsFile(Compilation compilation, NonNullable
158147
/// Generates formatted Q# code for each source file in the compilation.
159148
/// Returns a suitable error code if some of the source files or references could not be found or loaded, or if the Q# generation failed.
160149
/// Compilation errors are not reflected in the return code, but are logged using the given logger.
161-
/// Throws an ArgumentNullException if any of the given arguments is null.
162150
/// </summary>
163151
public static int Run(FormatOptions options, ConsoleLogger logger)
164152
{
165-
if (options == null)
166-
{
167-
throw new ArgumentNullException(nameof(options));
168-
}
169-
if (logger == null)
170-
{
171-
throw new ArgumentNullException(nameof(logger));
172-
}
173-
174153
ImmutableDictionary<Uri, string> LoadSources(SourceFileLoader loadFromDisk) =>
175154
options.LoadSourcesOrSnippet(logger)(loadFromDisk)
176155
.ToImmutableDictionary(entry => entry.Key, entry => UpdateArrayLiterals(entry.Value)); // manually replace array literals

src/QsCompiler/CommandLineTool/LoadContext.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ public void RemoveFromPath(params string[] paths) =>
3939

4040
private LoadContext(string parentAssembly)
4141
{
42-
this.PathToParentAssembly = parentAssembly ?? throw new ArgumentNullException(nameof(parentAssembly));
42+
this.PathToParentAssembly = parentAssembly;
4343
this.resolver = new AssemblyDependencyResolver(this.PathToParentAssembly);
4444
this.fallbackPaths = new HashSet<string>();
4545
this.Resolving += this.OnResolving;

src/QsCompiler/CommandLineTool/Logging.cs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,9 @@ public ConsoleLogger(
4040
/// <summary>
4141
/// Prints the given message to the Console.
4242
/// Errors and Warnings are printed to the error stream.
43-
/// Throws an ArgumentNullException if the given message is null.
4443
/// </summary>
4544
private static void PrintToConsole(DiagnosticSeverity severity, string message)
4645
{
47-
if (message == null)
48-
{
49-
throw new ArgumentNullException(nameof(message));
50-
}
5146
var (stream, color) =
5247
severity == DiagnosticSeverity.Error ? (Console.Error, ConsoleColor.Red) :
5348
severity == DiagnosticSeverity.Warning ? (Console.Error, ConsoleColor.Yellow) :

src/QsCompiler/CompilationManager/AssemblyLoader.cs

Lines changed: 4 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -31,19 +31,16 @@ public static class AssemblyLoader
3131
/// Returns false if some of the content could not be loaded successfully,
3232
/// possibly because the referenced assembly has been compiled with an older compiler version.
3333
/// If onDeserializationException is specified, invokes the given action on any exception thrown during deserialization.
34-
/// Throws an ArgumentNullException if the given uri is null.
34+
/// Throws an ArgumentException if the URI is not an absolute file URI.
3535
/// Throws a FileNotFoundException if no file with the given name exists.
3636
/// Throws the corresponding exceptions if the information cannot be extracted.
3737
/// </summary>
3838
public static bool LoadReferencedAssembly(Uri asm, out References.Headers headers, bool ignoreDllResources = false, Action<Exception>? onDeserializationException = null)
3939
{
40-
if (asm == null)
40+
var id = CompilationUnitManager.GetFileId(asm);
41+
if (!File.Exists(asm.LocalPath))
4142
{
42-
throw new ArgumentNullException(nameof(asm));
43-
}
44-
if (!CompilationUnitManager.TryGetFileId(asm, out var id) || !File.Exists(asm.LocalPath))
45-
{
46-
throw new FileNotFoundException($"The uri '{asm}' given to the assembly loader is invalid or the file does not exist.");
43+
throw new FileNotFoundException($"The file '{asm.LocalPath}' given to the assembly loader does not exist.");
4744
}
4845

4946
using var stream = File.OpenRead(asm.LocalPath);
@@ -65,18 +62,13 @@ public static bool LoadReferencedAssembly(Uri asm, out References.Headers header
6562
/// possibly because the referenced assembly has been compiled with an older compiler version.
6663
/// Catches any exception throw upon loading the compilation, and invokes onException with it if such an action has been specified.
6764
/// Sets the out parameter to null if an exception occurred during loading.
68-
/// Throws an ArgumentNullException if the given uri is null.
6965
/// Throws a FileNotFoundException if no file with the given name exists.
7066
/// </summary>
7167
public static bool LoadReferencedAssembly(
7268
string asmPath,
7369
[NotNullWhen(true)] out QsCompilation? compilation,
7470
Action<Exception>? onException = null)
7571
{
76-
if (asmPath == null)
77-
{
78-
throw new ArgumentNullException(nameof(asmPath));
79-
}
8072
if (!File.Exists(asmPath))
8173
{
8274
throw new FileNotFoundException($"The file '{asmPath}' does not exist.");
@@ -102,17 +94,12 @@ public static bool LoadReferencedAssembly(
10294
/// Given a stream containing the binary representation of compiled Q# code, returns the corresponding Q# compilation.
10395
/// Returns true if the compilation could be deserialized without throwing an exception, and false otherwise.
10496
/// If onDeserializationException is specified, invokes the given action on any exception thrown during deserialization.
105-
/// Throws an ArgumentNullException if the given stream is null, but ignores exceptions thrown during deserialization.
10697
/// </summary>
10798
public static bool LoadSyntaxTree(
10899
Stream stream,
109100
[NotNullWhen(true)] out QsCompilation? compilation,
110101
Action<Exception>? onDeserializationException = null)
111102
{
112-
if (stream == null)
113-
{
114-
throw new ArgumentNullException(nameof(stream));
115-
}
116103
using var reader = new BsonDataReader(stream);
117104
(compilation, reader.ReadRootValueAsArray) = (null, false);
118105
try
@@ -141,18 +128,13 @@ private static ImmutableDictionary<string, ManifestResource> Resources(this Meta
141128
/// Given a reader for the byte stream of a dotnet dll, loads any Q# compilation included as a resource.
142129
/// Returns true as well as the loaded compilation if the given dll includes a suitable resource, and returns false otherwise.
143130
/// If onDeserializationException is specified, invokes the given action on any exception thrown during deserialization.
144-
/// Throws an ArgumentNullException if any of the given readers is null.
145131
/// May throw an exception if the given binary file has been compiled with a different compiler version.
146132
/// </summary>
147133
private static bool FromResource(
148134
PEReader assemblyFile,
149135
[NotNullWhen(true)] out QsCompilation? compilation,
150136
Action<Exception>? onDeserializationException = null)
151137
{
152-
if (assemblyFile == null)
153-
{
154-
throw new ArgumentNullException(nameof(assemblyFile));
155-
}
156138
var metadataReader = assemblyFile.GetMetadataReader();
157139
compilation = null;
158140

@@ -239,15 +221,10 @@ private static (string, string)? GetAttribute(MetadataReader metadataReader, Cus
239221
/// Given a reader for the byte stream of a dotnet dll, read its custom attributes and
240222
/// returns a tuple containing the name of the attribute and the constructor argument
241223
/// for all attributes defined in a Microsoft.Quantum* namespace.
242-
/// Throws an ArgumentNullException if the given stream is null.
243224
/// Throws the corresponding exceptions if the information cannot be extracted.
244225
/// </summary>
245226
private static IEnumerable<(string, string)> LoadHeaderAttributes(PEReader assemblyFile)
246227
{
247-
if (assemblyFile == null)
248-
{
249-
throw new ArgumentNullException(nameof(assemblyFile));
250-
}
251228
var metadataReader = assemblyFile.GetMetadataReader();
252229
return metadataReader.GetAssemblyDefinition().GetCustomAttributes()
253230
.Select(metadataReader.GetCustomAttribute)

0 commit comments

Comments
 (0)