Skip to content

Instantly share code, notes, and snippets.

@HaloFour
Created January 3, 2023 18:31
Show Gist options
  • Save HaloFour/c665b4a4c85f93206ca91f135d08ee72 to your computer and use it in GitHub Desktop.
Save HaloFour/c665b4a4c85f93206ca91f135d08ee72 to your computer and use it in GitHub Desktop.
ChatGPT Roslyn Analyzer
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace MyAnalyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class NoCurseWordsAnalyzer : DiagnosticAnalyzer
{
private static readonly string[] CurseWords =
{
"damn", "hell", "crap", "piss", "frick", "fudge"
};
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
"NoCurseWords",
"Forbidden use of curse words as variable names",
"The use of curse words as variable names is not allowed: '{0}'",
"Naming",
DiagnosticSeverity.Error,
true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(AnalyzeVariableDeclaration, SyntaxKind.VariableDeclaration);
}
private static void AnalyzeVariableDeclaration(SyntaxNodeAnalysisContext context)
{
var variableDeclaration = (VariableDeclarationSyntax)context.Node;
foreach (var variable in variableDeclaration.Variables)
{
var variableName = variable.Identifier.Text;
if (Array.IndexOf(CurseWords, variableName.ToLowerInvariant()) >= 0)
{
var diagnostic = Diagnostic.Create(Rule, variable.Identifier.GetLocation(), variableName);
context.ReportDiagnostic(diagnostic);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment