Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable nullable reference types for the repo #3021

Merged
merged 30 commits into from
Nov 26, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
e29e3a1
Enable nullable on repo
mavasani Nov 7, 2019
a5b448a
Annotate Utilities with nullable annotation
mavasani Nov 7, 2019
b424db6
Restrict nullable enable to only shipping projects for now.
mavasani Nov 7, 2019
6398f5f
Nullable annotations in Metrics project
mavasani Nov 7, 2019
05bdcfa
Nullable annotations for Roslyn.Diagnostics.Analyzers
mavasani Nov 7, 2019
abecfb2
Nullable annotations for Microsoft.CodeAnalysis.Analyzers
mavasani Nov 7, 2019
73aaa1b
Nullable annotations for BannedApiAnalyzers
mavasani Nov 7, 2019
bb439cb
Nullable annotations for PublicApiAnalyzers
mavasani Nov 7, 2019
6f36f66
Disable nullable for MetaCompilation.Analyzers
mavasani Nov 7, 2019
e1afae9
Nullable annotations for PerformanceSensitiveAnalyzers
mavasani Nov 7, 2019
669b773
Nullable annotation for internal flow analysis utilties
mavasani Nov 7, 2019
1c344c2
Nullable annotations for Microsoft.CodeQuality.Analyzers
mavasani Nov 7, 2019
a2531f3
Some more nullable annotations for utilities
mavasani Nov 7, 2019
9090966
Additional nullable annotations to a code quality analyzer
mavasani Nov 7, 2019
2404ec0
Add nullable annotations for Microsoft.NetCore.Analyzers
mavasani Nov 7, 2019
28efa04
Add nullable annotations for ReleaseNotesUtil
mavasani Nov 8, 2019
de1b692
Add nullable annotations for GenerateAnalyzerRulesets
mavasani Nov 8, 2019
3591255
Fix a unit test failure from incorrect refactoring
mavasani Nov 8, 2019
404f9cc
Disable nullable in TestReferenceAssembly
mavasani Nov 8, 2019
c72761d
Add nullable annotations for Microsoft.NetFramework.Analyzers
mavasani Nov 8, 2019
64aa452
Add some more missing nullable annotations found after building the e…
mavasani Nov 8, 2019
614dde0
Address feedback for symbol extensions
mavasani Nov 8, 2019
b5b948d
Address feedback
mavasani Nov 8, 2019
4fdc7cc
Minor fix
mavasani Nov 8, 2019
a645fc3
Fix unit tests
mavasani Nov 8, 2019
9c1ee5b
Address feedback from Sam
mavasani Nov 16, 2019
0339d37
Merge remote-tracking branch 'upstream/2.9.x' into NullableReferenceT…
mavasani Nov 16, 2019
533b93e
Some more fixes
mavasani Nov 16, 2019
099e504
Merge remote-tracking branch 'upstream/2.9.x' into NullableReferenceT…
mavasani Nov 25, 2019
cbe55d1
Add nullable annotations after merging latest
mavasani Nov 25, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<PropertyGroup>
<LangVersion Condition="'$(Language)' == 'C#'">8</LangVersion>
<LangVersion Condition="'$(Language)' == 'VB'">16</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public override void Initialize(AnalysisContext context)
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(compilationContext =>
{
if (!DisposeAnalysisHelper.TryGetOrCreate(compilationContext.Compilation, out DisposeAnalysisHelper disposeAnalysisHelper))
if (!DisposeAnalysisHelper.TryGetOrCreate(compilationContext.Compilation, out var disposeAnalysisHelper))
{
return;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Utilities/Compiler/Analyzer.Utilities.projitems
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IOperationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ITypeSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\StringExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolVisibility.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\UriExtensions.cs" />
Expand All @@ -70,6 +69,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Options\AnalyzerOptionsExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\CategorizedAnalyzerConfigOptions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfigParser.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NullableAttributes.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SymbolDisplayFormats.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FxCopWellKnownDiagnosticTags.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UnusedValue.cs" />
Expand Down
14 changes: 7 additions & 7 deletions src/Utilities/Compiler/BoundedCacheWithFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ internal class BoundedCacheWithFactory<TKey, TValue>
{
// Bounded weak reference cache.
// Size 5 is an arbitrarily chosen bound, which can be tuned in future as required.
private readonly List<WeakReference<Entry>> _weakReferencedEntries
= new List<WeakReference<Entry>> {
new WeakReference<Entry>(null),
new WeakReference<Entry>(null),
new WeakReference<Entry>(null),
new WeakReference<Entry>(null),
new WeakReference<Entry>(null),
private readonly List<WeakReference<Entry?>> _weakReferencedEntries
= new List<WeakReference<Entry?>> {
new WeakReference<Entry?>(null),
new WeakReference<Entry?>(null),
new WeakReference<Entry?>(null),
new WeakReference<Entry?>(null),
new WeakReference<Entry?>(null),
};

public TValue GetOrCreateValue(TKey key, Func<TKey, TValue> valueFactory)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ internal static async Task<AssemblyMetricData> ComputeAsync(IAssemblySymbol asse
MetricsHelper.AddCoupledNamedTypes(coupledTypesBuilder, child.CoupledNamedTypes);
linesOfCode += child.SourceLines;
cyclomaticComplexity += child.CyclomaticComplexity;
depthOfInheritance = Math.Max(child.DepthOfInheritance.Value, depthOfInheritance);
depthOfInheritance = Math.Max(child.DepthOfInheritance.GetValueOrDefault(), depthOfInheritance);

// Compat: Maintainability index of an assembly is computed based on the values of types, not namespace children.
Debug.Assert(child.Symbol.Kind == SymbolKind.Namespace);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ internal static async Task<NamedTypeMetricData> ComputeAsync(INamedTypeSymbol na

ImmutableHashSet<IFieldSymbol> getFilteredFieldsForComplexity()
{
ImmutableHashSet<IFieldSymbol>.Builder builderOpt = null;
ImmutableHashSet<IFieldSymbol>.Builder? builderOpt = null;
var orderedFieldDatas = children.Where(c => c.Symbol.Kind == SymbolKind.Field).OrderBy(c => c.MaintainabilityIndex);
var indexThreshold = 99;
foreach (CodeAnalysisMetricData fieldData in orderedFieldDatas)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ internal static async Task<NamespaceMetricData> ComputeAsync(INamespaceSymbol @n
MetricsHelper.AddCoupledNamedTypes(coupledTypesBuilder, child.CoupledNamedTypes);
maintainabilityIndexTotal += child.MaintainabilityIndex;
cyclomaticComplexity += child.CyclomaticComplexity;
depthOfInheritance = Math.Max(child.DepthOfInheritance.Value, depthOfInheritance);
depthOfInheritance = Math.Max(child.DepthOfInheritance.GetValueOrDefault(), depthOfInheritance);

// Avoid double counting lines for nested types.
if (child.Symbol.ContainingType == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ internal CodeAnalysisMetricData(
int? depthOfInheritance,
ImmutableArray<CodeAnalysisMetricData> children)
{
Debug.Assert(symbol != null);
Debug.Assert(
symbol.Kind == SymbolKind.Assembly ||
symbol.Kind == SymbolKind.Namespace ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,19 +89,17 @@ private static ComputationalComplexityMetrics Create(

public static ComputationalComplexityMetrics Compute(IOperation operationBlock)
{
Debug.Assert(operationBlock != null);

bool hasSymbolInitializer = false;
long executableLinesOfCode = 0;
long operatorUsageCounts = 0;
long symbolUsageCounts = 0;
long constantUsageCounts = 0;
ImmutableHashSet<OperationKind>.Builder distinctOperatorKindsBuilder = null;
ImmutableHashSet<BinaryOperatorKind>.Builder distinctBinaryOperatorKindsBuilder = null;
ImmutableHashSet<UnaryOperatorKind>.Builder distinctUnaryOperatorKindsBuilder = null;
ImmutableHashSet<CaseKind>.Builder distinctCaseKindsBuilder = null;
ImmutableHashSet<ISymbol>.Builder distinctReferencedSymbolsBuilder = null;
ImmutableHashSet<object>.Builder distinctReferencedConstantsBuilder = null;
ImmutableHashSet<OperationKind>.Builder? distinctOperatorKindsBuilder = null;
ImmutableHashSet<BinaryOperatorKind>.Builder? distinctBinaryOperatorKindsBuilder = null;
ImmutableHashSet<UnaryOperatorKind>.Builder? distinctUnaryOperatorKindsBuilder = null;
ImmutableHashSet<CaseKind>.Builder? distinctCaseKindsBuilder = null;
ImmutableHashSet<ISymbol>.Builder? distinctReferencedSymbolsBuilder = null;
ImmutableHashSet<object>.Builder? distinctReferencedConstantsBuilder = null;

// Explicit user applied attribute.
if (operationBlock.Kind == OperationKind.None &&
Expand Down
9 changes: 3 additions & 6 deletions src/Utilities/Compiler/DiagnosticHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ public static bool TryConvertToUInt64(object value, SpecialType specialType, out

internal static bool TryGetEnumMemberValues(INamedTypeSymbol enumType, out IList<ulong> values)
{
Debug.Assert(enumType != null);
Debug.Assert(enumType.TypeKind == TypeKind.Enum);

values = new List<ulong>();
Expand Down Expand Up @@ -115,12 +114,10 @@ internal static bool TryGetEnumMemberValues(INamedTypeSymbol enumType, out IList
public static string GetMemberName(ISymbol symbol)
{
// For Types
if (symbol.Kind == SymbolKind.NamedType)
if (symbol is INamedTypeSymbol namedType &&
namedType.IsGenericType)
{
if ((symbol as INamedTypeSymbol).IsGenericType)
{
return symbol.MetadataName;
}
return symbol.MetadataName;
}

// For other language constructs
Expand Down
14 changes: 7 additions & 7 deletions src/Utilities/Compiler/DoNotCatchGeneralUnlessRethrown.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ namespace Analyzer.Utilities
internal abstract class DoNotCatchGeneralUnlessRethrownAnalyzer : DiagnosticAnalyzer
{
private readonly bool _shouldCheckLambdas;
private readonly string _enablingMethodAttributeFullyQualifiedName;
private readonly string? _enablingMethodAttributeFullyQualifiedName;

private bool RequiresAttributeOnMethod => !string.IsNullOrEmpty(_enablingMethodAttributeFullyQualifiedName);

protected DoNotCatchGeneralUnlessRethrownAnalyzer(bool shouldCheckLambdas, string enablingMethodAttributeFullyQualifiedName = null)
protected DoNotCatchGeneralUnlessRethrownAnalyzer(bool shouldCheckLambdas, string? enablingMethodAttributeFullyQualifiedName = null)
{
_shouldCheckLambdas = shouldCheckLambdas;
_enablingMethodAttributeFullyQualifiedName = enablingMethodAttributeFullyQualifiedName;
Expand All @@ -40,7 +40,7 @@ public override void Initialize(AnalysisContext analysisContext)

analysisContext.RegisterCompilationStartAction(compilationStartAnalysisContext =>
{
INamedTypeSymbol requiredAttributeType = null;
INamedTypeSymbol? requiredAttributeType = null;
if (RequiresAttributeOnMethod && (requiredAttributeType = GetRequiredAttributeType(compilationStartAnalysisContext.Compilation)) == null)
{
return;
Expand All @@ -61,7 +61,7 @@ bool IsDisallowedCatchType(INamedTypeSymbol type) =>

var method = (IMethodSymbol)operationBlockAnalysisContext.OwningSymbol;

if (RequiresAttributeOnMethod && !MethodHasAttribute(method, requiredAttributeType))
if (RequiresAttributeOnMethod && !MethodHasAttribute(method, requiredAttributeType!))
{
return;
}
Expand All @@ -80,9 +80,9 @@ bool IsDisallowedCatchType(INamedTypeSymbol type) =>
});
}

private INamedTypeSymbol GetRequiredAttributeType(Compilation compilation)
private INamedTypeSymbol? GetRequiredAttributeType(Compilation compilation)
{
return compilation.GetOrCreateTypeByMetadataName(_enablingMethodAttributeFullyQualifiedName);
return compilation.GetOrCreateTypeByMetadataName(_enablingMethodAttributeFullyQualifiedName!);
}

private bool MethodHasAttribute(IMethodSymbol method, INamedTypeSymbol attributeType)
Expand All @@ -97,7 +97,7 @@ private static IReadOnlyCollection<INamedTypeSymbol> GetDisallowedCatchTypes(Com
compilation.GetSpecialType(SpecialType.System_Object),
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemException),
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSystemException)
}.Where(x => x != null));
}.WhereNotNull());
}

/// <summary>
Expand Down
7 changes: 4 additions & 3 deletions src/Utilities/Compiler/Extensions/CompilationExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Linq;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis;

namespace Analyzer.Utilities.Extensions
Expand All @@ -14,7 +15,7 @@ internal static class CompilationExtensions
/// <param name="compilation">The compilation.</param>
/// <param name="fullTypeName">Namespace + type name, e.g. "System.Exception".</param>
/// <returns>The <see cref="INamedTypeSymbol"/> if found, null otherwise.</returns>
internal static INamedTypeSymbol GetOrCreateTypeByMetadataName(this Compilation compilation, string fullTypeName) =>
internal static INamedTypeSymbol? GetOrCreateTypeByMetadataName(this Compilation compilation, string fullTypeName) =>
WellKnownTypeProvider.GetOrCreate(compilation).GetOrCreateTypeByMetadataName(fullTypeName);

/// <summary>
Expand All @@ -23,7 +24,7 @@ internal static INamedTypeSymbol GetOrCreateTypeByMetadataName(this Compilation
/// <param name="compilation">The compilation.</param>
/// <param name="fullTypeName">Namespace + type name, e.g. "System.Exception".</param>
/// <returns>The <see cref="INamedTypeSymbol"/> if found, null otherwise.</returns>
internal static bool TryGetOrCreateTypeByMetadataName(this Compilation compilation, string fullTypeName, out INamedTypeSymbol namedTypeSymbol) =>
internal static bool TryGetOrCreateTypeByMetadataName(this Compilation compilation, string fullTypeName, [NotNullWhen(returnValue: true)] out INamedTypeSymbol? namedTypeSymbol) =>
WellKnownTypeProvider.GetOrCreate(compilation).TryGetOrCreateTypeByMetadataName(fullTypeName, out namedTypeSymbol);
}
}
6 changes: 3 additions & 3 deletions src/Utilities/Compiler/Extensions/DiagnosticExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public static Diagnostic CreateDiagnostic(
{
if (!location.IsInSource)
{
location = null;
location = Location.None;
}

return Diagnostic.Create(
Expand Down Expand Up @@ -158,7 +158,7 @@ public static Diagnostic CreateDiagnostic(
public static Diagnostic CreateDiagnostic(
this IEnumerable<Location> locations,
DiagnosticDescriptor rule,
ImmutableDictionary<string, string> properties,
ImmutableDictionary<string, string>? properties,
params object[] args)
{
IEnumerable<Location> inSource = locations.Where(l => l.IsInSource);
Expand Down Expand Up @@ -197,7 +197,7 @@ public static void ReportNoLocationDiagnostic(
this Compilation compilation,
DiagnosticDescriptor rule,
Action<Diagnostic> addDiagnostic,
ImmutableDictionary<string, string> properties,
ImmutableDictionary<string, string>? properties,
params object[] args)
{
var effectiveSeverity = GetEffectiveSeverity();
Expand Down
10 changes: 5 additions & 5 deletions src/Utilities/Compiler/Extensions/IEnumerableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,16 @@ public static IEnumerable<T> Order<T>(this IEnumerable<T> source) where T : ICom
return source.OrderBy((t1, t2) => t1.CompareTo(t2));
}

private static readonly Func<object, bool> s_notNullTest = x => x != null;
private static readonly Func<object?, bool> s_notNullTest = x => x != null;

public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> source) where T : class
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : class
{
if (source == null)
{
return ImmutableArray<T>.Empty;
}

return source.Where((Func<T, bool>)s_notNullTest);
return source.Where((Func<T?, bool>)s_notNullTest)!;
}

public static ImmutableArray<TSource> WhereAsArray<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> selector)
Expand All @@ -95,8 +95,8 @@ public static ImmutableArray<TSource> WhereAsArray<TSource>(this IEnumerable<TSo
}
}

public static void Dispose<T>(this IEnumerable<T> collection)
where T : IDisposable
public static void Dispose<T>(this IEnumerable<T?> collection)
where T : class, IDisposable
{
foreach (var item in collection)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public static IEnumerable<IMethodSymbol> GetMethodOverloadsWithDesiredParameterA
/// <param name="members"></param>
/// <param name="expectedParameterTypesInOrder"></param>
/// <returns></returns>
public static IMethodSymbol GetFirstOrDefaultMemberWithParameterInfos(this IEnumerable<IMethodSymbol> members, params ParameterInfo[] expectedParameterTypesInOrder)
public static IMethodSymbol? GetFirstOrDefaultMemberWithParameterInfos(this IEnumerable<IMethodSymbol> members, params ParameterInfo[] expectedParameterTypesInOrder)
{
var expectedParameterCount = expectedParameterTypesInOrder.Length;
return members?.FirstOrDefault(member =>
Expand Down
Loading