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

CA1416 Do not warn for OS dependent messages for creating NotSupportedExceptions #4577

Merged
merged 2 commits into from
Dec 16, 2020
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,11 @@ public override void Initialize(AnalysisContext context)
m.ReturnType.Equals(osPlatformType) &&
m.Parameters.Length == 1 &&
m.Parameters[0].Type.SpecialType == SpecialType.System_String).FirstOrDefault();
var notSupportedExceptionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotSupportedException);

context.RegisterOperationBlockStartAction(
context => AnalyzeOperationBlock(context, guardMethods, runtimeIsOSPlatformMethod, osPlatformCreateMethod,
osPlatformTypeArray, stringType, platformSpecificMembers, msBuildPlatforms));
osPlatformTypeArray, stringType, platformSpecificMembers, msBuildPlatforms, notSupportedExceptionType));
});

static ImmutableArray<IMethodSymbol> GetOperatingSystemGuardMethods(IMethodSymbol? runtimeIsOSPlatformMethod, INamedTypeSymbol operatingSystemType)
Expand Down Expand Up @@ -230,15 +231,21 @@ private void AnalyzeOperationBlock(
ImmutableArray<INamedTypeSymbol> osPlatformTypeArray,
INamedTypeSymbol stringType,
ConcurrentDictionary<ISymbol, SmallDictionary<string, PlatformAttributes>?> platformSpecificMembers,
ImmutableArray<string> msBuildPlatforms)
ImmutableArray<string> msBuildPlatforms,
ITypeSymbol? notSupportedExceptionType)
{
if (context.IsMethodNotImplementedOrSupported(checkPlatformNotSupported: true))
{
return;
}

var osPlatformType = osPlatformTypeArray[0];
var platformSpecificOperations = PooledConcurrentDictionary<IOperation, (SmallDictionary<string, PlatformAttributes> attributes,
SmallDictionary<string, PlatformAttributes>? csAttributes)>.GetInstance();

context.RegisterOperationAction(context =>
{
AnalyzeOperation(context.Operation, context, platformSpecificOperations, platformSpecificMembers, msBuildPlatforms);
AnalyzeOperation(context.Operation, context, platformSpecificOperations, platformSpecificMembers, msBuildPlatforms, notSupportedExceptionType);
},
OperationKind.MethodReference,
OperationKind.EventReference,
Expand Down Expand Up @@ -977,8 +984,14 @@ private static ISymbol GetEventAccessor(IEventSymbol iEvent, IOperation operatio

private static void AnalyzeOperation(IOperation operation, OperationAnalysisContext context, PooledConcurrentDictionary<IOperation,
(SmallDictionary<string, PlatformAttributes> attributes, SmallDictionary<string, PlatformAttributes>? csAttributes)> platformSpecificOperations,
ConcurrentDictionary<ISymbol, SmallDictionary<string, PlatformAttributes>?> platformSpecificMembers, ImmutableArray<string> msBuildPlatforms)
ConcurrentDictionary<ISymbol, SmallDictionary<string, PlatformAttributes>?> platformSpecificMembers, ImmutableArray<string> msBuildPlatforms,
ITypeSymbol? notSupportedExceptionType)
{
if (operation.Parent is IArgumentOperation argumentOperation && UsedInCreatingNotSupportedException(argumentOperation, notSupportedExceptionType))
{
return;
}

var symbol = GetOperationSymbol(operation);

if (symbol == null)
Expand Down Expand Up @@ -1038,6 +1051,18 @@ static void CheckOperationAttributes(IOperation operation, OperationAnalysisCont
}
}

private static bool UsedInCreatingNotSupportedException(IArgumentOperation operation, ITypeSymbol? notSupportedExceptionType)
{
if (operation.Parent is IObjectCreationOperation creation &&
operation.Parameter.Type.SpecialType == SpecialType.System_String &&
creation.Type.DerivesFrom(notSupportedExceptionType, baseTypesOnly: true, checkTypeParameterConstraints: false))
{
return true;
}

return false;
}

private static bool TryCopyAttributesNotSuppressedByMsBuild(SmallDictionary<string, PlatformAttributes> operationAttributes,
ImmutableArray<string> msBuildPlatforms, out SmallDictionary<string, PlatformAttributes> copiedAttributes)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1552,7 +1552,7 @@ public void M2()
await VerifyAnalyzerAsyncCs(source);
}

[Fact(Skip = "TODO: Failing because we cannot detect the correct local invocation being called")]
[Fact]
public async Task LocalFunctionCallsPlatformDependentMember_InvokedFromDifferentContext()
{
var source = @"
Expand All @@ -1562,24 +1562,17 @@ public class Test
{
void M()
{
LocalM();
if (OperatingSystemHelper.IsOSPlatformVersionAtLeast(""Windows"", 10, 2))
{
LocalM(true);
LocalM();
}
LocalM(false);
return;

void LocalM(bool suppressed)
void LocalM()
{
if (suppressed)
{
WindowsOnlyMethod();
}
else
{
[|WindowsOnlyMethod()|];
}

[|WindowsOnlyMethod()|];

if (OperatingSystemHelper.IsOSPlatformVersionAtLeast(""Windows"", 10, 2))
{
WindowsOnlyMethod();
Expand All @@ -1595,6 +1588,7 @@ void LocalM(bool suppressed)
}
}
}

[SupportedOSPlatform(""Windows10.1.2.3"")]
public void WindowsOnlyMethod()
{
Expand All @@ -1605,7 +1599,7 @@ public void UnsupportedWindows10()
}
}
" + MockAttributesCsSource + MockOperatingSystemApiSource;
await VerifyAnalyzerAsyncCs(source);
await VerifyAnalyzerAsyncCs(source, s_msBuildPlatforms);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,212 @@ class Target
[SupportedOSPlatform(""windows"")]
public static void WindowsOnlyMethod() { }
}
}
" + MockAttributesCsSource;
}" + MockAttributesCsSource;
await VerifyAnalyzerAsyncCs(source, tfmAndOption);
}

[Fact]
public async Task OnlyThrowsNotSupportedWithOsDependentStringNotWarns()
{
var csSource = @"
using System;
using System.Runtime.Versioning;

[SupportedOSPlatform(""Browser"")]
public class Test
{
private static string s_message = ""Browser not supported"";

[UnsupportedOSPlatform(""browser"")]
public static void ThrowPnseWithStringArgument() { throw new PlatformNotSupportedException(s_message); }

[UnsupportedOSPlatform(""browser"")]
public static void ThrowNotSupportedWithStringArgument() { throw new NotSupportedException(s_message); }

[UnsupportedOSPlatform(""browser"")]
public static void ThrowPnseWithStringAndExceptionArgument() { throw new PlatformNotSupportedException(s_message, new Exception(s_message)); }

[UnsupportedOSPlatform(""browser"")]
public static void ThrowPnseDefaultConstructor() { throw new PlatformNotSupportedException(); }
}" + MockAttributesCsSource;
await VerifyAnalyzerAsyncCs(csSource);
}

[Fact]
public async Task ThrowNotSupportedWithOtherOsDependentApiUsageNotWarns()
{
var csSource = @"
using System;
using System.Runtime.Versioning;
[assembly: SupportedOSPlatform(""browser"")]

public static class SR
{
public static string Message {get; set;}
}

[UnsupportedOSPlatform(""browser"")]
public class Test
{
void ThrowWithStringArgument()
{
[|SR.Message|] = ""Warns not reachable on Browser"";
throw new PlatformNotSupportedException(SR.Message);
}

void ThrowNotSupportedWithStringArgument()
{
[|SR.Message|] = ""Warns not reachable on Browser"";
throw new NotSupportedException(SR.Message);
}

void ThrowWithNoArgument()
{
[|SR.Message|] = ""Warns not reachable on Browser"";
throw new PlatformNotSupportedException();
}

void ThrowWithStringAndExceptionConstructor()
{
[|SR.Message|] = ""Warns not reachable on Browser"";
throw new PlatformNotSupportedException(SR.Message, new Exception());
}

void ThrowWithAnotherExceptionUsingResourceString()
{
[|SR.Message|] = ""Warns not reachable on Browser"";
throw new PlatformNotSupportedException(SR.Message, new Exception([|SR.Message|]));
}
}" + MockAttributesCsSource;
await VerifyAnalyzerAsyncCs(csSource);
}

[Fact]
public async Task ThrowNotSupportedWithOtherStatementAndWithinConditionNotWarns()
{
var csSource = @"
using System;
using System.Runtime.Versioning;

[SupportedOSPlatform(""windows"")]
public static class Windows
{
public static string Message {get; set;}
}

[SupportedOSPlatform(""browser"")]
public static class SR
{
public static string Message {get; set;}
public static void M1() { }
}

public class Test
{
void ThrowWithStringConstructor()
{
[|SR.M1()|];
if (!OperatingSystemHelper.IsBrowser())
{
throw new PlatformNotSupportedException(SR.Message);
}
SR.M1();

[|Windows.Message|] = ""Warns supported only on Windows"";
if (!OperatingSystemHelper.IsWindows())
{
throw new NotSupportedException(Windows.Message);
}
Windows.Message = ""It is windows!"";
}

void ThrowWithOtherConstructorWarnsForInnnerException()
{
[|SR.M1()|];
if (!OperatingSystemHelper.IsBrowser())
{
throw new PlatformNotSupportedException();
}
SR.M1();

[|Windows.Message|] = ""Warns supported only on Windows"";
if (!OperatingSystemHelper.IsWindows())
{
throw new NotSupportedException(Windows.Message, new Exception([|Windows.Message|]));
}
}
}" + MockAttributesCsSource + MockOperatingSystemApiSource;
await VerifyAnalyzerAsyncCs(csSource);
}

[Fact]
public async Task CreateNotSupportedWithOsDependentStringNotWarns()
{
var csSource = @"
using System;
using System.Runtime.Versioning;

[SupportedOSPlatform(""Browser"")]
public class Test
{
private static string s_message = ""Browser not supported"";

[UnsupportedOSPlatform(""browser"")]
public static Exception GetPnseWithStringArgument() { return new PlatformNotSupportedException(s_message); }

[UnsupportedOSPlatform(""browser"")]
public static Exception GetNotSupportedWithStringArgument()
{
[|s_message|] = ""Warns not reachable on Browser"";
return new NotSupportedException(s_message);
}

[UnsupportedOSPlatform(""browser"")]
public static Exception ThrowPnseWithStringWarnsForInnerException()
{
return new PlatformNotSupportedException(s_message, new Exception([|s_message|]));
}

[UnsupportedOSPlatform(""browser"")]
public static Exception ThrowPnseDefaultConstructor() { return new PlatformNotSupportedException(); }
}" + MockAttributesCsSource;
await VerifyAnalyzerAsyncCs(csSource);
}

[Fact]
public async Task ThrowNotSupportedWarnsForNonStringArgument()
{
var csSource = @"
using System;
using System.Runtime.Versioning;

[SupportedOSPlatform(""windows"")]
public class WindowsOnlyException : Exception
{
public WindowsOnlyException() { }
public WindowsOnlyException(string message) { }
public static string Message {get; set;}
}

public class Test
{
void ThrowWindowsOnlyExceptionWarns()
{
[|WindowsOnlyException.Message|] = ""Warns for message and exception"";
throw [|new WindowsOnlyException([|WindowsOnlyException.Message|])|];
}

void ThrowWithWindowsOnlyInnnerExceptionWarns()
{
if (!OperatingSystemHelper.IsWindows())
{
throw new NotSupportedException(WindowsOnlyException.Message, [|new WindowsOnlyException()|]);
}
}
}" + MockAttributesCsSource + MockOperatingSystemApiSource;
await VerifyAnalyzerAsyncCs(csSource);
}

[Fact]
public async Task OsDependentMethodsCalledWarns()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace Analyzer.Utilities.Extensions
internal static class OperationBlockAnalysisContextExtension
{
#pragma warning disable RS1012 // Start action has no registered actions.
public static bool IsMethodNotImplementedOrSupported(this OperationBlockStartAnalysisContext context)
public static bool IsMethodNotImplementedOrSupported(this OperationBlockStartAnalysisContext context, bool checkPlatformNotSupported = false)
#pragma warning restore RS1012 // Start action has no registered actions.
{
// Note that VB method bodies with 1 action have 3 operations.
Expand Down Expand Up @@ -53,8 +53,10 @@ body.Operations[1] is ILabeledOperation labeledOp && labeledOp.IsImplicit &&
descendants[0] is IThrowOperation throwOperation &&
throwOperation.GetThrownExceptionType() is ITypeSymbol createdExceptionType)
{
if (Equals(context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotImplementedException), createdExceptionType.OriginalDefinition)
|| Equals(context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotSupportedException), createdExceptionType.OriginalDefinition))
if (Equals(context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotImplementedException), createdExceptionType.OriginalDefinition) ||
Equals(context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotSupportedException), createdExceptionType.OriginalDefinition) ||
(checkPlatformNotSupported &&
Equals(context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemPlatformNotSupportedException), createdExceptionType.OriginalDefinition)))
{
return true;
}
Expand Down
1 change: 1 addition & 0 deletions src/Utilities/Compiler/WellKnownTypeNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ internal static class WellKnownTypeNames
public const string SystemObsoleteAttribute = "System.ObsoleteAttribute";
public const string SystemOperatingSystem = "System.OperatingSystem";
public const string SystemOutOfMemoryException = "System.OutOfMemoryException";
public const string SystemPlatformNotSupportedException = "System.PlatformNotSupportedException";
public const string SystemRandom = "System.Random";
public const string SystemRange = "System.Range";
public const string SystemReadOnlyMemory1 = "System.ReadOnlyMemory`1";
Expand Down