Skip to content

Instantly share code, notes, and snippets.

@Schandlich
Created June 4, 2014 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Schandlich/f34becb8caa3be3d9cac to your computer and use it in GitHub Desktop.
Save Schandlich/f34becb8caa3be3d9cac to your computer and use it in GitHub Desktop.
Roslyn EndOfFile
[DiagnosticAnalyzer]
[ExportDiagnosticAnalyzer(DiagnosticId, LanguageNames.CSharp)]
public class DiagnosticAnalyzer : ISyntaxTreeAnalyzer
{
internal const string DiagnosticId = "EndOfFile";
internal const string Description = "No blank lines at the end of the file please.";
internal const string MessageFormat = "No blank lines at the end of the file please.";
internal const string Category = "Naming";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning);
public ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }
public void AnalyzeSyntaxTree(SyntaxTree tree, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
{
var root = tree.GetRoot();
var eofToken = root.DescendantTokens().Where(x => x.IsKind(SyntaxKind.EndOfFileToken)).First();
var leadingTrivia = eofToken.LeadingTrivia;
var leadingBlankLines = eofToken.LeadingTrivia.Where(x => x.IsKind(SyntaxKind.EndOfLineTrivia));
foreach (var blankline in leadingBlankLines)
{
addDiagnostic(Diagnostic.Create(Rule, blankline.GetLocation()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment