本文整理汇总了C#中Microsoft.CodeAnalysis.CodeFixes.CodeFixContext类的典型用法代码示例。如果您正苦于以下问题:C# CodeFixContext类的具体用法?C# CodeFixContext怎么用?C# CodeFixContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CodeFixContext类属于Microsoft.CodeAnalysis.CodeFixes命名空间,在下文中一共展示了CodeFixContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RegisterCodeFixesAsync
public async override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var cancellationToken = context.CancellationToken;
var diagnostics = context.Diagnostics;
var root = await document.GetSyntaxRootAsync(cancellationToken);
var diagnostic = diagnostics.First();
var node = root.FindNode(context.Span) as BinaryExpressionSyntax;
if (node == null)
return;
StatementSyntax expression = null;
var ifStatement = node.Parent as IfStatementSyntax;
if (ifStatement == null)
return;
var statement = ifStatement.Statement;
if (statement is BlockSyntax)
expression = ((BlockSyntax)statement).Statements[0];
else
expression = statement;
if (expression == null)
return;
context.RegisterCodeFix(CodeAction.Create("Remove redundant check", async token => {
var editor = await DocumentEditor.CreateAsync(document, cancellationToken);
expression = expression
.WithOrderedTriviaFromSubTree(ifStatement)
.WithAdditionalAnnotations(Formatter.Annotation);
editor.ReplaceNode(ifStatement, expression);
return editor.GetChangedDocument();
}, string.Empty), diagnostic);
}
开发者ID:nhabuiduc,项目名称:RefactoringEssentials,代码行数:32,代码来源:RedundantCheckBeforeAssignmentCodeFixProvider.cs
示例2: RegisterCodeFixesAsync
/// <inheritdoc/>
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var root = await document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
foreach (var diagnostic in context.Diagnostics)
{
if (!diagnostic.Id.Equals(SA1309FieldNamesMustNotBeginWithUnderscore.DiagnosticId))
{
continue;
}
var token = root.FindToken(diagnostic.Location.SourceSpan.Start);
if (token.IsMissing)
{
continue;
}
if (!string.IsNullOrEmpty(token.ValueText))
{
var newName = token.ValueText.TrimStart(new[] { '_' });
if (string.IsNullOrEmpty(newName))
{
// The variable consisted of only underscores. In this case we cannot
// generate a valid variable name and thus will not offer a code fix.
continue;
}
context.RegisterCodeFix(CodeAction.Create(string.Format(NamingResources.SA1309CodeFix, newName), cancellationToken => RenameHelper.RenameSymbolAsync(document, root, token, newName, cancellationToken), equivalenceKey: nameof(SA1309CodeFixProvider)), diagnostic);
}
}
}
示例3: VerifyGetFixesWhenUsingSystemDoesNotExist
public async Task VerifyGetFixesWhenUsingSystemDoesNotExist()
{
var code = File.ReadAllText(
[email protected]"Targets\{nameof(IsBusinessObjectSerializableMakeSerializableCodeFixTests)}.{(nameof(this.VerifyGetFixesWhenUsingSystemDoesNotExist))}.cs");
var document = TestHelpers.Create(code);
var tree = await document.GetSyntaxTreeAsync();
var diagnostics = await TestHelpers.GetDiagnosticsAsync(code, new IsBusinessObjectSerializableAnalyzer());
var sourceSpan = diagnostics[0].Location.SourceSpan;
var actions = new List<CodeAction>();
var codeActionRegistration = new Action<CodeAction, ImmutableArray<Diagnostic>>(
(a, _) => { actions.Add(a); });
var fix = new IsBusinessObjectSerializableMakeSerializableCodeFix();
var codeFixContext = new CodeFixContext(document, diagnostics[0],
codeActionRegistration, new CancellationToken(false));
await fix.RegisterCodeFixesAsync(codeFixContext);
Assert.AreEqual(2, actions.Count, nameof(actions.Count));
await TestHelpers.VerifyActionAsync(actions,
IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSystemSerializableDescription, document,
tree, $"{Environment.NewLine}[System.Serializable]");
await TestHelpers.VerifyActionAsync(actions,
IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSerializableAndUsingDescription, document,
tree, $"using System;{Environment.NewLine}{Environment.NewLine}[Serializable]");
}
示例4: RegisterCodeFixesAsync
public async override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var cancellationToken = context.CancellationToken;
var span = context.Span;
var diagnostics = context.Diagnostics;
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (model.IsFromGeneratedCode(cancellationToken))
return;
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var diagnostic = diagnostics.First();
var node = root.FindNode(context.Span);
context.RegisterCodeFix(CodeActionFactory.Create(
node.Span,
diagnostic.Severity,
GettextCatalog.GetString("Add 'new' modifier"),
token =>
{
SyntaxNode newRoot;
if (node.Kind() != SyntaxKind.VariableDeclarator)
newRoot = root.ReplaceNode(node, AddNewModifier(node));
else //this one wants to be awkward - you can't add modifiers to a variable declarator
{
SyntaxNode declaringNode = node.Parent.Parent;
if (declaringNode is FieldDeclarationSyntax)
newRoot = root.ReplaceNode(node.Parent.Parent, (node.Parent.Parent as FieldDeclarationSyntax).AddModifiers(SyntaxFactory.Token(SyntaxKind.NewKeyword)));
else //it's an event declaration
newRoot = root.ReplaceNode(node.Parent.Parent, (node.Parent.Parent as EventFieldDeclarationSyntax).AddModifiers(SyntaxFactory.Token(SyntaxKind.NewKeyword)));
}
return Task.FromResult(document.WithSyntaxRoot(newRoot.WithAdditionalAnnotations(Formatter.Annotation)));
}), diagnostic);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:33,代码来源:CS0108UseNewKeywordIfHidingIntendedCodeFixProvider.cs
示例5: GetFixes
public async Task GetFixes()
{
var code =
@"using System.ServiceModel;
public class AClass
{
[OperationContract(IsOneWay = true)]
public string AMethod() { return string.Empty; }
}";
var document = TestHelpers.Create(code);
var tree = await document.GetSyntaxTreeAsync();
var diagnostics = await TestHelpers.GetDiagnosticsAsync(
code, new IsOneWayOperationAnalyzer());
var sourceSpan = diagnostics[0].Location.SourceSpan;
var actions = new List<CodeAction>();
var codeActionRegistration = new Action<CodeAction, ImmutableArray<Diagnostic>>(
(a, _) => { actions.Add(a); });
var fix = new IsOneWayOperationMakeIsOneWayFalseCodeFix();
var codeFixContext = new CodeFixContext(document, diagnostics[0],
codeActionRegistration, new CancellationToken(false));
await fix.RegisterCodeFixesAsync(codeFixContext);
Assert.Equal(1, actions.Count);
await TestHelpers.VerifyActionAsync(actions,
IsOneWayOperationMakeIsOneWayFalseCodeFixConstants.Description, document,
tree, new[] { "fals" });
}
示例6: RegisterCodeFixesAsync
/// <inheritdoc/>
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
foreach (var diagnostic in context.Diagnostics)
{
SyntaxNode node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true);
if (node == null || node.IsMissing)
{
continue;
}
SyntaxNode declarationNode = FindParentDeclarationNode(node);
if (declarationNode == null)
{
continue;
}
context.RegisterCodeFix(
CodeAction.Create(
MaintainabilityResources.SA1400CodeFix,
cancellationToken => GetTransformedDocumentAsync(context.Document, root, declarationNode),
nameof(SA1400CodeFixProvider)),
diagnostic);
}
}
示例7: RegisterCodeFixesAsync
/// <inheritdoc/>
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
var documentRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
SyntaxNode syntax = documentRoot.FindNode(diagnostic.Location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
if (syntax == null)
{
continue;
}
XmlElementSyntax xmlElementSyntax = syntax as XmlElementSyntax;
if (xmlElementSyntax == null)
{
// We continue even for placeholders if they are empty elements (XmlEmptyElementSyntax)
continue;
}
if (string.IsNullOrWhiteSpace(xmlElementSyntax.Content.ToString()))
{
// The placeholder hasn't been updated yet.
continue;
}
context.RegisterCodeFix(
CodeAction.Create(
DocumentationResources.SA1651CodeFix,
cancellationToken => this.GetTransformedDocumentAsync(context.Document, xmlElementSyntax, cancellationToken),
nameof(SA1651CodeFixProvider)),
diagnostic);
}
}
示例8: RegisterCodeFixesAsync
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
context.RegisterCodeFix(CodeAction.Create(
"Removes redundant comparision", c => RemoveRedundantComparisonAsync(context.Document, diagnostic, c), nameof(SimplifyRedundantBooleanComparisonsCodeFixProvider)), diagnostic);
return Task.FromResult(0);
}
示例9: RegisterCodeFixesAsync
public override sealed async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var syntaxNode = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true);
var statement = syntaxNode as StatementSyntax;
var assignment = syntaxNode as AssignmentExpressionSyntax;
var binary = syntaxNode as BinaryExpressionSyntax;
if (statement != null ||
assignment != null ||
binary != null)
{
context.RegisterCodeFix(
CodeAction.Create(
Title,
c =>
{
var newRoot = CalculateNewRoot(root, diagnostic, statement, assignment, binary);
return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
}),
context.Diagnostics);
}
}
示例10: RegisterCodeFixesAsync
public override sealed Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
if (diagnostic.Properties["kind"] == "missingDoc")
context.RegisterCodeFix(CodeAction.Create(Resources.XmlDocumentationCreateMissingParametersCodeFixProvider_Title, c => FixParametersAsync(context.Document, diagnostic, c)), diagnostic);
return Task.FromResult(0);
}
开发者ID:gerryaobrien,项目名称:code-cracker,代码行数:7,代码来源:XmlDocumentationCreateMissingParametersCodeFixProvider.cs
示例11: RegisterCodeFixesAsync
public override sealed async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var initializer = root.FindNode(diagnosticSpan) as ConstructorInitializerSyntax;
if (initializer == null)
{
return;
}
var constructor = initializer.Parent as ConstructorDeclarationSyntax;
if (constructor == null)
{
return;
}
context.RegisterCodeFix(
CodeAction.Create(
Title,
c =>
{
var newRoot = RemoveInitializer(root, constructor);
return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
}),
context.Diagnostics);
}
示例12: AddFix
private void AddFix(string codeFixTitle, CodeFixContext context, SyntaxNode root, SyntaxNode classDecl, SyntaxGenerator generator, params string[] languages)
{
var fix = new MyCodeAction(
codeFixTitle,
c => GetFix(context.Document, root, classDecl, generator, languages));
context.RegisterCodeFix(fix, context.Diagnostics);
}
示例13: RegisterCodeFixesAsync
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var token = root.FindToken(context.Span.Start);
if (!token.Span.IntersectsWith(context.Span))
{
return;
}
var generator = SyntaxGenerator.GetGenerator(context.Document);
var classDecl = generator.GetDeclaration(token.Parent);
if (classDecl == null)
{
return;
}
// Register fixes.
// 1) Apply C# DiagnosticAnalyzerAttribute.
var title = string.Format(CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_1, LanguageNames.CSharp);
AddFix(title, context, root, classDecl, generator, LanguageNames.CSharp);
// 2) Apply VB DiagnosticAnalyzerAttribute.
title = string.Format(CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_1, LanguageNames.VisualBasic);
AddFix(title, context, root, classDecl, generator, LanguageNames.VisualBasic);
// 3) Apply both C# and VB DiagnosticAnalyzerAttributes.
title = string.Format(CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_2, LanguageNames.CSharp, LanguageNames.VisualBasic);
AddFix(title, context, root, classDecl, generator, LanguageNames.CSharp, LanguageNames.VisualBasic);
}
示例14: RegisterCodeFixesAsync
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var syntaxFactoryService = SyntaxGenerator.GetGenerator(context.Document);
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var node = root.FindNode(context.Span);
// We cannot have multiple overlapping diagnostics of this id.
var diagnostic = context.Diagnostics.Single();
if (IsInArgumentContext(node))
{
// StringComparison.CurrentCulture => StringComparison.Ordinal
// StringComparison.CurrentCultureIgnoreCase => StringComparison.OrdinalIgnoreCase
context.RegisterCodeFix(new MyCodeAction(SystemRuntimeAnalyzersResources.UseOrdinalStringComparisonTitle,
async ct => await FixArgument(context.Document, syntaxFactoryService, root, node).ConfigureAwait(false)),
diagnostic);
}
else if (IsInIdentifierNameContext(node))
{
// string.Equals(a, b) => string.Equals(a, b, StringComparison.Ordinal)
// string.Compare(a, b) => string.Compare(a, b, StringComparison.Ordinal)
context.RegisterCodeFix(new MyCodeAction(SystemRuntimeAnalyzersResources.UseOrdinalStringComparisonTitle,
async ct => await FixIdentifierName(context.Document, syntaxFactoryService, root, node, context.CancellationToken).ConfigureAwait(false)),
diagnostic);
}
else if (IsInEqualsContext(node))
{
// "a == b" => "string.Equals(a, b, StringComparison.Ordinal)"
// "a != b" => "!string.Equals(a, b, StringComparison.Ordinal)"
context.RegisterCodeFix(new MyCodeAction(SystemRuntimeAnalyzersResources.UseOrdinalStringComparisonTitle,
async ct => await FixEquals(context.Document, syntaxFactoryService, root, node, context.CancellationToken).ConfigureAwait(false)),
diagnostic);
}
}
示例15: RegisterCodeFixesAsync
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
var declaration = root.FindNode(context.Span);
if (declaration == null)
{
return;
}
// find a Dispose method
var iDisposableType = model.Compilation.GetSpecialType(SpecialType.System_IDisposable);
var iDisposable_Dispose = (iDisposableType?.GetMembers(DisposableFieldsShouldBeDisposedAnalyzer.Dispose))?.Single();
if (iDisposableType == null || iDisposable_Dispose == null)
{
return;
}
var fieldSymbol = model.GetDeclaredSymbol(declaration, context.CancellationToken) as IFieldSymbol;
var disposeMethod = fieldSymbol?.ContainingType?.FindImplementationForInterfaceMember(iDisposable_Dispose) as IMethodSymbol;
if (disposeMethod == null)
{
return;
}
// We cannot have multiple overlapping diagnostics of this id.
var diagnostic = context.Diagnostics.Single();
context.RegisterCodeFix(new MyCodeAction(SystemRuntimeAnalyzersResources.DisposableFieldsShouldBeDisposedMessage,
async ct => await AddDisposeCall(context.Document, declaration, fieldSymbol, disposeMethod, iDisposableType, iDisposable_Dispose, ct).ConfigureAwait(false)),
diagnostic);
}