
上QQ阅读APP看书,第一时间看更新
How it works...
Syntax tree analyzers register callbacks to analyze syntax of all source files in the compilation. Our analysis works by getting the roots of the syntax tree and then operating on all the descendant syntax nodes of the roots which are of type StatementSyntax. First, we note that a block statement is itself an aggregate statement, and by definition has curly braces, so we skip past these.
// Skip analyzing block statements.
if (statement is BlockSyntax)
{
continue;
}
We then perform syntactic checks for the parent of statement syntax. If the parent of the statement is also a statement, but not a block with curly braces, then we report a diagnostic on the first syntax token of the statement recommending usage of curly braces.
// Report issue for all statements that are nested within a statement,
// but not a block statement.
if (statement.Parent is StatementSyntax && !(statement.Parent is BlockSyntax))
{
var diagnostic = Diagnostic.Create(Rule, statement.GetFirstToken().GetLocation());
syntaxTreeContext.ReportDiagnostic(diagnostic);
}
SyntaxTreeAnalysisContext provided to syntax tree actions does not expose the semantic model for the source file, hence no semantic analysis can be performed within a syntax tree action.