public async Task> AnalyzeCodeAsync(Document document) { List
result = new List (); SyntaxNode root = await document.GetSyntaxRootAsync(); var expressions = root.DescendantNodes().OfType (); foreach (var expression in expressions) { var condition = expression.Condition; var trueExpression = expression.WhenTrue; var falseExpression = expression.WhenFalse; if (trueExpression.ToString() == falseExpression.ToString()) { var diagnostic = Diagnostic.Create(DiagnosticDescriptor, expression.GetLocation()); result.Add(diagnostic); } } return result; } public async Task ApplyFixAsync(Document document, List diagnostics, CancellationToken cancellationToken) { SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken); foreach (var diagnostic in diagnostics) { var expression = root.FindNode(diagnostic.Location.SourceSpan); var trueExpression = ((ConditionalExpressionSyntax)expression).WhenTrue; var newExpression = SyntaxFactory.ParseExpression($"({trueExpression})"); root = root.ReplaceNode(trueExpression, newExpression); } return document.WithSyntaxRoot(root); }
public async TaskThis example registers a code fix for an imported namespace that is missing. The Package library used by CodeFixContext.RegisterFix is Microsoft.CodeAnalysis.CSharp.Workspaces.> AnalyzeCodeAsync(Document document) { List
result = new List (); SyntaxNode root = await document.GetSyntaxRootAsync(); var namespaces = root.DescendantNodes().OfType (); foreach (var ns in namespaces) { var symbol = await document.GetSemanticModelAsync(); var importedNamespace = symbol.GetSymbolInfo(ns.Name).Symbol?.ContainingNamespace?.ToString() ?? ""; if (importedNamespace != "") { result.Add(Diagnostic.Create(DiagnosticDescriptor, ns.Name.GetLocation())); } return result; } } public async Task ApplyFixAsync(Document document, List diagnostics, CancellationToken cancellationToken) { SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken); foreach (var diagnostic in diagnostics) { var namespaceNode = (UsingDirectiveSyntax)root.FindNode(diagnostic.Location.SourceSpan); var importedNamespace = namespaceNode.Name.ToString(); var newImport = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(importedNamespace)); root = root.InsertNodesBefore(namespaceNode, new List { newImport }); } return document.WithSyntaxRoot(root); }