Skip to content

Commit

Permalink
Merge pull request #767 from JoeRobich/fix-nullability-warnings
Browse files Browse the repository at this point in the history
Fix warnings and apply suggestions.
  • Loading branch information
JoeRobich committed Aug 20, 2020
2 parents 0570b5b + cf18249 commit d73e027
Show file tree
Hide file tree
Showing 20 changed files with 209 additions and 54 deletions.
6 changes: 3 additions & 3 deletions .vscode/tasks.json
Expand Up @@ -11,7 +11,7 @@
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
"problemMatcher": []
},
{
"label": "publish",
Expand All @@ -25,7 +25,7 @@
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
"problemMatcher": []
},
{
"label": "watch",
Expand All @@ -38,7 +38,7 @@
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
"problemMatcher": []
}
]
}
2 changes: 1 addition & 1 deletion perf/Utilities/MSBuildRegister.cs
Expand Up @@ -8,7 +8,7 @@ namespace Microsoft.CodeAnalysis.Tools.Perf
{
public static class MSBuildRegister
{
private static int s_registered = 0;
private static int s_registered;

public static void RegisterInstance()
{
Expand Down
2 changes: 1 addition & 1 deletion perf/Utilities/SolutionPathSetter.cs
Expand Up @@ -8,7 +8,7 @@ namespace Microsoft.CodeAnalysis.Tools.Perf
{
public static class SolutionPathSetter
{
private static int s_registered = 0;
private static int s_registered;
private static string s_currentDirectory;
public static string RepositoryRootDirectory => Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.FullName;

Expand Down
13 changes: 9 additions & 4 deletions src/Analyzers/AnalyzerFormatter.cs
Expand Up @@ -101,7 +101,7 @@ internal class AnalyzerFormatter : ICodeFormatter
foreach (var project in solution.Projects)
{
var analyzers = projectAnalyzers[project];
if (analyzers.Length == 0)
if (analyzers.IsEmpty)
{
continue;
}
Expand All @@ -116,13 +116,18 @@ internal class AnalyzerFormatter : ICodeFormatter

static void LogDiagnosticLocations(Solution solution, IEnumerable<Diagnostic> diagnostics, string workspacePath, bool changesAreErrors, ILogger logger, List<FormattedFile> formattedFiles)
{
var workspaceFolder = Path.GetDirectoryName(workspacePath);
var workspaceFolder = Path.GetDirectoryName(workspacePath) ?? workspacePath;

foreach (var diagnostic in diagnostics)
{
var message = $"{diagnostic.GetMessage()} ({diagnostic.Id})";
var filePath = diagnostic.Location.SourceTree?.FilePath;
var document = solution.GetDocument(diagnostic.Location.SourceTree);
if (document is null)
{
continue;
}

var filePath = document.FilePath ?? document.Name;

var mappedLineSpan = diagnostic.Location.GetMappedLineSpan();
var changePosition = mappedLineSpan.StartLinePosition;
Expand Down Expand Up @@ -252,7 +257,7 @@ static void LogDiagnosticLocations(Solution solution, IEnumerable<Diagnostic> di
{
// Always run naming style analyzers because we cannot determine potential severity.
// The reported diagnostics will be filtered by severity when they are run.
if (analyzer.GetType().FullName.EndsWith("NamingStyleDiagnosticAnalyzer"))
if (analyzer.GetType().FullName?.EndsWith("NamingStyleDiagnosticAnalyzer") == true)
{
analyzers.Add(analyzer);
continue;
Expand Down
5 changes: 4 additions & 1 deletion src/Analyzers/AnalyzerReferenceInformationProvider.cs
Expand Up @@ -70,7 +70,10 @@ internal class AnalyzerReferenceInformationProvider : IAnalyzerInformationProvid
{
// Next see if this assembly has already been loaded into our context.
var assemblyName = AssemblyLoadContext.GetAssemblyName(path);
return AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(assemblyName.Name));
if (assemblyName?.Name != null)
{
return AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(assemblyName.Name));
}
}
catch { }

Expand Down
2 changes: 1 addition & 1 deletion src/Analyzers/CodeStyleInformationProvider.cs
Expand Up @@ -12,7 +12,7 @@ namespace Microsoft.CodeAnalysis.Tools.Analyzers
{
internal class CodeStyleInformationProvider : IAnalyzerInformationProvider
{
private static readonly string s_executingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static readonly string s_executingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty;

private readonly string _featuresPath = Path.Combine(s_executingPath, "Microsoft.CodeAnalysis.Features.dll");
private readonly string _featuresCSharpPath = Path.Combine(s_executingPath, "Microsoft.CodeAnalysis.CSharp.Features.dll");
Expand Down
20 changes: 12 additions & 8 deletions src/Analyzers/Extensions.cs
Expand Up @@ -22,8 +22,8 @@ public static class Extensions
static Extensions()
{
MicrosoftCodeAnalysisFeaturesAssembly = Assembly.Load(new AssemblyName("Microsoft.CodeAnalysis.Features"));
IDEDiagnosticIdToOptionMappingHelperType = MicrosoftCodeAnalysisFeaturesAssembly.GetType("Microsoft.CodeAnalysis.Diagnostics.IDEDiagnosticIdToOptionMappingHelper");
TryGetMappedOptionsMethod = IDEDiagnosticIdToOptionMappingHelperType.GetMethod("TryGetMappedOptions", BindingFlags.Static | BindingFlags.Public);
IDEDiagnosticIdToOptionMappingHelperType = MicrosoftCodeAnalysisFeaturesAssembly.GetType("Microsoft.CodeAnalysis.Diagnostics.IDEDiagnosticIdToOptionMappingHelper")!;
TryGetMappedOptionsMethod = IDEDiagnosticIdToOptionMappingHelperType.GetMethod("TryGetMappedOptions", BindingFlags.Static | BindingFlags.Public)!;
}

public static bool Any(this SolutionChanges solutionChanges)
Expand All @@ -36,7 +36,7 @@ public static bool Any(this SolutionChanges solutionChanges)
var defaultCtor = type.GetConstructor(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
binder: null,
new Type[] { },
Array.Empty<Type>(),
modifiers: null);

instance = defaultCtor != null
Expand All @@ -45,7 +45,7 @@ public static bool Any(this SolutionChanges solutionChanges)
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
binder: null,
args: null,
culture: null)
culture: null)!
: null;

return instance != null;
Expand Down Expand Up @@ -160,7 +160,7 @@ public static DiagnosticSeverity ToSeverity(this ReportDiagnostic reportDiagnost
severity = DiagnosticSeverity.Hidden;

var parameters = new object?[] { descriptor.Id, compilation.Language, null };
var result = (bool)TryGetMappedOptionsMethod.Invoke(null, parameters);
var result = (bool)(TryGetMappedOptionsMethod.Invoke(null, parameters) ?? false);

if (!result)
{
Expand All @@ -170,7 +170,7 @@ public static DiagnosticSeverity ToSeverity(this ReportDiagnostic reportDiagnost
var codeStyleOptions = (IEnumerable)parameters[2]!;
foreach (var codeStyleOptionObj in codeStyleOptions)
{
var codeStyleOption = (IOption)codeStyleOptionObj;
var codeStyleOption = (IOption)codeStyleOptionObj!;
var option = options.GetOption(new OptionKey(codeStyleOption, codeStyleOption.IsPerLanguage ? compilation.Language : null));
if (option is null)
{
Expand All @@ -184,9 +184,13 @@ public static DiagnosticSeverity ToSeverity(this ReportDiagnostic reportDiagnost
}

var notification = notificationProperty.GetValue(option);
var reportDiagnostic = (ReportDiagnostic)notification.GetType().GetProperty("Severity").GetValue(notification);
var codeStyleSeverity = ToSeverity(reportDiagnostic);
var reportDiagnosticValue = notification?.GetType().GetProperty("Severity")?.GetValue(notification);
if (reportDiagnosticValue is null)
{
continue;
}

var codeStyleSeverity = ToSeverity((ReportDiagnostic)reportDiagnosticValue);
if (codeStyleSeverity > severity)
{
severity = codeStyleSeverity;
Expand Down
2 changes: 1 addition & 1 deletion src/Formatters/EndOfLineFormatter.cs
Expand Up @@ -38,7 +38,7 @@ internal sealed class EndOfLineFormatter : DocumentFormatter
var lineEndingSpan = new TextSpan(line.End, line.EndIncludingLineBreak - line.End);
// Check for end of file
if (lineEndingSpan.Length == 0)
if (lineEndingSpan.IsEmpty)
{
break;
}
Expand Down
7 changes: 3 additions & 4 deletions src/Formatters/FinalNewlineFormatter.cs
@@ -1,7 +1,6 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
Expand Down Expand Up @@ -35,7 +34,7 @@ internal sealed class FinalNewlineFormatter : DocumentFormatter
endOfLine = Environment.NewLine;
}

var lastLine = sourceText.Lines.Last();
var lastLine = sourceText.Lines[^1];
var hasFinalNewline = lastLine.Span.IsEmpty;

if (insertFinalNewline && !hasFinalNewline)
Expand All @@ -49,12 +48,12 @@ internal sealed class FinalNewlineFormatter : DocumentFormatter
// In the case of empty files where there is a single empty line, there is nothing to remove.
while (sourceText.Lines.Count > 1 && hasFinalNewline)
{
var lineBeforeLast = sourceText.Lines[sourceText.Lines.Count - 2];
var lineBeforeLast = sourceText.Lines[^2];
var finalNewlineSpan = new TextSpan(lineBeforeLast.End, lineBeforeLast.EndIncludingLineBreak - lineBeforeLast.End);
var removeNewlineChange = new TextChange(finalNewlineSpan, string.Empty);
sourceText = sourceText.WithChanges(removeNewlineChange);

lastLine = sourceText.Lines.Last();
lastLine = sourceText.Lines[^1];
hasFinalNewline = lastLine.Span.IsEmpty;
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/Formatters/UnnecessaryImportsFormatter.cs
Expand Up @@ -49,6 +49,10 @@ internal sealed class UnnecessaryImportsFormatter : DocumentFormatter
}

var formattedDocument = await RemoveUnnecessaryImportsHelper.RemoveUnnecessaryImportsAsync(document, cancellationToken).ConfigureAwait(false);
if (formattedDocument is null)
{
return sourceText;
}

var isSameVersion = await IsSameDocumentAndVersionAsync(document, formattedDocument, cancellationToken).ConfigureAwait(false);
if (isSameVersion)
Expand Down
11 changes: 7 additions & 4 deletions src/MSBuild/LooseVersionAssemblyLoader.cs
Expand Up @@ -69,10 +69,13 @@ public static void Register(string searchPath)
}
catch
{
// We were unable to load the assembly from the file path. It is likely that
// a different version of the assembly has already been loaded into the context.
// Be forgiving and attempt to load assembly by name without specifying a version.
return context.LoadFromAssemblyName(new AssemblyName(assemblyName.Name));
if (assemblyName.Name != null)
{
// We were unable to load the assembly from the file path. It is likely that
// a different version of the assembly has already been loaded into the context.
// Be forgiving and attempt to load assembly by name without specifying a version.
return context.LoadFromAssemblyName(new AssemblyName(assemblyName.Name));
}
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Program.cs
Expand Up @@ -29,7 +29,7 @@ internal class Program
private static async Task<int> Main(string[] args)
{
var rootCommand = FormatCommand.CreateCommandLineOptions();
rootCommand.Handler = CommandHandler.Create(typeof(Program).GetMethod(nameof(Run)));
rootCommand.Handler = CommandHandler.Create(typeof(Program).GetMethod(nameof(Run))!);

// Parse the incoming args so we can give warnings when deprecated options are used.
s_parseResult = rootCommand.Parse(args);
Expand Down Expand Up @@ -74,7 +74,7 @@ private static async Task<int> Main(string[] args)
currentDirectory = Environment.CurrentDirectory;


string workspaceDirectory;
string? workspaceDirectory;
string workspacePath;
WorkspaceType workspaceType;

Expand Down
2 changes: 1 addition & 1 deletion src/Reflection/RemoveUnnecessaryImportsHelper.cs
Expand Up @@ -13,7 +13,7 @@ internal static class RemoveUnnecessaryImportsHelper
private static readonly Type? s_abstractRemoveUnnecessaryImportsCodeFixProviderType = s_microsoftCodeAnalysisFeaturesAssembly?.GetType("Microsoft.CodeAnalysis.RemoveUnnecessaryImports.AbstractRemoveUnnecessaryImportsCodeFixProvider");
private static readonly MethodInfo? s_removeUnnecessaryImportsAsyncMethod = s_abstractRemoveUnnecessaryImportsCodeFixProviderType?.GetMethod("RemoveUnnecessaryImportsAsync", BindingFlags.Static | BindingFlags.NonPublic);

public static async Task<Document> RemoveUnnecessaryImportsAsync(Document document, CancellationToken cancellationToken)
public static async Task<Document?> RemoveUnnecessaryImportsAsync(Document document, CancellationToken cancellationToken)
{
if (s_removeUnnecessaryImportsAsyncMethod is null)
{
Expand Down
2 changes: 1 addition & 1 deletion src/ReportWriter.cs
Expand Up @@ -15,7 +15,7 @@ public static void Write(string reportPath, IEnumerable<FormattedFile> formatted
var reportFilePath = GetReportFilePath(reportPath);
var reportFolderPath = Path.GetDirectoryName(reportFilePath);

if (!Directory.Exists(reportFolderPath))
if (reportFolderPath != null && !Directory.Exists(reportFolderPath))
{
Directory.CreateDirectory(reportFolderPath);
}
Expand Down

0 comments on commit d73e027

Please sign in to comment.