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

Handle unsupported diagnostics reported by analyzers #1286

Merged
merged 2 commits into from
Mar 17, 2015
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 @@ -133,7 +133,7 @@ internal override Diagnostic WithSeverity(DiagnosticSeverity severity)
private class ComplainAboutX : DiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor s_CA9999_UseOfVariableThatStartsWithX =
new DiagnosticDescriptor(id: "CA9999", title: "CA9999_UseOfVariableThatStartsWithX", messageFormat: "Use of variable whose name starts with 'x': '{0}'", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true);
new DiagnosticDescriptor(id: "CA9999_UseOfVariableThatStartsWithX", title: "CA9999_UseOfVariableThatStartsWithX", messageFormat: "Use of variable whose name starts with 'x': '{0}'", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true);

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
Expand All @@ -153,7 +153,7 @@ private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
var id = (IdentifierNameSyntax)context.Node;
if (id.Identifier.ValueText.StartsWith("x", StringComparison.Ordinal))
{
context.ReportDiagnostic(new TestDiagnostic("CA9999_UseOfVariableThatStartsWithX", "CsTest", DiagnosticSeverity.Warning, id.Location, "Use of variable whose name starts with 'x': '{0}'", id.Identifier.ValueText));
context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(s_CA9999_UseOfVariableThatStartsWithX, id.Location, id.Identifier.ValueText));
}
}
}
Expand Down Expand Up @@ -935,5 +935,45 @@ public override void Initialize(AnalysisContext context)
}, SymbolKind.Method);
}
}

[Fact, WorkItem(252, "https://github.com/dotnet/roslyn/issues/252")]
public void TestReportingUnsupportedDiagnostic()
{
string source = @"";
var analyzers = new DiagnosticAnalyzer[] { new AnalyzerReportingUnsupportedDiagnostic() };

CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(analyzers, null, null, logAnalyzerExceptionAsDiagnostics: true,
expected: Diagnostic("AD0001")
.WithArguments("Microsoft.CodeAnalysis.CSharp.UnitTests.DiagnosticAnalyzerTests+AnalyzerReportingUnsupportedDiagnostic",
@"Reported diagnostic with ID 'ID_2' is not supported by the analyzer.
Parameter name: diagnostic")
.WithLocation(1, 1));
}

[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class AnalyzerReportingUnsupportedDiagnostic : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor SupportedDescriptor =
new DiagnosticDescriptor("ID_1", "DummyTitle", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true);

public static readonly DiagnosticDescriptor UnsupportedDescriptor =
new DiagnosticDescriptor("ID_2", "DummyTitle", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true);

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(SupportedDescriptor);
}
}

public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
compilationContext.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(UnsupportedDescriptor, Location.None)));
}
}
}
}
46 changes: 37 additions & 9 deletions src/Compilers/Core/AnalyzerDriver/AnalyzerExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ internal class AnalyzerExecutor
private readonly AnalyzerOptions _analyzerOptions;
private readonly Action<Diagnostic> _addDiagnostic;
private readonly Action<Exception, DiagnosticAnalyzer, Diagnostic> _onAnalyzerException;
private readonly AnalyzerManager _analyzerManager;
private readonly Func<DiagnosticAnalyzer, bool> _isCompilerAnalyzer;
private readonly CancellationToken _cancellationToken;

/// <summary>
/// Creates AnalyzerActionsExecutor to execute analyzer actions with given arguments
/// Creates <see cref="AnalyzerExecutor"/> to execute analyzer actions with given arguments
/// </summary>
/// <param name="compilation">Compilation to be used in the analysis.</param>
/// <param name="analyzerOptions">Analyzer options.</param>
Expand All @@ -36,34 +38,43 @@ internal class AnalyzerExecutor
/// Optional delegate which is invoked when an analyzer throws an exception.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the name AnalyzerActionsExecutor in the <summary> element above up-to-date? Consider using cref for it.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The same question about <summary> here.

/// Delegate can do custom tasks such as report the given analyzer exception diagnostic, report a non-fatal watson for the exception, etc.
/// </param>
/// <param name="isCompilerAnalyzer">Delegate to determine if the given analyzer is compiler analyzer.
/// We need to special case the compiler analyzer at few places for performance reasons.</param>
/// <param name="analyzerManager">Analyzer manager to fetch supported diagnostics.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public static AnalyzerExecutor Create(
Compilation compilation,
AnalyzerOptions analyzerOptions,
Action<Diagnostic> addDiagnostic,
Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException,
Func<DiagnosticAnalyzer, bool> isCompilerAnalyzer,
AnalyzerManager analyzerManager,
CancellationToken cancellationToken)
{
return new AnalyzerExecutor(compilation, analyzerOptions, addDiagnostic, onAnalyzerException, cancellationToken);
return new AnalyzerExecutor(compilation, analyzerOptions, addDiagnostic, onAnalyzerException, isCompilerAnalyzer, analyzerManager, cancellationToken);
}

/// <summary>
/// Creates AnalyzerActionsExecutor to fetch <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/>.
/// Creates <see cref="AnalyzerExecutor"/> to fetch <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/>.
/// </summary>
/// <param name="onAnalyzerException">
/// Optional delegate which is invoked when an analyzer throws an exception.
/// Delegate can do custom tasks such as report the given analyzer exception diagnostic, report a non-fatal watson for the exception, etc.
/// </param>
/// <param name="analyzerManager">Analyzer manager to fetch supported diagnostics.</param>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the manager providing supported diagnostics or diagnostic identifiers?

/// <param name="cancellationToken">Cancellation token.</param>
public static AnalyzerExecutor CreateForSupportedDiagnostics(
Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException,
AnalyzerManager analyzerManager,
CancellationToken cancellationToken)
{
return new AnalyzerExecutor(
compilation: null,
analyzerOptions: null,
addDiagnostic: null,
isCompilerAnalyzer: null,
onAnalyzerException: onAnalyzerException,
analyzerManager: analyzerManager,
cancellationToken: cancellationToken);
}

Expand All @@ -72,12 +83,16 @@ private AnalyzerExecutor(
AnalyzerOptions analyzerOptions,
Action<Diagnostic> addDiagnostic,
Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException,
Func<DiagnosticAnalyzer, bool> isCompilerAnalyzer,
AnalyzerManager analyzerManager,
CancellationToken cancellationToken)
{
_compilation = compilation;
_analyzerOptions = analyzerOptions;
_addDiagnostic = addDiagnostic;
_onAnalyzerException = onAnalyzerException;
_isCompilerAnalyzer = isCompilerAnalyzer;
_analyzerManager = analyzerManager;
_cancellationToken = cancellationToken;
}

Expand Down Expand Up @@ -127,7 +142,8 @@ public void ExecuteCompilationActions(ImmutableArray<CompilationAnalyzerAction>
{
_cancellationToken.ThrowIfCancellationRequested();
ExecuteAndCatchIfThrows(endAction.Analyzer,
() => endAction.Action(new CompilationAnalysisContext(_compilation, _analyzerOptions, _addDiagnostic, _cancellationToken)));
() => endAction.Action(new CompilationAnalysisContext(_compilation, _analyzerOptions, _addDiagnostic,
d => IsSupportedDiagnostic(endAction.Analyzer, d), _cancellationToken)));
}
}

Expand Down Expand Up @@ -172,7 +188,8 @@ public void ExecuteSymbolActions(ImmutableArray<SymbolAnalyzerAction> symbolActi
{
_cancellationToken.ThrowIfCancellationRequested();
ExecuteAndCatchIfThrows(symbolAction.Analyzer,
() => action(new SymbolAnalysisContext(symbol, _compilation, _analyzerOptions, addDiagnostic, _cancellationToken)));
() => action(new SymbolAnalysisContext(symbol, _compilation, _analyzerOptions, addDiagnostic,
d => IsSupportedDiagnostic(symbolAction.Analyzer, d), _cancellationToken)));
}
}
}
Expand Down Expand Up @@ -200,7 +217,8 @@ public void ExecuteSemanticModelActions(ImmutableArray<SemanticModelAnalyzerActi

// Catch Exception from action.
ExecuteAndCatchIfThrows(semanticModelAction.Analyzer,
() => semanticModelAction.Action(new SemanticModelAnalysisContext(semanticModel, _analyzerOptions, _addDiagnostic, _cancellationToken)));
() => semanticModelAction.Action(new SemanticModelAnalysisContext(semanticModel, _analyzerOptions, _addDiagnostic,
d => IsSupportedDiagnostic(semanticModelAction.Analyzer, d), _cancellationToken)));
}
}

Expand All @@ -227,7 +245,8 @@ public void ExecuteSyntaxTreeActions(ImmutableArray<SyntaxTreeAnalyzerAction> sy

// Catch Exception from action.
ExecuteAndCatchIfThrows(syntaxTreeAction.Analyzer,
() => syntaxTreeAction.Action(new SyntaxTreeAnalysisContext(tree, _analyzerOptions, _addDiagnostic, _cancellationToken)));
() => syntaxTreeAction.Action(new SyntaxTreeAnalysisContext(tree, _analyzerOptions, _addDiagnostic,
d => IsSupportedDiagnostic(syntaxTreeAction.Analyzer, d), _cancellationToken)));
}
}

Expand Down Expand Up @@ -265,7 +284,8 @@ private void ExecuteSyntaxNodeAction<TLanguageKindEnum>(
SemanticModel semanticModel)
where TLanguageKindEnum : struct
{
var syntaxNodeContext = new SyntaxNodeAnalysisContext(node, semanticModel, _analyzerOptions, _addDiagnostic, _cancellationToken);
var syntaxNodeContext = new SyntaxNodeAnalysisContext(node, semanticModel, _analyzerOptions, _addDiagnostic,
d => IsSupportedDiagnostic(syntaxNodeAction.Analyzer, d), _cancellationToken);
ExecuteAndCatchIfThrows(syntaxNodeAction.Analyzer, () => syntaxNodeAction.Action(syntaxNodeContext));
}

Expand Down Expand Up @@ -369,7 +389,8 @@ private void ExecuteCodeBlockActions(PooledHashSet<CodeBlockAnalyzerAction> bloc
foreach (var blockAction in blockActions)
{
ExecuteAndCatchIfThrows(blockAction.Analyzer,
() => blockAction.Action(new CodeBlockAnalysisContext(declaredNode, declaredSymbol, semanticModel, _analyzerOptions, _addDiagnostic, _cancellationToken)));
() => blockAction.Action(new CodeBlockAnalysisContext(declaredNode, declaredSymbol, semanticModel, _analyzerOptions, _addDiagnostic,
d => IsSupportedDiagnostic(blockAction.Analyzer, d), _cancellationToken)));
}

blockActions.Free();
Expand Down Expand Up @@ -513,5 +534,12 @@ internal static bool IsAnalyzerExceptionDiagnostic(Diagnostic diagnostic)

return false;
}

private bool IsSupportedDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic)
{
Debug.Assert(_isCompilerAnalyzer != null);

return _analyzerManager.IsSupportedDiagnostic(analyzer, diagnostic, _isCompilerAnalyzer, this);
}
}
}
22 changes: 22 additions & 0 deletions src/Compilers/Core/AnalyzerDriver/AnalyzerManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,28 @@ internal void ClearAnalyzerExceptionHandlers(DiagnosticAnalyzer analyzer)
}
}

internal bool IsSupportedDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Func<DiagnosticAnalyzer, bool> isCompilerAnalyzer, AnalyzerExecutor analyzerExecutor)
{
// Avoid realizing all the descriptors for all compiler diagnostics by assuming that compiler analyzer doesn't report unsupported diagnostics.
if (isCompilerAnalyzer(analyzer))
{
return true;
}

// Get all the supported diagnostics and scan them linearly to see if the reported diagnostic is supported by the analyzer.
// The linear scan is okay, given that this runs only if a diagnostic is being reported and a given analyzer is quite unlikely to have hundreds of thousands of supported diagnostics.
var supportedDescriptors = GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor);
foreach (var descriptor in supportedDescriptors)
{
if (descriptor.Id.Equals(diagnostic.Id, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}

return false;
}

/// <summary>
/// Returns true if all the diagnostics that can be produced by this analyzer are suppressed through options.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,17 @@ internal static void VerifyArguments<TContext, TLanguageKindEnum>(Action<TContex
VerifySyntaxKinds(syntaxKinds);
}

internal static void VerifyArguments(Diagnostic diagnostic)
internal static void VerifyArguments(Diagnostic diagnostic, Func<Diagnostic, bool> isSupportedDiagnostic)
{
if (diagnostic == null)
{
throw new ArgumentNullException(nameof(diagnostic));
}

if (!isSupportedDiagnostic(diagnostic))
{
throw new ArgumentException(string.Format(AnalyzerDriverResources.UnsupportedDiagnosticReported, diagnostic.Id), nameof(diagnostic));
}
}

private static void VerifyAction<TContext>(Action<TContext> action)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ private static void TestDescriptorIsExceptionSafeCore(DiagnosticDescriptor descr
var analyzer = new MyAnalyzer(descriptor);
var exceptionDiagnostics = new List<Diagnostic>();
Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException = (ex, a, diag) => exceptionDiagnostics.Add(diag);
var analyzerExecutor = AnalyzerExecutor.CreateForSupportedDiagnostics(onAnalyzerException, CancellationToken.None);
var analyzerExecutor = AnalyzerExecutor.CreateForSupportedDiagnostics(onAnalyzerException, AnalyzerManager.Instance, CancellationToken.None);
var descriptors = AnalyzerManager.Instance.GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor);

Assert.Equal(1, descriptors.Length);
Expand Down
9 changes: 9 additions & 0 deletions src/Compilers/Core/Portable/CodeAnalysisResources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/Compilers/Core/Portable/CodeAnalysisResources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,9 @@
<data name="ArgumentElementCannotBeNull" xml:space="preserve">
<value>Argument cannot have a null element.</value>
</data>
<data name="UnsupportedDiagnosticReported" xml:space="preserve">
<value>Reported diagnostic with ID '{0}' is not supported by the analyzer.</value>
</data>
<data name="NoBinderException" xml:space="preserve">
<value>Cannot deserialize type '{0}', no binder supplied.</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ internal static AnalyzerDriver Create(
newOnAnalyzerException = (ex, analyzer, diagnostic) => addDiagnostic(diagnostic);
}

var analyzerExecutor = AnalyzerExecutor.Create(newCompilation, options, addDiagnostic, newOnAnalyzerException, cancellationToken);
var analyzerExecutor = AnalyzerExecutor.Create(newCompilation, options, addDiagnostic, newOnAnalyzerException, IsCompilerAnalyzer, analyzerManager, cancellationToken);

analyzerDriver.Initialize(newCompilation, analyzerExecutor, cancellationToken);

Expand Down Expand Up @@ -969,5 +969,6 @@ internal static class AnalyzerDriverResources
internal static string DiagnosticDescriptorThrows => CodeAnalysisResources.DiagnosticDescriptorThrows;
internal static string ArgumentElementCannotBeNull => CodeAnalysisResources.ArgumentElementCannotBeNull;
internal static string ArgumentCannotBeEmpty => CodeAnalysisResources.ArgumentCannotBeEmpty;
internal static string UnsupportedDiagnosticReported => CodeAnalysisResources.UnsupportedDiagnosticReported;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public static bool IsDiagnosticAnalyzerSuppressed(DiagnosticAnalyzer analyzer, C

Action<Exception, DiagnosticAnalyzer, Diagnostic> voidHandler = (ex, a, diag) => { };
onAnalyzerException = onAnalyzerException ?? voidHandler;
var analyzerExecutor = AnalyzerExecutor.CreateForSupportedDiagnostics(onAnalyzerException, CancellationToken.None);
var analyzerExecutor = AnalyzerExecutor.CreateForSupportedDiagnostics(onAnalyzerException, AnalyzerManager.Instance, CancellationToken.None);

return AnalyzerDriver.IsDiagnosticAnalyzerSuppressed(analyzer, options, AnalyzerManager.Instance, analyzerExecutor);
}
Expand Down
Loading