当前位置: 首页>>代码示例>>C#>>正文


C# SyntaxNode.ReplaceNodes方法代码示例

本文整理汇总了C#中Microsoft.CodeAnalysis.SyntaxNode.ReplaceNodes方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxNode.ReplaceNodes方法的具体用法?C# SyntaxNode.ReplaceNodes怎么用?C# SyntaxNode.ReplaceNodes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.CodeAnalysis.SyntaxNode的用法示例。


在下文中一共展示了SyntaxNode.ReplaceNodes方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetUpdatedDocumentAsync

 internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, Diagnostic diagnostic, CancellationToken cancellationToken)
 {
     var classSymbol = (INamedTypeSymbol)model.GetDeclaredSymbol(nodeToFix, cancellationToken);
     var instanceConstructors = classSymbol.InstanceConstructors.Where(t => t.DeclaredAccessibility == Accessibility.Public).Select(t => GetDeclaration(t)).Where(d => d != null).ToList();
     var generator = SyntaxGenerator.GetGenerator(document);
     var newRoot = root.ReplaceNodes(instanceConstructors, (original, rewritten) => generator.WithAccessibility(original, Accessibility.Protected));
     return Task.FromResult(document.WithSyntaxRoot(newRoot));
 }
开发者ID:GloryChou,项目名称:roslyn,代码行数:8,代码来源:CA1012CodeFixProvider.cs

示例2: ChangeAccessibilityCodeFix

 private async Task<Document> ChangeAccessibilityCodeFix(Document document, SyntaxNode root, SyntaxNode nodeToFix, CancellationToken cancellationToken)
 {
     var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
     var classSymbol = (INamedTypeSymbol)model.GetDeclaredSymbol(nodeToFix, cancellationToken);
     var instanceConstructors = classSymbol.InstanceConstructors.Where(t => t.DeclaredAccessibility == Accessibility.Public).Select(t => GetDeclaration(t)).Where(d => d != null).ToList();
     var generator = SyntaxGenerator.GetGenerator(document);
     var newRoot = root.ReplaceNodes(instanceConstructors, (original, rewritten) => generator.WithAccessibility(original, Accessibility.Protected));
     return document.WithSyntaxRoot(newRoot);
 }
开发者ID:maggiemsft,项目名称:roslyn-analyzers,代码行数:9,代码来源:AbstractTypesShouldNotHaveConstructors.Fixer.cs

示例3: link

        public SyntaxNode link(SyntaxNode node, out Compilation result)
        {
            var           tree  = node.SyntaxTree;
            SemanticModel model = compilation_.GetSemanticModel(node.SyntaxTree);
            node = node.ReplaceNodes(node.GetAnnotatedNodes(Compiler.LinkerAnnotationId), (oldNode, newNode) =>
            {
                var annotation = oldNode.GetAnnotations(Compiler.LinkerAnnotationId).First();
                if (oldNode.SyntaxTree != model.SyntaxTree)
                {
                    oldNode = model.SyntaxTree.GetRoot().GetAnnotatedNodes(Compiler.LinkerAnnotationId).
                                Where(i => i.GetAnnotations(Compiler.LinkerAnnotationId).First().Data == annotation.Data).First();
                }

                return ctx_.Link(oldNode, newNode, annotation.Data, model);
            });

            result = compilation_.ReplaceSyntaxTree(tree, node.SyntaxTree);
            model  = result.GetSemanticModel(node.SyntaxTree);
            return ctx_.ApplyLinkerInfo(node, model, result, out result);
        }
开发者ID:mpmedia,项目名称:Excess,代码行数:20,代码来源:Linker.cs

示例4: ChangeTypesAccessibilityInSyntaxRoot

        private static SyntaxNode ChangeTypesAccessibilityInSyntaxRoot(SyntaxNode syntaxRoot, SyntaxTokenList newAccessibilityModifiers, IEnumerable<Location> typeLocations)
        {
            var declarations =  typeLocations.Select(typeLocation => (MemberDeclarationSyntax)syntaxRoot.FindNode(typeLocation.SourceSpan)).ToList();
            var newDeclarations = new Dictionary<MemberDeclarationSyntax, MemberDeclarationSyntax>();

            foreach (var declaration in declarations)
            {
                newDeclarations.Add(declaration, ChangeAccessibilityModifiersInDeclaration(declaration, newAccessibilityModifiers));
            }

            return syntaxRoot.ReplaceNodes(declarations, (original, rewritten) => newDeclarations[original]);
        }
开发者ID:nagyistoce,项目名称:code-cracker,代码行数:12,代码来源:InconsistentAccessibilityCodeFixProvider.cs

示例5: CreateUsing

        public static SyntaxNode CreateUsing(SyntaxNode root, ObjectCreationExpressionSyntax objectCreation, SemanticModel semanticModel)
        {
            SyntaxNode newRoot;
            if (objectCreation.Parent.IsKind(SyntaxKind.SimpleAssignmentExpression))
            {
                var assignmentExpression = (AssignmentExpressionSyntax)objectCreation.Parent;
                var statement = assignmentExpression.Parent as ExpressionStatementSyntax;
                var identitySymbol = (ILocalSymbol)semanticModel.GetSymbolInfo(assignmentExpression.Left).Symbol;
                newRoot = UsedOutsideParentBlock(semanticModel, statement, identitySymbol)
                    ? CreateRootAddingDisposeToEndOfMethod(root, statement, identitySymbol)
                    : CreateRootWithUsing(root, statement, u => u.WithExpression(assignmentExpression));
            }
            else if (objectCreation.Parent.IsKind(SyntaxKind.EqualsValueClause) && objectCreation.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator))
            {
                var variableDeclarator = (VariableDeclaratorSyntax)objectCreation.Parent.Parent;
                var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent;
                var statement = (LocalDeclarationStatementSyntax)variableDeclaration.Parent;
                newRoot = CreateRootWithUsing(root, statement, u => u.WithDeclaration(variableDeclaration.WithoutLeadingTrivia()));
            }
            else if (objectCreation.Parent.IsKind(SyntaxKind.Argument))
            {
                var identifierName = GetIdentifierName(objectCreation, semanticModel);

                var variableDeclaration = SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName(@"var"))
                    .WithVariables(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(identifierName))
                    .WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.Token(SyntaxKind.EqualsToken), objectCreation))));

                var arg = objectCreation.Parent as ArgumentSyntax;
                var args = objectCreation.Parent.Parent as ArgumentListSyntax;
                var newArgs = args.ReplaceNode(arg, arg.WithExpression(SyntaxFactory.IdentifierName(identifierName)));

                StatementSyntax statement = objectCreation.FirstAncestorOfType<ExpressionStatementSyntax>();
                if (statement != null)
                {
                    var exprStatement = statement.ReplaceNode(args, newArgs);
                    var newUsingStatment = CreateUsingStatement(exprStatement, SyntaxFactory.Block(exprStatement))
                        .WithDeclaration(variableDeclaration);
                    return root.ReplaceNode(statement, newUsingStatment);
                }

                statement = (StatementSyntax)objectCreation.Ancestors().First(node => node is StatementSyntax);
                var newStatement = statement.ReplaceNode(args, newArgs);
                var statementsForUsing = new[] { newStatement }.Concat(GetChildStatementsAfter(statement));
                var usingBlock = SyntaxFactory.Block(statementsForUsing);
                var usingStatement = CreateUsingStatement(newStatement, usingBlock)
                    .WithDeclaration(variableDeclaration);
                var statementsToReplace = new List<StatementSyntax> { statement };
                statementsToReplace.AddRange(statementsForUsing.Skip(1));
                newRoot = root.ReplaceNodes(statementsToReplace, (node, _) => node.Equals(statement) ? usingStatement : null);
            }
            else
            {
                newRoot = CreateRootWithUsing(root, (ExpressionStatementSyntax)objectCreation.Parent, u => u.WithExpression(objectCreation));
            }
            return newRoot;
        }
开发者ID:Cadums01,项目名称:code-cracker,代码行数:56,代码来源:DisposableVariableNotDisposedCodeFixProvider.cs

示例6: CreateRootWithUsing

 private static SyntaxNode CreateRootWithUsing(SyntaxNode root, StatementSyntax statement, Func<UsingStatementSyntax, UsingStatementSyntax> updateUsing)
 {
     var statementsForUsing = GetChildStatementsAfter(statement);
     var statementsToReplace = new List<StatementSyntax> { statement };
     statementsToReplace.AddRange(statementsForUsing);
     var block = SyntaxFactory.Block(statementsForUsing);
     var usingStatement = updateUsing?.Invoke(CreateUsingStatement(statement, block));
     var newRoot = root.ReplaceNodes(statementsToReplace, (node, _) => node.Equals(statement) ? usingStatement : null);
     return newRoot;
 }
开发者ID:Cadums01,项目名称:code-cracker,代码行数:10,代码来源:DisposableVariableNotDisposedCodeFixProvider.cs

示例7: TraverseSyntaxTree

 private SyntaxNode TraverseSyntaxTree(SyntaxNode node)
 {
     node = node.ReplaceNodes(node.ChildNodes(), (child, dummy) => TraverseSyntaxTree(child));
     return Visit(node);
 }
开发者ID:the-ress,项目名称:ReplaceTypeKeywords,代码行数:5,代码来源:TypeKeywordsReplacer.cs

示例8: Visit

        public override void Visit(SyntaxNode node)
        {
            List<MemberDeclarationSyntax> members = new List<MemberDeclarationSyntax>();
            var newRoot = node.ReplaceNodes(node.ChildNodes().OfType<MemberDeclarationSyntax>(), (oldNode, newNode) =>
            {
                members.Add(newNode);
                return null;
            });

            if (node is CompilationUnitSyntax)
            {
                base.Visit(node);
                return;
            }

            all_++;
            if (node is MemberDeclarationSyntax)
            {
                members_.Add((MemberDeclarationSyntax)node);
            }
        }
开发者ID:mpmedia,项目名称:Excess,代码行数:21,代码来源:Compiler.cs

示例9: GetNewDocumentRoot

        private static SyntaxNode GetNewDocumentRoot(SyntaxNode docRoot, ITypeParameterSymbol typeParameterSymbol, KeyValuePair<DocumentId, List<ClassDeclarationSyntax>> classes)
        {
            var newDocRoot = docRoot.ReplaceNodes(classes.Value, (original, rewritten) => original.WithAdditionalAnnotations(annotation));
            var annotatedNodes = newDocRoot.GetAnnotatedNodes(annotation);
            while (annotatedNodes.Any())
            {
                var classDeclaration = (ClassDeclarationSyntax)annotatedNodes.First();
                var constraintClauses = GetNewConstraintClause(classDeclaration.ConstraintClauses, typeParameterSymbol.Name);
                newDocRoot = newDocRoot.ReplaceNode(
                    classDeclaration,
                    classDeclaration
                        .WithConstraintClauses(constraintClauses)
                        .WithoutAnnotations(annotation));
                annotatedNodes = newDocRoot.GetAnnotatedNodes(annotation);
            }

            return newDocRoot;
        }
开发者ID:Godin,项目名称:sonarlint-vs,代码行数:18,代码来源:GenericReadonlyFieldPropertyAssignmentCodeFixProvider.cs

示例10: CastResursiveMethod

        private static SyntaxNode CastResursiveMethod(SyntaxNode tree, SemanticModel semanticModel, GenRef genRef, Dictionary<SyntaxNode, SyntaxNode> castChanges)
        {
            var change = new Dictionary<SyntaxNode, SyntaxNode>();

            foreach (var node in tree.ChildNodes())
            {
                ITypeSymbol ts = null;
                
                // if invocation -> ITypeSymbol
                // -------------------------
                if (node is InvocationExpressionSyntax)
                {
                    ISymbol invokedSymbol = semanticModel.GetSymbolInfo(node).Symbol;

                    // if is generic method
                    if (genRef.Methods.Contains(invokedSymbol.OriginalDefinition))
                    {
                        ts = ((IMethodSymbol)invokedSymbol).ReturnType;                        
                    }
                }
                else if ((node is MemberAccessExpressionSyntax) && !(node.Parent is AssignmentExpressionSyntax))
                {
                    ISymbol invokedSymbol = semanticModel.GetSymbolInfo(node).Symbol;

                    // if is generic property
                    if (genRef.Properties.Contains(invokedSymbol.OriginalDefinition))
                    {
                        ts = ((IPropertySymbol)invokedSymbol).Type;                        
                    }
                }

                // recurse for changed node
                var casted = CastResursiveMethod(node, semanticModel, genRef, castChanges);

                if (ts != null)
                {
                    // do cast
                    casted = Helpers.CastTo((ExpressionSyntax)casted, ts);

                    if (node.Parent is MemberAccessExpressionSyntax)
                        casted = ((ExpressionSyntax)casted).Parenthesize();

                    castChanges.Add(node, casted);
                }

                // add for replace
                if (node != casted)
                    change.Add(node, casted);
            }

            if (change.Any())
                tree = tree.ReplaceNodes(change.Keys, (x, y) => change[x]);

            return tree;
        }
开发者ID:mpielikis,项目名称:gencast,代码行数:55,代码来源:Generator.cs

示例11: CastResursiveMethod

        private static SyntaxNode CastResursiveMethod(SyntaxNode tree, SemanticModel semanticModel, GenRef genRef, Dictionary<SyntaxNode, SyntaxNode> castChanges)
        {
            var change = new Dictionary<SyntaxNode, SyntaxNode>();

            foreach (var node in tree.ChildNodes())
            {
                // recurse for changed node
                var casted = CastResursiveMethod(node, semanticModel, genRef, castChanges);

                var ts = GetGenericType(node, genRef, semanticModel);

                if (ts != null)
                {
                    casted = Helpers.CastTo((ExpressionSyntax)casted, ts);

                    if (node.Parent is MemberAccessExpressionSyntax)
                        casted = ((ExpressionSyntax)casted).Parenthesize();

                    castChanges.Add(node, casted);
                }

                if (node != casted)
                    change.Add(node, casted);
            }

            if (change.Any())
                tree = tree.ReplaceNodes(change.Keys, (x, y) => change[x]);

            return tree;
        }
开发者ID:mpielikis,项目名称:retrosharp,代码行数:30,代码来源:Generator.cs

示例12: CreateRootWithUsingFromArgument

        private static SyntaxNode CreateRootWithUsingFromArgument(SyntaxNode root, ExpressionSyntax childOfArgumentNode, string identifierName)
        {
            var arg = childOfArgumentNode.Parent as ArgumentSyntax;

            var variableDeclaration = SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName(@"var"))
                .WithVariables(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(identifierName))
                .WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.Token(SyntaxKind.EqualsToken), childOfArgumentNode))));


            var args = arg.Parent as ArgumentListSyntax;
            var newArgs = args.ReplaceNode(arg, arg.WithExpression(SyntaxFactory.IdentifierName(identifierName)));

            StatementSyntax statement = childOfArgumentNode.FirstAncestorOfType<ExpressionStatementSyntax>();
            if (statement != null)
            {
                var exprStatement = statement.ReplaceNode(args, newArgs);
                var newUsingStatment = CreateUsingStatement(exprStatement, SyntaxFactory.Block(exprStatement))
                    .WithDeclaration(variableDeclaration);
                return root.ReplaceNode(statement, newUsingStatment);
            }

            statement = (StatementSyntax)childOfArgumentNode.Ancestors().First(node => node is StatementSyntax);
            var newStatement = statement.ReplaceNode(args, newArgs);
            var statementsForUsing = new[] { newStatement }.Concat(GetChildStatementsAfter(statement));
            var usingBlock = SyntaxFactory.Block(statementsForUsing);
            var usingStatement = CreateUsingStatement(newStatement, usingBlock)
                .WithDeclaration(variableDeclaration);
            var statementsToReplace = new List<StatementSyntax> { statement };
            statementsToReplace.AddRange(statementsForUsing.Skip(1));
            return root.ReplaceNodes(statementsToReplace, (node, _) => node.Equals(statement) ? usingStatement : null);
        }
开发者ID:Vossekop,项目名称:code-cracker,代码行数:31,代码来源:DisposableVariableNotDisposedCodeFixProvider.cs

示例13: CreateUsing

        public static SyntaxNode CreateUsing(SyntaxNode root, ObjectCreationExpressionSyntax objectCreation, SemanticModel semanticModel)
        {
            SyntaxNode newRoot;
            if (objectCreation.Parent.IsKind(SyntaxKind.SimpleAssignmentExpression))
            {
                var assignmentExpression = (AssignmentExpressionSyntax)objectCreation.Parent;
                var statement = assignmentExpression.Parent as ExpressionStatementSyntax;
                var identitySymbol = (ILocalSymbol)semanticModel.GetSymbolInfo(assignmentExpression.Left).Symbol;
                newRoot = UsedOutsideParentBlock(semanticModel, statement, identitySymbol)
                    ? CreateRootAddingDisposeToEndOfMethod(root, statement, identitySymbol)
                    : CreateRootWithUsing(root, statement, u => u.WithExpression(assignmentExpression));
            }
            else if (objectCreation.Parent.IsKind(SyntaxKind.EqualsValueClause) && objectCreation.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator))
            {
                var variableDeclarator = (VariableDeclaratorSyntax)objectCreation.Parent.Parent;
                var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent;
                var statement = (LocalDeclarationStatementSyntax)variableDeclaration.Parent;
                newRoot = CreateRootWithUsing(root, statement, u => u.WithDeclaration(variableDeclaration.WithoutLeadingTrivia()));
            }
            else if (objectCreation.Parent.IsKind(SyntaxKind.Argument))
            {
                var identifierName = GetIdentifierName(objectCreation, semanticModel);

                var variableDeclaration = SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName(@"var"))
                    .WithVariables(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(identifierName))
                    .WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.Token(SyntaxKind.EqualsToken), objectCreation))));

                var arg = objectCreation.Parent as ArgumentSyntax;
                var args = objectCreation.Parent.Parent as ArgumentListSyntax;
                var newArgs = args.ReplaceNode(arg, arg.WithExpression(SyntaxFactory.IdentifierName(identifierName)));

                StatementSyntax statement = objectCreation.FirstAncestorOfType<ExpressionStatementSyntax>();
                if (statement != null)
                {
                    var exprStatement = statement.ReplaceNode(args, newArgs);
                    var newUsingStatment = CreateUsingStatement(exprStatement, SyntaxFactory.Block(exprStatement))
                        .WithDeclaration(variableDeclaration);
                    return root.ReplaceNode(statement, newUsingStatment);
                }

                statement = (StatementSyntax)objectCreation.Ancestors().First(node => node is StatementSyntax);
                var newStatement = statement.ReplaceNode(args, newArgs);
                var statementsForUsing = new[] { newStatement }.Concat(GetChildStatementsAfter(statement));
                var usingBlock = SyntaxFactory.Block(statementsForUsing);
                var usingStatement = CreateUsingStatement(newStatement, usingBlock)
                    .WithDeclaration(variableDeclaration);
                var statementsToReplace = new List<StatementSyntax> { statement };
                statementsToReplace.AddRange(statementsForUsing.Skip(1));
                newRoot = root.ReplaceNodes(statementsToReplace, (node, _) => node.Equals(statement) ? usingStatement : null);
            }
            else if (objectCreation.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression))
            {
                var newVariableName = objectCreation.Type.ToString();
                var newVariableNameParts = newVariableName.Split('.');
                newVariableName = newVariableNameParts[newVariableNameParts.Length - 1].ToLowerCaseFirstLetter();
                var parentStatement = objectCreation.Parent.FirstAncestorOrSelfThatIsAStatement();
                var originalName = newVariableName;
                for (int nameIncrement = 1; ; nameIncrement++)
                {
                    var speculativeSymbol = semanticModel.GetSpeculativeSymbolInfo(parentStatement.GetLocation().SourceSpan.Start, SyntaxFactory.IdentifierName(newVariableName), SpeculativeBindingOption.BindAsExpression);
                    if (speculativeSymbol.Symbol == null) break;
                    newVariableName = originalName + nameIncrement;
                }
                var newVariable = SyntaxFactory.LocalDeclarationStatement(SyntaxFactory.VariableDeclaration(SyntaxFactory.ParseTypeName("var"),
                    SyntaxFactory.SeparatedList(new[] {
                        SyntaxFactory.VariableDeclarator(newVariableName).WithInitializer(SyntaxFactory.EqualsValueClause(objectCreation))
                    })));
                newRoot = root.TrackNodes(parentStatement, objectCreation);
                newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(objectCreation), SyntaxFactory.IdentifierName(newVariableName));
                var newTrackedParentStatement = newRoot.GetCurrentNode(parentStatement);
                newRoot = newRoot.InsertNodesBefore(newTrackedParentStatement, new[] { newVariable });
                var statement = (LocalDeclarationStatementSyntax)newRoot.GetCurrentNode(parentStatement).GetPreviousStatement();
                var variableDeclaration = statement.Declaration;
                var variableDeclarator = variableDeclaration.Variables.First();
                newRoot = CreateRootWithUsing(newRoot, statement, u => u.WithDeclaration(variableDeclaration.WithoutLeadingTrivia()));
            }
            else
            {
                newRoot = CreateRootWithUsing(root, (ExpressionStatementSyntax)objectCreation.Parent, u => u.WithExpression(objectCreation));
            }
            return newRoot;
        }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:82,代码来源:DisposableVariableNotDisposedCodeFixProvider.cs


注:本文中的Microsoft.CodeAnalysis.SyntaxNode.ReplaceNodes方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。