Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
24 changes: 15 additions & 9 deletions ExhaustiveMatching.Analyzer.Enums/Analysis/SwitchOnEnumAnalyzer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using ExhaustiveMatching.Analyzer.Enums.Semantics;
using ExhaustiveMatching.Analyzer.Enums.Utility;
Expand All @@ -26,14 +27,19 @@ public static IEnumerable<ISymbol> UnusedEnumValues(
// SortedSet. Both of those use more memory and have more overhead. Hash of primitive
// types is not normally well distributed. It is expected that the values used will
// rarely contain duplicates.
var valuesUsed = caseExpressions.Select(e => GetEnumCaseValue(context, e, enumType))
.WhereNotNull().ToArray();
var valuesUsed = caseExpressions
.Select(e => GetEnumCaseValue(context, e, enumType))
.WhereNotNull()
.ToArray();

Array.Sort(valuesUsed);

var allSymbols = enumType.GetMembers().OfType<IFieldSymbol>();

// Use where instead of Except because we have a set
return allSymbols.Where(s => !SortedArrayContains(valuesUsed, s.ConstantValue));
// Use `Where` instead of `Except` because we have a set
return allSymbols
.Where(s => s.ConstantValue != null)
.Where(s => !SortedArrayContains(valuesUsed, s.ConstantValue!));
}

/// <summary>
Expand All @@ -42,16 +48,16 @@ public static IEnumerable<ISymbol> UnusedEnumValues(
/// <remarks>Case expressions can contain errors. They can also be various forms of literal
/// zero where the type won't match the underlying type of the enum. This deals with all
/// of that.</remarks>
private static object GetEnumCaseValue(
private static object? GetEnumCaseValue(
SyntaxNodeAnalysisContext context,
ExpressionSyntax expression,
INamedTypeSymbol enumType)
{
var underlyingType = enumType.EnumUnderlyingType.SpecialType;
var underlyingType = enumType.EnumUnderlyingType?.SpecialType ?? SpecialType.None;
return GetEnumCaseValue(context.SemanticModel, expression, underlyingType.ToTypeCode());
}

private static object GetEnumCaseValue(
private static object? GetEnumCaseValue(
SemanticModel semanticModel,
ExpressionSyntax expression,
TypeCode typeCode)
Expand All @@ -78,12 +84,12 @@ private static object GetEnumCaseValue(
/// <remarks>There seems to be no built in way to try a conversion. Without writing
/// custom converter code for every pair of types, the only option is to catch the exception
/// from <see cref="Convert.ChangeType(object,Type)"/></remarks>
private static bool TryChangeType(object value, TypeCode typeCode, out object converted)
private static bool TryChangeType(object value, TypeCode typeCode, [NotNullWhen(true)] out object? converted)
{
try
{
converted = Convert.ChangeType(value, typeCode);
return true;
return converted != null;
}
catch
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze
| GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterSyntaxNodeAction(AnalyzeSwitchStatement, SyntaxKind.SwitchStatement);
//context.RegisterSyntaxNodeAction(AnalyzeSwitchExpression, SyntaxKind.SwitchExpression);
}
Expand All @@ -37,7 +36,7 @@ private void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context)
// Include stack trace info by ToString() the exception as part of the message.
// Only the first line is included, so we have to remove newlines
var exDetails = Regex.Replace(ex.ToString(), @"\r\n?|\n|\r", " ");
throw new Exception($"Uncaught exception in analyzer: {exDetails}");
throw new Exception($"Uncaught exception in analyzer: {exDetails}", innerException: ex);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<TargetFrameworks>netstandard2.0;netstandard2.1;</TargetFrameworks>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="1.3.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.9.0" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,20 @@ public static class SyntaxNodeAnalysisContextExtensions
/// <summary>
/// Get the type of an expression.
/// </summary>
public static ITypeSymbol GetExpressionType(
public static ITypeSymbol? GetExpressionType(
this SyntaxNodeAnalysisContext context,
ExpressionSyntax switchStatementExpression)
=> context.SemanticModel.GetTypeInfo(switchStatementExpression, context.CancellationToken).Type;

/// <summary>
/// Get the converted type of an expression.
/// </summary>
public static ITypeSymbol GetExpressionConvertedType(
public static ITypeSymbol? GetExpressionConvertedType(
this SyntaxNodeAnalysisContext context,
ExpressionSyntax switchStatementExpression) =>
context.SemanticModel.GetTypeInfo(switchStatementExpression, context.CancellationToken).ConvertedType;

public static ISymbol GetSymbol(this SyntaxNodeAnalysisContext context, ExpressionSyntax expression)
public static ISymbol? GetSymbol(this SyntaxNodeAnalysisContext context, ExpressionSyntax expression)
=> context.SemanticModel.GetSymbolInfo(expression, context.CancellationToken).Symbol;
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Diagnostics.CodeAnalysis;
using System.ComponentModel;
using System.Linq;
using Microsoft.CodeAnalysis;
Expand All @@ -20,7 +21,7 @@ public static bool IsInvalidEnumArgumentException(this ITypeSymbol typeSymbol)
public static bool IsEnum(
this ITypeSymbol type,
SyntaxNodeAnalysisContext context,
out INamedTypeSymbol enumType,
[NotNullWhen(true)] out INamedTypeSymbol? enumType,
out bool nullable)
{
switch (type.TypeKind)
Expand All @@ -31,7 +32,7 @@ public static bool IsEnum(
return true;
case TypeKind.Struct:
var nullableType = context.Compilation.GetTypeByMetadataName(TypeNames.Nullable);
if (type.OriginalDefinition.Equals(nullableType))
if (SymbolEqualityComparer.IncludeNullability.Equals(type.OriginalDefinition, nullableType))
{
type = ((INamedTypeSymbol)type).TypeArguments.Single();
if (type.TypeKind == TypeKind.Enum)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ namespace ExhaustiveMatching.Analyzer.Enums.Syntax
public static class ThrowStatementSyntaxExtensions
{
/// <summary>
/// The type of the expression being thrown.
/// Returns the <see cref="ITypeParameterSymbol"/> for type being thrown by <paramref name="throwStatement"/>, if determinable, otherwise <see langword="null"/>.
/// </summary>
/// <returns>The type being thrown or <see langword="null"/> if it can't
/// be determined (e.g. compile error).</returns>
public static ITypeSymbol ThrowsType(this ThrowStatementSyntax throwStatement, SyntaxNodeAnalysisContext context)
public static ITypeSymbol? ThrowsType(this ThrowStatementSyntax throwStatement, SyntaxNodeAnalysisContext context)
{
if (throwStatement.Expression is null) return null;
var exceptionType = context.GetExpressionType(throwStatement.Expression);
if (exceptionType == null || exceptionType is IErrorTypeSymbol)
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,8 @@ namespace ExhaustiveMatching.Analyzer.Enums.Utility
{
public static class EnumerableExtensions
{
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> values)
=> new HashSet<T>(values);
public static IReadOnlyList<T> ToReadOnlyList<T>(this IEnumerable<T> values) => values.ToList();

public static IReadOnlyList<T> ToReadOnlyList<T>(this IEnumerable<T> values)
=> values.ToList().AsReadOnly();

public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> values)
where T : class
=> values.Where(v => v != null);
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> values) where T : class => values.Where(v => v != null)!;
}
}
209 changes: 209 additions & 0 deletions ExhaustiveMatching.Analyzer.Enums/Utility/NullableAttributes.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
// https://www.meziantou.net/how-to-use-nullable-reference-types-in-dotnet-standard-2-0-and-dotnet-.htm
// https://github.com/dotnet/runtime/blob/527f9ae88a0ee216b44d556f9bdc84037fe0ebda/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis/NullableAttributes.cs

#pragma warning disable
#define INTERNAL_NULLABLE_ATTRIBUTES

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace System.Diagnostics.CodeAnalysis
{
#if NETSTANDARD2_0 || NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48
/// <summary>Specifies that null is allowed as an input even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class AllowNullAttribute : Attribute
{ }

/// <summary>Specifies that null is disallowed as an input even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class DisallowNullAttribute : Attribute
{ }

/// <summary>Specifies that an output may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class MaybeNullAttribute : Attribute
{ }

/// <summary>Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class NotNullAttribute : Attribute
{ }

/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class MaybeNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter may be null.
/// </param>
public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;

/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}

/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter will not be null even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class NotNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;

/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}

/// <summary>Specifies that the output will be non-null if the named parameter is non-null.</summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class NotNullIfNotNullAttribute : Attribute
{
/// <summary>Initializes the attribute with the associated parameter name.</summary>
/// <param name="parameterName">
/// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null.
/// </param>
public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;

/// <summary>Gets the associated parameter name.</summary>
public string ParameterName { get; }
}

/// <summary>Applied to a method that will never return under any circumstance.</summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class DoesNotReturnAttribute : Attribute
{ }

/// <summary>Specifies that the method will not return if the associated Boolean parameter is passed the specified value.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class DoesNotReturnIfAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified parameter value.</summary>
/// <param name="parameterValue">
/// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to
/// the associated parameter matches this value.
/// </param>
public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;

/// <summary>Gets the condition parameter value.</summary>
public bool ParameterValue { get; }
}
#endif

#if NETSTANDARD2_0 || NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 || NETCOREAPP3_0 || NETCOREAPP3_1 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48
/// <summary>Specifies that the method or property will ensure that the listed field and property members have not-null values.</summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class MemberNotNullAttribute : Attribute
{
/// <summary>Initializes the attribute with a field or property member.</summary>
/// <param name="member">
/// The field or property member that is promised to be not-null.
/// </param>
public MemberNotNullAttribute(string member) => Members = new[] { member };

/// <summary>Initializes the attribute with the list of field and property members.</summary>
/// <param name="members">
/// The list of field and property members that are promised to be not-null.
/// </param>
public MemberNotNullAttribute(params string[] members) => Members = members;

/// <summary>Gets field or property member names.</summary>
public string[] Members { get; }
}

/// <summary>Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition.</summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class MemberNotNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition and a field or property member.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
/// <param name="member">
/// The field or property member that is promised to be not-null.
/// </param>
public MemberNotNullWhenAttribute(bool returnValue, string member)
{
ReturnValue = returnValue;
Members = new[] { member };
}

/// <summary>Initializes the attribute with the specified return value condition and list of field and property members.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
/// <param name="members">
/// The list of field and property members that are promised to be not-null.
/// </param>
public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
{
ReturnValue = returnValue;
Members = members;
}

/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }

/// <summary>Gets field or property member names.</summary>
public string[] Members { get; }
}
#endif
}
Loading