本文整理汇总了C#中Microsoft.CodeAnalysis.SyntaxNode.ReplaceNode方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxNode.ReplaceNode方法的具体用法?C# SyntaxNode.ReplaceNode怎么用?C# SyntaxNode.ReplaceNode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CodeAnalysis.SyntaxNode
的用法示例。
在下文中一共展示了SyntaxNode.ReplaceNode方法的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: CreateNewLiteral
private static SyntaxNode CreateNewLiteral(LiteralExpressionSyntax literal, SyntaxNode root)
{
SyntaxNode newRoot;
if (literal.Token.ValueText != literal.Token.Text)
{
var newTokenText = literal.Token.ValueText;
var newLiteral = literal.WithToken(SyntaxFactory.ParseToken(newTokenText));
newRoot = root.ReplaceNode(literal, newLiteral);
}
else
{
var value = (dynamic)literal.Token.Value;
if (literal.Parent != null && literal.Parent.IsKind(SyntaxKind.UnaryMinusExpression))
{
var newTokenText = (string)("0x" + (value * -1).ToString("X"));
var newLiteral = literal.WithToken(SyntaxFactory.ParseToken(newTokenText))
.WithLeadingTrivia(literal.Parent.GetLeadingTrivia())
.WithTrailingTrivia(literal.Parent.GetTrailingTrivia());
newRoot = root.ReplaceNode(literal.Parent, newLiteral);
}
else
{
var newTokenText = (string)("0x" + value.ToString("X"));
var newLiteral = literal.WithToken(SyntaxFactory.ParseToken(newTokenText));
newRoot = root.ReplaceNode(literal, newLiteral);
}
}
return newRoot;
}
示例3: UseExpressionBodiedMemberAsync
private Task<Solution> UseExpressionBodiedMemberAsync(Document document, SyntaxNode root, SyntaxNode statement)
{
var returnStatement = (ReturnStatementSyntax) statement;
var expression = returnStatement.Expression;
var arrowClause = SyntaxFactory.ArrowExpressionClause(expression);
var property = statement.AncestorsAndSelf().OfType<PropertyDeclarationSyntax>().FirstOrDefault();
if (property != null)
{
var newProperty = property.RemoveNode(property.AccessorList, SyntaxRemoveOptions.KeepNoTrivia)
.WithExpressionBody(arrowClause)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
root = root.ReplaceNode(property, newProperty);
}
var method = statement.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().FirstOrDefault();
if (method != null)
{
root = root.ReplaceNode(method, method.RemoveNode(method.Body, SyntaxRemoveOptions.KeepNoTrivia)
.WithExpressionBody(arrowClause)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
}
return Task.FromResult(document.WithSyntaxRoot(root).Project.Solution);
}
示例4: CalculateNewRoot
private static SyntaxNode CalculateNewRoot(SyntaxNode root, IfStatementSyntax ifStatement)
{
SyntaxNode newRoot;
var isTrue = ifStatement.Condition.IsKind(SyntaxKind.TrueLiteralExpression);
if (isTrue)
{
var block = ifStatement.Statement as BlockSyntax;
newRoot = block == null
? root.ReplaceNode(ifStatement, ifStatement.Statement)
: root.ReplaceNode(ifStatement, block.Statements);
}
else
{
if (ifStatement.Else == null)
{
newRoot = root.RemoveNode(ifStatement, SyntaxRemoveOptions.KeepNoTrivia);
}
else
{
var block = ifStatement.Else.Statement as BlockSyntax;
newRoot = block == null
? root.ReplaceNode(ifStatement, ifStatement.Else.Statement)
: root.ReplaceNode(ifStatement, block.Statements);
}
}
return newRoot.WithAdditionalAnnotations(Formatter.Annotation);
}
开发者ID:peterstevens130561,项目名称:sonarlint-vs,代码行数:29,代码来源:IfConditionalAlwaysTrueOrFalseCodeFixProvider.cs
示例5: ReplaceInvocation
private static SyntaxNode ReplaceInvocation(InvocationExpressionSyntax invocation, ExpressionSyntax newInvocation, SyntaxNode root)
{
if (invocation.Parent.IsKind(SyntaxKind.LogicalNotExpression))
return root.ReplaceNode(invocation.Parent, newInvocation);
var negatedInvocation = SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, newInvocation);
var newRoot = root.ReplaceNode(invocation, negatedInvocation);
return newRoot;
}
示例6: ReplaceInvocation
private static SyntaxNode ReplaceInvocation(InvocationExpressionSyntax invocation, ExpressionSyntax newInvocation, SyntaxNode root)
{
ExpressionSyntax lastExpression = invocation;
while (lastExpression.Parent is ExpressionSyntax)
lastExpression = (ExpressionSyntax)lastExpression.Parent;
var lastExpressionWithNewInvocation = lastExpression.ReplaceNode(invocation, newInvocation);
if (lastExpression.IsKind(SyntaxKind.LogicalNotExpression))
return root.ReplaceNode(lastExpression, ((PrefixUnaryExpressionSyntax)lastExpressionWithNewInvocation).Operand);
var negatedLastExpression = SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, lastExpressionWithNewInvocation);
var newRoot = root.ReplaceNode(lastExpression, negatedLastExpression);
return newRoot;
}
示例7: ConvertToInterpolatedString
private Task<Document> ConvertToInterpolatedString(Document document, SyntaxNode root, InvocationExpressionSyntax invocation, CancellationToken cancellationToken)
{
string previousString = null;
var parts = new List<InterpolatedStringContentSyntax>(invocation.ArgumentList.Arguments.Count);
for (int i = 0; i < invocation.ArgumentList.Arguments.Count; i++)
{
ArgumentSyntax argument = invocation.ArgumentList.Arguments[i];
var literal = argument.Expression as LiteralExpressionSyntax;
if (literal?.IsKind(SyntaxKind.StringLiteralExpression) ?? false)
{
//strings needs to be collapsed, otherwise VS will insert additional whitespaces
previousString += literal.Token.Text.Substring(1, literal.Token.Text.Length - 2);
}
else
{
if (previousString != null)
{
parts.Add(InterpolatedStringGenerator.TextPart(previousString));
previousString = null;
}
parts.Add(InterpolatedStringGenerator.ExpressionPart(argument.Expression.WithoutLeadingTrivia().WithoutTrailingTrivia()));
}
}
if (previousString != null)
{
parts.Add(InterpolatedStringGenerator.TextPart(previousString));
}
SyntaxNode interpolated = InterpolatedStringGenerator.InterpolatedString(parts);
root = root.ReplaceNode(invocation, interpolated);
return Task.FromResult(document.WithSyntaxRoot(root));
}
示例8: 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);
}
示例9: MakePublicAsync
private Task<Solution> MakePublicAsync(Document document, SyntaxNode root, MethodDeclarationSyntax method)
{
var generator = SyntaxGenerator.GetGenerator(document);
var newMethod = generator.WithAccessibility(method, Accessibility.Public);
var newRoot = root.ReplaceNode(method, newMethod);
return Task.FromResult(document.WithSyntaxRoot(newRoot).Project.Solution);
}
示例10: RemoveRethrowAsync
private Task<Solution> RemoveRethrowAsync(Document document, SyntaxNode root, ThrowStatementSyntax throwStatement)
{
var newStatement = SyntaxFactory.ThrowStatement();
var newRoot = root.ReplaceNode(throwStatement, newStatement);
var newDocument = document.WithSyntaxRoot(newRoot);
return Task.FromResult(newDocument.Project.Solution);
}
示例11: GetUpdatedDocumentAsync
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
//// We are going to implement IDisposable interface:
////
//// public void Dispose()
//// {
//// throw new NotImplementedException();
//// }
var syntaxNode = nodeToFix as ClassDeclarationSyntax;
if (syntaxNode == null)
{
return Task.FromResult(document);
}
var statement = CreateThrowNotImplementedStatement(model);
if (statement == null)
{
return Task.FromResult(document);
}
var member = CreateSimpleMethodDeclaration(CA1001DiagnosticAnalyzer.Dispose, statement);
var newNode =
syntaxNode.BaseList != null ?
syntaxNode.AddBaseListTypes(SyntaxFactory.ParseTypeName(CA1001DiagnosticAnalyzer.IDisposable)).AddMembers(new[] { member }) :
syntaxNode.AddBaseListTypes(SyntaxFactory.ParseTypeName(CA1001DiagnosticAnalyzer.IDisposable)).AddMembers(new[] { member }).WithIdentifier(syntaxNode.Identifier.WithTrailingTrivia(SyntaxFactory.Space));
newNode = newNode.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);
return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(nodeToFix, newNode)));
}
示例12: 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);
}
示例13: PerformAction
static Document PerformAction(Document document, SyntaxNode root, InvocationExpressionSyntax invocationNode)
{
var arg = invocationNode.ArgumentList.Arguments.Select(a => a.Expression).First();
if (!arg.DescendantNodesAndSelf().OfType<BinaryExpressionSyntax>().All(bop => bop.IsKind(SyntaxKind.BitwiseOrExpression)))
return document;
arg = ConvertBitwiseFlagComparisonToHasFlagsCodeRefactoringProvider.MakeFlatExpression(arg, SyntaxKind.BitwiseAndExpression);
if (arg is BinaryExpressionSyntax)
arg = SyntaxFactory.ParenthesizedExpression(arg);
SyntaxNode nodeToReplace = invocationNode;
while (nodeToReplace.Parent is ParenthesizedExpressionSyntax)
nodeToReplace = nodeToReplace.Parent;
bool negateHasFlags = nodeToReplace.Parent != null && nodeToReplace.Parent.IsKind(SyntaxKind.LogicalNotExpression);
if (negateHasFlags)
nodeToReplace = nodeToReplace.Parent;
var expr = SyntaxFactory.BinaryExpression(
negateHasFlags ? SyntaxKind.EqualsExpression : SyntaxKind.NotEqualsExpression,
SyntaxFactory.ParenthesizedExpression(SyntaxFactory.BinaryExpression(SyntaxKind.BitwiseAndExpression, ((MemberAccessExpressionSyntax)invocationNode.Expression).Expression, arg))
.WithAdditionalAnnotations(Formatter.Annotation),
SyntaxFactory.ParseExpression("0")
);
var newRoot = root.ReplaceNode((SyntaxNode)
nodeToReplace,
expr.WithAdditionalAnnotations(Formatter.Annotation)
);
return document.WithSyntaxRoot(newRoot);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:31,代码来源:ConvertHasFlagsToBitwiseFlagComparisonCodeRefactoringProvider.cs
示例14: 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);
}
}
示例15: 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);
}