本文整理汇总了C#中Microsoft.CodeAnalysis.SyntaxNode.FindNode方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxNode.FindNode方法的具体用法?C# SyntaxNode.FindNode怎么用?C# SyntaxNode.FindNode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CodeAnalysis.SyntaxNode
的用法示例。
在下文中一共展示了SyntaxNode.FindNode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: UpdateMainDocument
private static Solution UpdateMainDocument(Document document, SyntaxNode root, MethodDeclarationSyntax method, IEnumerable<IGrouping<Document, ReferenceLocation>> documentGroups)
{
var mainDocGroup = documentGroups.FirstOrDefault(dg => dg.Key.Equals(document));
SyntaxNode newRoot;
if (mainDocGroup == null)
{
newRoot = root.ReplaceNode(method, method.AddModifiers(staticToken));
}
else
{
var diagnosticNodes = mainDocGroup.Select(referenceLocation => root.FindNode(referenceLocation.Location.SourceSpan)).ToList();
newRoot = root.TrackNodes(diagnosticNodes.Union(new[] { method }));
newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(method), method.AddModifiers(staticToken));
foreach (var diagnosticNode in diagnosticNodes)
{
var token = newRoot.FindToken(diagnosticNode.GetLocation().SourceSpan.Start);
var tokenParent = token.Parent;
if (token.Parent.IsKind(SyntaxKind.IdentifierName)) continue;
var invocationExpression = newRoot.GetCurrentNode(diagnosticNode).FirstAncestorOrSelfOfType<InvocationExpressionSyntax>()?.Expression;
if (invocationExpression == null || invocationExpression.IsKind(SyntaxKind.IdentifierName)) continue;
var memberAccess = invocationExpression as MemberAccessExpressionSyntax;
if (memberAccess == null) continue;
var newMemberAccessParent = memberAccess.Parent.ReplaceNode(memberAccess, memberAccess.Name)
.WithAdditionalAnnotations(Formatter.Annotation);
newRoot = newRoot.ReplaceNode(memberAccess.Parent, newMemberAccessParent);
}
}
var newSolution = document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newRoot);
return newSolution;
}
示例2: RegisterMethodDocumentationCodeFix
/// <summary>
/// Register the property fix for property documentation.
/// </summary>
/// <param name="root">the syntax root node.</param>
/// <param name="context">the code fix context, containing the location of the fix.</param>
/// <param name="diagnostic">the diagnostic, where the invalid code was located.</param>
private void RegisterMethodDocumentationCodeFix(SyntaxNode root, CodeFixContext context, Diagnostic diagnostic)
{
var startNode = root.FindNode(diagnostic.Location.SourceSpan);
var methodDeclarationSyntax = startNode as MethodDeclarationSyntax;
if (methodDeclarationSyntax != null)
this.RegisterMethodCodeFix(methodDeclarationSyntax, root, context, diagnostic);
}
示例3: RegisterCodeFixesAsync
protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var attribute = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as AttributeSyntax;
var attributeList = attribute?.Parent as AttributeListSyntax;
if (attribute == null ||
attributeList == null)
{
return;
}
var semanticModel = await context.Document.GetSemanticModelAsync().ConfigureAwait(false);
var optionalAttribute = semanticModel?.Compilation?.GetTypeByMetadataName(
KnownType.System_Runtime_InteropServices_OptionalAttribute.TypeName);
if (optionalAttribute == null)
{
return;
}
context.RegisterCodeFix(
CodeAction.Create(
Title,
c =>
{
var newRoot = root.ReplaceNode(
attributeList,
GetNewAttributeList(attributeList, optionalAttribute, semanticModel));
return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
}),
context.Diagnostics);
}
示例4: RegisterCodeFixesAsync
protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var syntaxNode = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as PrefixUnaryExpressionSyntax;
if (syntaxNode == null)
{
return;
}
context.RegisterCodeFix(
CodeAction.Create(
Title,
c =>
{
var expression = syntaxNode.Operand.RemoveParentheses();
var newBinary = ChangeOperator((BinaryExpressionSyntax)expression);
if (syntaxNode.Parent is ExpressionSyntax &&
!ExpressionTypesWithNoParens.Any(type => type.IsInstanceOfType(syntaxNode.Parent)))
{
newBinary = SyntaxFactory.ParenthesizedExpression(newBinary);
}
var newRoot = root.ReplaceNode(
syntaxNode,
newBinary.WithAdditionalAnnotations(Formatter.Annotation));
return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
}),
context.Diagnostics);
}
示例5: RegisterCodeFixesAsync
protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var literal = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as LiteralExpressionSyntax;
if (literal == null)
{
return;
}
var newLiteral = SyntaxFactory.Literal(
literal.Token.Text.ToUpperInvariant(),
(long)literal.Token.Value);
if (!newLiteral.IsKind(SyntaxKind.None))
{
context.RegisterCodeFix(
CodeAction.Create(
Title,
c =>
{
var newRoot = root.ReplaceNode(literal,
literal.WithToken(newLiteral).WithTriviaFrom(literal));
return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
}),
context.Diagnostics);
}
}
示例6: GetUnnecessaryImports
public static IEnumerable<SyntaxNode> GetUnnecessaryImports(SemanticModel semanticModel, SyntaxNode root, CancellationToken cancellationToken)
{
var diagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken);
if (!diagnostics.Any())
{
return null;
}
var unnecessaryImports = new HashSet<UsingDirectiveSyntax>();
foreach (var diagnostic in diagnostics)
{
if (diagnostic.Id == "CS8019")
{
var node = root.FindNode(diagnostic.Location.SourceSpan) as UsingDirectiveSyntax;
if (node != null)
{
unnecessaryImports.Add(node);
}
}
}
if (cancellationToken.IsCancellationRequested || !unnecessaryImports.Any())
{
return null;
}
return unnecessaryImports;
}
示例7: RegisterCodeFixesAsync
protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var syntaxNode = root.FindNode(diagnosticSpan);
var initializer = syntaxNode as ConstructorInitializerSyntax;
if (initializer != null)
{
RegisterActionForBaseCall(context, root, initializer);
return;
}
var method = syntaxNode.FirstAncestorOrSelf<BaseMethodDeclarationSyntax>();
if (method is ConstructorDeclarationSyntax)
{
RegisterActionForConstructor(context, root, method);
return;
}
if (method is DestructorDeclarationSyntax)
{
RegisterActionForDestructor(context, root, method);
}
}
开发者ID:duncanpMS,项目名称:sonarlint-vs,代码行数:25,代码来源:RedundancyInConstructorDestructorDeclarationCodeFixProvider.cs
示例8: RegisterCodeFixesAsync
protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var nameEquals = root.FindNode(diagnosticSpan) as NameEqualsSyntax;
var anonymousObjectCreation = nameEquals?.Parent?.Parent as AnonymousObjectCreationExpressionSyntax;
if (anonymousObjectCreation == null)
{
return;
}
context.RegisterCodeFix(
CodeAction.Create(
Title,
c =>
{
var newInitializersWithSeparators = anonymousObjectCreation.Initializers.GetWithSeparators()
.Select(item => GetNewSyntaxListItem(item));
var newAnonymousObjectCreation = anonymousObjectCreation
.WithInitializers(SyntaxFactory.SeparatedList<AnonymousObjectMemberDeclaratorSyntax>(newInitializersWithSeparators))
.WithTriviaFrom(anonymousObjectCreation);
var newRoot = root.ReplaceNode(
anonymousObjectCreation,
newAnonymousObjectCreation);
return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
}),
context.Diagnostics);
}
开发者ID:duncanpMS,项目名称:sonarlint-vs,代码行数:29,代码来源:RedundantPropertyNamesInAnonymousClassCodeFixProvider.cs
示例9: RegisterCodeFixesAsync
protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var prefix = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as PrefixUnaryExpressionSyntax;
if (prefix == null)
{
return;
}
context.RegisterCodeFix(
CodeAction.Create(
Title,
c =>
{
ExpressionSyntax expression;
uint count;
GetExpression(prefix, out expression, out count);
if (count%2 == 1)
{
expression = SyntaxFactory.PrefixUnaryExpression(
prefix.Kind(),
expression);
}
var newRoot = root.ReplaceNode(prefix, expression
.WithAdditionalAnnotations(Formatter.Annotation));
return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
}),
context.Diagnostics);
}
示例10: RegisterMethodDocumentationCodeFix
/// <summary>
/// Register the property fix for property documentation.
/// </summary>
/// <param name="root">the syntax root node.</param>
/// <param name="context">the code fix context, containing the location of the fix.</param>
/// <param name="diagnostic">the diagnostic, where the invalid code was located.</param>
private void RegisterMethodDocumentationCodeFix(SyntaxNode root, CodeFixContext context, Diagnostic diagnostic)
{
var startNode = root.FindNode(diagnostic.Location.SourceSpan);
var constructorDeclaration = startNode as ConstructorDeclarationSyntax;
if (constructorDeclaration != null)
this.RegisterConstructorCodeFix(constructorDeclaration, root, context, diagnostic);
}
开发者ID:jimmymain,项目名称:Documentation.Analyzers,代码行数:13,代码来源:DocumentationConstructorCodeFixProvider.cs
示例11: CreateCodeFix
private Document CreateCodeFix(Document document, Diagnostic diagnostic, SyntaxNode syntaxRoot)
{
SyntaxNode newSyntaxRoot = syntaxRoot;
var node = syntaxRoot.FindNode(diagnostic.Location.SourceSpan);
var indentationOptions = IndentationOptions.FromDocument(document);
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
newSyntaxRoot = this.RegisterBaseTypeDeclarationCodeFix(syntaxRoot, (BaseTypeDeclarationSyntax)node, indentationOptions);
break;
case SyntaxKind.AccessorList:
newSyntaxRoot = this.RegisterPropertyLikeDeclarationCodeFix(syntaxRoot, (BasePropertyDeclarationSyntax)node.Parent, indentationOptions);
break;
case SyntaxKind.Block:
newSyntaxRoot = this.RegisterMethodLikeDeclarationCodeFix(syntaxRoot, (BaseMethodDeclarationSyntax)node.Parent, indentationOptions);
break;
case SyntaxKind.NamespaceDeclaration:
newSyntaxRoot = this.RegisterNamespaceDeclarationCodeFix(syntaxRoot, (NamespaceDeclarationSyntax)node, indentationOptions);
break;
}
return document.WithSyntaxRoot(newSyntaxRoot);
}
示例12: RegisterCodeFixesAsync
protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var syntaxNode = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as ExpressionSyntax;
if (syntaxNode == null)
{
return;
}
var parent = syntaxNode.Parent;
syntaxNode = syntaxNode.RemoveParentheses();
var binary = syntaxNode as BinaryExpressionSyntax;
if (binary != null)
{
RegisterBinaryExpressionReplacement(context, root, syntaxNode, binary);
return;
}
var conditional = syntaxNode as ConditionalExpressionSyntax;
if (conditional != null)
{
RegisterConditionalExpressionRemoval(context, root, conditional);
return;
}
var literal = syntaxNode as LiteralExpressionSyntax;
if (literal == null)
{
return;
}
if (parent is PrefixUnaryExpressionSyntax)
{
RegisterBooleanInversion(context, root, literal);
return;
}
var conditionalParent = parent as ConditionalExpressionSyntax;
if (conditionalParent != null)
{
RegisterConditionalExpressionRewrite(context, root, literal, conditionalParent);
return;
}
var binaryParent = parent as BinaryExpressionSyntax;
if (binaryParent != null)
{
RegisterBinaryExpressionRemoval(context, root, literal, binaryParent);
return;
}
var forStatement = parent as ForStatementSyntax;
if (forStatement != null)
{
RegisterForStatementConditionRemoval(context, root, forStatement);
return;
}
}
示例13: RegisterCodeFixesAsync
protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var syntaxNode = root.FindNode(diagnosticSpan);
var variableDeclarator = syntaxNode.FirstAncestorOrSelf<VariableDeclaratorSyntax>();
var variableDeclaration = variableDeclarator?.Parent as VariableDeclarationSyntax;
if (variableDeclaration == null)
{
return;
}
if (variableDeclaration.Variables.Count == 1)
{
var fieldDeclaration = variableDeclaration.Parent as FieldDeclarationSyntax;
if (fieldDeclaration == null)
{
return;
}
context.RegisterCodeFix(
CodeAction.Create(
Title,
c =>
{
var newFieldDeclaration = fieldDeclaration.AddModifiers(
SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
var newRoot = root.ReplaceNode(fieldDeclaration, newFieldDeclaration);
return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
}),
context.Diagnostics);
}
}
示例14: AddConstructorsAsync
private async Task<Document> AddConstructorsAsync(Document document, IEnumerable<Diagnostic> diagnostics, SyntaxNode root, CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var generator = editor.Generator;
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var diagnosticSpan = diagnostics.First().Location.SourceSpan; // All the diagnostics are reported at the same location -- the name of the declared class -- so it doesn't matter which one we pick
var node = root.FindNode(diagnosticSpan);
var targetNode = editor.Generator.GetDeclaration(node, DeclarationKind.Class);
var typeSymbol = model.GetDeclaredSymbol(targetNode) as INamedTypeSymbol;
foreach (var diagnostic in diagnostics)
{
var missingCtorSignature = (ImplementStandardExceptionConstructorsAnalyzer.MissingCtorSignature)Enum.Parse(typeof(ImplementStandardExceptionConstructorsAnalyzer.MissingCtorSignature), diagnostic.Properties["Signature"]);
switch (missingCtorSignature)
{
case ImplementStandardExceptionConstructorsAnalyzer.MissingCtorSignature.CtorWithNoParameter:
// Add missing CtorWithNoParameter
var newConstructorNode1 = generator.ConstructorDeclaration(typeSymbol.Name, accessibility: Accessibility.Public);
editor.AddMember(targetNode, newConstructorNode1);
break;
case ImplementStandardExceptionConstructorsAnalyzer.MissingCtorSignature.CtorWithStringParameter:
// Add missing CtorWithStringParameter
var newConstructorNode2 = generator.ConstructorDeclaration(
containingTypeName: typeSymbol.Name,
parameters: new[]
{
generator.ParameterDeclaration("message", generator.TypeExpression(WellKnownTypes.String(editor.SemanticModel.Compilation)))
},
accessibility: Accessibility.Public,
baseConstructorArguments: new[]
{
generator.Argument(generator.IdentifierName("message"))
});
editor.AddMember(targetNode, newConstructorNode2);
break;
case ImplementStandardExceptionConstructorsAnalyzer.MissingCtorSignature.CtorWithStringAndExceptionParameters:
// Add missing CtorWithStringAndExceptionParameters
var newConstructorNode3 = generator.ConstructorDeclaration(
containingTypeName: typeSymbol.Name,
parameters: new[]
{
generator.ParameterDeclaration("message", generator.TypeExpression(WellKnownTypes.String(editor.SemanticModel.Compilation))),
generator.ParameterDeclaration("innerException", generator.TypeExpression(WellKnownTypes.Exception(editor.SemanticModel.Compilation)))
},
accessibility: Accessibility.Public,
baseConstructorArguments: new[]
{
generator.Argument(generator.IdentifierName("message")),
generator.Argument(generator.IdentifierName("innerException"))
});
editor.AddMember(targetNode, newConstructorNode3);
break;
}
}
return editor.GetChangedDocument();
}
开发者ID:jakub-sturc,项目名称:roslyn-analyzers,代码行数:59,代码来源:ImplementStandardExceptionConstructors.Fixer.cs
示例15: Fix
private static async Task<Document> Fix(CodeFixContext context, SyntaxNode root, SyntaxGenerator generator, SemanticModel semanticModel, CancellationToken cancellationToken)
{
SyntaxNode node = root.FindNode(context.Span);
Diagnostic diagnostic = context.Diagnostics.First();
switch (diagnostic.Properties[OperatorOverloadsHaveNamedAlternatesAnalyzer.DiagnosticKindText])
{
case OperatorOverloadsHaveNamedAlternatesAnalyzer.AddAlternateText:
SyntaxNode methodDeclaration = generator.GetDeclaration(node, DeclarationKind.Operator) ?? generator.GetDeclaration(node, DeclarationKind.ConversionOperator);
var operatorOverloadSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken);
INamedTypeSymbol typeSymbol = operatorOverloadSymbol.ContainingType;
// For C# the following `typeDeclarationSyntax` and `typeDeclaration` nodes are identical, but for VB they're different so in
// an effort to keep this as language-agnostic as possible, the heavy-handed approach is used.
SyntaxNode typeDeclarationSyntax = typeSymbol.DeclaringSyntaxReferences.First().GetSyntax(cancellationToken);
SyntaxNode typeDeclaration = generator.GetDeclaration(typeDeclarationSyntax, DeclarationKind.Class);
SyntaxNode addedMember;
ImmutableArray<SyntaxNode> bodyStatements = ImmutableArray.Create(
generator.ThrowStatement(generator.ObjectCreationExpression(semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException"))));
if (OperatorOverloadsHaveNamedAlternatesAnalyzer.IsPropertyExpected(operatorOverloadSymbol.Name))
{
// add a property
addedMember = generator.PropertyDeclaration(
name: OperatorOverloadsHaveNamedAlternatesAnalyzer.IsTrueText,
type: generator.TypeExpression(SpecialType.System_Boolean),
accessibility: Accessibility.Public,
modifiers: DeclarationModifiers.ReadOnly,
getAccessorStatements: bodyStatements);
}
else
{
// add a method
ExpectedMethodSignature expectedSignature = GetExpectedMethodSignature(operatorOverloadSymbol, semanticModel.Compilation);
addedMember = generator.MethodDeclaration(
name: expectedSignature.Name,
parameters: expectedSignature.Parameters.Select(p => generator.ParameterDeclaration(p.Item1, generator.TypeExpression(p.Item2))),
returnType: generator.TypeExpression(expectedSignature.ReturnType),
accessibility: Accessibility.Public,
modifiers: expectedSignature.IsStatic ? DeclarationModifiers.Static : DeclarationModifiers.None,
statements: bodyStatements);
}
SyntaxNode newTypeDeclaration = generator.AddMembers(typeDeclaration, addedMember);
return context.Document.WithSyntaxRoot(root.ReplaceNode(typeDeclaration, newTypeDeclaration));
case OperatorOverloadsHaveNamedAlternatesAnalyzer.FixVisibilityText:
SyntaxNode badVisibilityNode = generator.GetDeclaration(node, DeclarationKind.Method) ?? generator.GetDeclaration(node, DeclarationKind.Property);
ISymbol badVisibilitySymbol = semanticModel.GetDeclaredSymbol(badVisibilityNode, cancellationToken);
SymbolEditor symbolEditor = SymbolEditor.Create(context.Document);
ISymbol newSymbol = await symbolEditor.EditOneDeclarationAsync(badVisibilitySymbol,
(documentEditor, syntaxNode) => documentEditor.SetAccessibility(badVisibilityNode, Accessibility.Public)).ConfigureAwait(false);
Document newDocument = symbolEditor.GetChangedDocuments().Single();
SyntaxNode newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return context.Document.WithSyntaxRoot(newRoot);
default:
return context.Document;
}
}