Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -23,5 +23,8 @@ public sealed class CSharpSymbolIsBannedInAnalyzersAnalyzer : SymbolIsBannedInAn
protected override SyntaxNode GetReferenceSyntaxNodeFromXmlCref(SyntaxNode syntaxNode) => ((XmlCrefAttributeSyntax)syntaxNode).Cref;

protected override IEnumerable<SyntaxNode> GetTypeSyntaxNodesFromBaseType(SyntaxNode syntaxNode) => ((BaseListSyntax)syntaxNode).Types.Select(t => (SyntaxNode)t.Type);

protected override bool IsRegularCommentOrDocumentationComment(SyntaxTrivia trivia)
=> trivia.Kind() is SyntaxKind.SingleLineCommentTrivia or SyntaxKind.MultiLineCommentTrivia or SyntaxKind.ShebangDirectiveTrivia or SyntaxKind.SingleLineDocumentationCommentTrivia or SyntaxKind.MultiLineDocumentationCommentTrivia;
Copy link
Member

Choose a reason for hiding this comment

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

Other callers like CSharpCompilation.CreateAnalyzerDriver only consider the first two kinds. Should we unify this logic?

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Analyzers
End If
End Function

Protected Overrides Function IsRegularCommentOrDocumentationComment(trivia As SyntaxTrivia) As Boolean
Return trivia.Kind() = SyntaxKind.CommentTrivia OrElse trivia.Kind() = SyntaxKind.DocumentationCommentTrivia
End Function

End Class
End Namespace
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ This can be done by:
</ItemGroup>
```

Generated code is analyzed by default. To exclude generated code from banned API analysis, add the following to an analyzer config file such as `.globalconfig`:

```ini
is_global = true

banned_api_analyzer.exclude_generated_code = true
```

To add a symbol to the banned list, just add an entry in the format below to one of the configuration files (Description Text will be displayed as description in diagnostics, which is optional):

```txt
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ public sealed class CSharpSymbolIsBannedAnalyzer : SymbolIsBannedAnalyzer<Syntax

protected override SymbolDisplayFormat SymbolDisplayFormat => SymbolDisplayFormat.CSharpShortErrorMessageFormat;

protected override bool IsRegularCommentOrDocumentationComment(SyntaxTrivia trivia)
=> trivia.Kind() is SyntaxKind.SingleLineCommentTrivia or SyntaxKind.MultiLineCommentTrivia or SyntaxKind.ShebangDirectiveTrivia or SyntaxKind.SingleLineDocumentationCommentTrivia or SyntaxKind.MultiLineDocumentationCommentTrivia;

protected override SyntaxNode GetReferenceSyntaxNodeFromXmlCref(SyntaxNode syntaxNode) => ((XmlCrefAttributeSyntax)syntaxNode).Cref;

protected override IEnumerable<SyntaxNode> GetTypeSyntaxNodesFromBaseType(SyntaxNode syntaxNode) => ((BaseListSyntax)syntaxNode).Types.Select(t => (SyntaxNode)t.Type);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
Expand All @@ -13,12 +14,15 @@
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.BannedApiAnalyzers
{
public abstract class SymbolIsBannedAnalyzerBase<TSyntaxKind> : DiagnosticAnalyzer
where TSyntaxKind : struct
{
private const string ExcludeGeneratedCodeOptionName = "banned_api_analyzer.exclude_generated_code";

protected abstract Dictionary<(string ContainerName, string SymbolName), ImmutableArray<BanFileEntry>>? ReadBannedApis(CompilationStartAnalysisContext compilationContext);

protected abstract DiagnosticDescriptor SymbolIsBannedRule { get; }
Expand All @@ -33,6 +37,8 @@ public abstract class SymbolIsBannedAnalyzerBase<TSyntaxKind> : DiagnosticAnalyz

protected abstract SymbolDisplayFormat SymbolDisplayFormat { get; }

protected abstract bool IsRegularCommentOrDocumentationComment(SyntaxTrivia trivia);

public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
Expand All @@ -49,6 +55,8 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte
if (bannedApis == null || bannedApis.Count == 0)
return;

var excludeGeneratedCodeMap = new ConcurrentDictionary<SyntaxTree, bool>();

if (ShouldAnalyzeAttributes())
{
compilationContext.RegisterCompilationEndAction(
Expand All @@ -59,7 +67,10 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte
});

compilationContext.RegisterSymbolAction(
context => VerifyAttributes(context.ReportDiagnostic, context.Symbol.GetAttributes(), context.CancellationToken),
context =>
{
VerifyAttributes(context.ReportDiagnostic, context.Symbol.GetAttributes(), context.CancellationToken);
},
SymbolKind.NamedType,
SymbolKind.Method,
SymbolKind.Field,
Expand All @@ -71,6 +82,9 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte
context =>
{
context.CancellationToken.ThrowIfCancellationRequested();
if (ShouldSkipOperationAnalysis(context))
return;

switch (context.Operation)
{
case IObjectCreationOperation objectCreation:
Expand Down Expand Up @@ -153,11 +167,23 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte
OperationKind.TypeOf);

compilationContext.RegisterSyntaxNodeAction(
context => VerifyDocumentationSyntax(context.ReportDiagnostic, GetReferenceSyntaxNodeFromXmlCref(context.Node), context),
context =>
{
if (ShouldSkipSyntaxNodeAnalysis(context))
return;

VerifyDocumentationSyntax(context.ReportDiagnostic, GetReferenceSyntaxNodeFromXmlCref(context.Node), context);
},
XmlCrefSyntaxKind);

compilationContext.RegisterSyntaxNodeAction(
context => VerifyBaseTypesSyntax(context.ReportDiagnostic, GetTypeSyntaxNodesFromBaseType(context.Node), context),
context =>
{
if (ShouldSkipSyntaxNodeAnalysis(context))
return;

VerifyBaseTypesSyntax(context.ReportDiagnostic, GetTypeSyntaxNodesFromBaseType(context.Node), context);
},
BaseTypeSyntaxKinds);

return;
Expand Down Expand Up @@ -219,32 +245,55 @@ bool ContainsAttributeSymbol(ISymbol symbol)
};
}

bool ShouldSkipOperationAnalysis(OperationAnalysisContext context)
=> context.IsGeneratedCode && ExcludesGeneratedCode(context.Operation.Syntax.SyntaxTree);

bool ShouldSkipSyntaxNodeAnalysis(SyntaxNodeAnalysisContext context)
=> context.IsGeneratedCode && ExcludesGeneratedCode(context.Node.SyntaxTree);

bool ShouldSkipTreeAnalysis(SyntaxTree tree, CancellationToken cancellationToken)
=> ExcludesGeneratedCode(tree) && IsGeneratedCode(tree, cancellationToken);

bool ExcludesGeneratedCode(SyntaxTree tree)
=> excludeGeneratedCodeMap.GetOrAdd(
tree,
tree =>
{
var options = compilationContext.Options.AnalyzerConfigOptionsProvider.GetOptions(tree);
return options.TryGetValue(ExcludeGeneratedCodeOptionName, out var optionValue) &&
bool.TryParse(optionValue, out var excludeGeneratedCode) &&
excludeGeneratedCode;
});

bool IsGeneratedCode(SyntaxTree tree, CancellationToken cancellationToken)
=> GeneratedCodeUtilities.GetGeneratedCodeKindFromOptions(compilationContext.Options.AnalyzerConfigOptionsProvider.GetOptions(tree)).ToNullable() ??
GeneratedCodeUtilities.IsGeneratedCode(tree, IsRegularCommentOrDocumentationComment, cancellationToken);

void VerifyAttributes(Action<Diagnostic> reportDiagnostic, ImmutableArray<AttributeData> attributes, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var attribute in attributes)
{
var applicationSyntaxReference = attribute.ApplicationSyntaxReference;
if (applicationSyntaxReference == null)
continue;

var node = applicationSyntaxReference.GetSyntax(cancellationToken);
if (ShouldSkipTreeAnalysis(node.SyntaxTree, cancellationToken))
continue;

if (IsBannedSymbol(attribute.AttributeClass, out var entry))
{
var node = attribute.ApplicationSyntaxReference?.GetSyntax(cancellationToken);
if (node != null)
{
reportDiagnostic(
node.CreateDiagnostic(
SymbolIsBannedRule,
attribute.AttributeClass.ToDisplayString(),
string.IsNullOrWhiteSpace(entry.Message) ? "" : ": " + entry.Message));
}
reportDiagnostic(
node.CreateDiagnostic(
SymbolIsBannedRule,
attribute.AttributeClass.ToDisplayString(),
string.IsNullOrWhiteSpace(entry.Message) ? "" : ": " + entry.Message));
}

if (attribute.AttributeConstructor != null)
{
var syntaxNode = attribute.ApplicationSyntaxReference?.GetSyntax(cancellationToken);

if (syntaxNode != null)
{
VerifySymbol(reportDiagnostic, attribute.AttributeConstructor, syntaxNode);
}
VerifySymbol(reportDiagnostic, attribute.AttributeConstructor, node);
}
}
}
Expand Down
Loading
Loading