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 authored 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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ private async Task<ImmutableDictionary<ProjectId, ImmutableHashSet<string>>> Get
foreach (var project in solution.Projects)
{
var analyzers = projectAnalyzers[project];
if (analyzers.Length == 0)
if (analyzers.IsEmpty)
{
continue;
}
Expand All @@ -116,13 +116,18 @@ private async Task<ImmutableDictionary<ProjectId, ImmutableHashSet<string>>> Get

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 @@ internal static async Task<ImmutableDictionary<Project, ImmutableArray<Diagnosti
{
// 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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 TryCreateInstance<T>(this Type type, [NotNullWhen(returnValue
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 TryCreateInstance<T>(this Type type, [NotNullWhen(returnValue
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 @@ static bool TryGetSeverityFromCodeStyleOption(
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 @@ static bool TryGetSeverityFromCodeStyleOption(
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 @@ static bool TryGetSeverityFromCodeStyleOption(
}

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
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ internal override Task<SourceText> FormatFileAsync(
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
Original file line number Diff line number Diff line change
@@ -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 override async Task<SourceText> FormatFileAsync(
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 override async Task<SourceText> FormatFileAsync(
// 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
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ internal override async Task<SourceText> FormatFileAsync(
}

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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 @@ public static async Task<int> Run(
currentDirectory = Environment.CurrentDirectory;


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

Expand Down
2 changes: 1 addition & 1 deletion src/Reflection/RemoveUnnecessaryImportsHelper.cs
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Loading

0 comments on commit d73e027

Please sign in to comment.