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


C# Document.WithSyntaxRoot方法代码示例

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


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

示例1: FixAllAsync

        private async Task<Document> FixAllAsync(
            Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            // Create an editor to do all the transformations.  This allows us to fix all
            // the diagnostics in a clean manner.  If we used the normal batch fix provider
            // then it might fail to apply all the individual text changes as many of the 
            // changes produced by the diff might end up overlapping others.
            var editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
            var options = document.Project.Solution.Workspace.Options;

            // Attempt to use an out-var declaration if that's the style the user prefers.
            // Note: if using 'var' would cause a problem, we will use the actual type
            // of hte local.  This is necessary in some cases (for example, when the
            // type of the out-var-decl affects overload resolution or generic instantiation).
            var useVarWhenDeclaringLocals = options.GetOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals);
            var useImplicitTypeForIntrinsicTypes = options.GetOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes).Value;

            foreach (var diagnostic in diagnostics)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await AddEditsAsync(document, editor, diagnostic, 
                    useVarWhenDeclaringLocals, useImplicitTypeForIntrinsicTypes, 
                    cancellationToken).ConfigureAwait(false);
            }

            var newRoot = editor.GetChangedRoot();
            return document.WithSyntaxRoot(newRoot);
        }
开发者ID:otawfik-ms,项目名称:roslyn,代码行数:30,代码来源:CSharpInlineDeclarationCodeFixProvider.cs

示例2: AddImportsAsync

        public async Task<Document> AddImportsAsync(Document document, IEnumerable<TextSpan> spans, OptionSet options, CancellationToken cancellationToken)
        {
            options = options ?? document.Project.Solution.Workspace.Options;

            var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);

            // Create a simple interval tree for simplification spans.
            var spansTree = new SimpleIntervalTree<TextSpan>(TextSpanIntervalIntrospector.Instance, spans);

            Func<SyntaxNodeOrToken, bool> isInSpan = (nodeOrToken) =>
                spansTree.GetOverlappingIntervals(nodeOrToken.FullSpan.Start, nodeOrToken.FullSpan.Length).Any();

            var nodesWithExplicitNamespaces = root.DescendantNodesAndSelf().Where(n => isInSpan(n) && GetExplicitNamespaceSymbol(n, model) != null).ToList();

            var namespacesToAdd = new HashSet<INamespaceSymbol>();
            namespacesToAdd.AddRange(nodesWithExplicitNamespaces.Select(n => GetExplicitNamespaceSymbol(n, model)));

            // annotate these nodes so they get simplified later
            var newRoot = root.ReplaceNodes(nodesWithExplicitNamespaces, (o, r) => r.WithAdditionalAnnotations(Simplifier.Annotation));
            var newDoc = document.WithSyntaxRoot(newRoot);
            var newModel = await newDoc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            newRoot = await this.AddNamespaceImportsAsync(newDoc, newModel, options, namespacesToAdd, cancellationToken).ConfigureAwait(false);
            return document.WithSyntaxRoot(newRoot);
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:26,代码来源:ImportAdderService.cs

示例3: RemoveUnnecessaryImports

        public Document RemoveUnnecessaryImports(Document document, SemanticModel model, SyntaxNode root, CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.Refactoring_RemoveUnnecessaryImports_CSharp, cancellationToken))
            {
                var unnecessaryImports = GetUnnecessaryImports(model, root, cancellationToken) as ISet<UsingDirectiveSyntax>;
                if (unnecessaryImports == null)
                {
                    return document;
                }

                var oldRoot = (CompilationUnitSyntax)root;
                if (unnecessaryImports.Any(import => oldRoot.OverlapsHiddenPosition(cancellationToken)))
                {
                    return document;
                }

                var newRoot = (CompilationUnitSyntax)new Rewriter(unnecessaryImports, cancellationToken).Visit(oldRoot);
                if (cancellationToken.IsCancellationRequested)
                {
                    return null;
                }

                return document.WithSyntaxRoot(FormatResult(document, newRoot, cancellationToken));
            }
        }
开发者ID:GloryChou,项目名称:roslyn,代码行数:25,代码来源:CSharpRemoveUnnecessaryImportsService.cs

示例4: GetFixesAsync

        internal async override Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, CancellationToken cancellationToken)
        {
            IEnumerable<CodeAction> actions = null;

            // Fix 1: Add a NonSerialized attribute to the field
            var fieldNode = GetFieldDeclarationNode(nodeToFix);
            if (fieldNode != null)
            { 
                var attr = CodeGenerationSymbolFactory.CreateAttributeData(WellKnownTypes.NonSerializedAttribute(model.Compilation));
                var newNode = CodeGenerator.AddAttributes(fieldNode, document.Project.Solution.Workspace, SpecializedCollections.SingletonEnumerable(attr)).WithAdditionalAnnotations(Formatting.Formatter.Annotation);
                var newDocument = document.WithSyntaxRoot(root.ReplaceNode(fieldNode, newNode));
                var codeAction = CodeAction.Create(FxCopFixersResources.AddNonSerializedAttribute, newDocument);
                actions = SpecializedCollections.SingletonEnumerable(codeAction);

                // Fix 2: If the type of the field is defined in source, then add the serializable attribute to the type.
                var fieldSymbol = model.GetDeclaredSymbol(nodeToFix) as IFieldSymbol;
                var type = fieldSymbol.Type;
                if (type.Locations.Any(l => l.IsInSource))
                {
                    var typeDeclNode = type.DeclaringSyntaxReferences.First().GetSyntax();
                    var serializableAttr = CodeGenerationSymbolFactory.CreateAttributeData(WellKnownTypes.SerializableAttribute(model.Compilation));
                    var newTypeDeclNode = CodeGenerator.AddAttributes(typeDeclNode, document.Project.Solution.Workspace, SpecializedCollections.SingletonEnumerable(serializableAttr)).WithAdditionalAnnotations(Formatting.Formatter.Annotation);

                    var documentContainingNode = document.Project.Solution.GetDocument(typeDeclNode.SyntaxTree);
                    var docRoot = await documentContainingNode.GetSyntaxRootAsync(cancellationToken);
                    var newDocumentContainingNode = documentContainingNode.WithSyntaxRoot(docRoot.ReplaceNode(typeDeclNode, newTypeDeclNode));
                    var typeCodeAction = CodeAction.Create(FxCopFixersResources.AddSerializableAttribute, newDocumentContainingNode.Project.Solution);

                    actions = actions.Concat(typeCodeAction);
                }
            }

            return actions;
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:34,代码来源:CA2235CodeFixProviderBase.cs

示例5: GetUpdatedDocumentAsync

 internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, Diagnostic diagnostic, CancellationToken cancellationToken)
 {
     var generator = SyntaxGenerator.GetGenerator(document);
     var attr = generator.Attribute(generator.TypeExpression(WellKnownTypes.SerializableAttribute(model.Compilation)));
     var newNode = generator.AddAttributes(nodeToFix, attr);
     return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(nodeToFix, newNode)));
 }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:7,代码来源:CA2237CodeFixProvider.cs

示例6: FixAllAsync

        private async Task<Document> FixAllAsync(
            Document document, 
            ImmutableArray<Diagnostic> diagnostics, 
            CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
            var generator = editor.Generator;

            foreach (var diagnostic in diagnostics)
            {
                var ifStatement = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan);
                var throwStatementExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan);
                var assignmentValue = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan);

                // First, remote the if-statement entirely.
                editor.RemoveNode(ifStatement);

                // Now, update the assignemnt value to go from 'a' to 'a ?? throw ...'.
                editor.ReplaceNode(assignmentValue,
                    generator.CoalesceExpression(assignmentValue,
                    generator.ThrowExpression(throwStatementExpression)));
            }

            var newRoot = editor.GetChangedRoot();
            return document.WithSyntaxRoot(newRoot);
        }
开发者ID:jkotas,项目名称:roslyn,代码行数:28,代码来源:UseThrowExpressionCodeFixProvider.cs

示例7: HandleDeclarationAsync

        private async Task<Document> HandleDeclarationAsync(Document document, SyntaxNode root, SyntaxNode node, CancellationToken cancellationToken)
        {
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var declarationContext = node.Parent;

            TypeSyntax typeSyntax = null;
            if (declarationContext is VariableDeclarationSyntax)
            {
                typeSyntax = ((VariableDeclarationSyntax)declarationContext).Type;
            }
            else if (declarationContext is ForEachStatementSyntax)
            {
                typeSyntax = ((ForEachStatementSyntax)declarationContext).Type;
            }
            else
            {
                Contract.Fail($"unhandled kind {declarationContext.Kind().ToString()}");
            }

            var typeSymbol = semanticModel.GetTypeInfo(typeSyntax).ConvertedType;

            var typeName = typeSymbol.GenerateTypeSyntax()
                                     .WithLeadingTrivia(node.GetLeadingTrivia())
                                     .WithTrailingTrivia(node.GetTrailingTrivia());

            Debug.Assert(!typeName.ContainsDiagnostics, "Explicit type replacement likely introduced an error in code");

            var newRoot = root.ReplaceNode(node, typeName);
            return document.WithSyntaxRoot(newRoot);
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:30,代码来源:UseExplicitTypeCodeFixProvider.cs

示例8: AddStaticKeyword

 private Task<Document> AddStaticKeyword(Document document, SyntaxNode root, ClassDeclarationSyntax classDeclaration)
 {
     var staticKeyword = SyntaxFactory.Token(SyntaxKind.StaticKeyword).WithAdditionalAnnotations(Formatter.Annotation);
     var newDeclaration = classDeclaration.AddModifiers(staticKeyword);
     var newRoot = root.ReplaceNode(classDeclaration, newDeclaration);
     return Task.FromResult(document.WithSyntaxRoot(newRoot));
 }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:7,代码来源:CA1052CSharpCodeFixProvider.cs

示例9: HandleSingleIfStatementForm

        private Document HandleSingleIfStatementForm(Document document, SyntaxNode root, Diagnostic diagnostic)
        {
            var ifStatementLocation = diagnostic.AdditionalLocations[0];
            var expressionStatementLocation = diagnostic.AdditionalLocations[1];

            var ifStatement = (IfStatementSyntax)root.FindNode(ifStatementLocation.SourceSpan);
            var expressionStatement = (ExpressionStatementSyntax)root.FindNode(expressionStatementLocation.SourceSpan);
            var invocationExpression = (InvocationExpressionSyntax)expressionStatement.Expression;

            StatementSyntax newStatement = expressionStatement.WithExpression(
                SyntaxFactory.ConditionalAccessExpression(
                    invocationExpression.Expression,
                    SyntaxFactory.InvocationExpression(
                        SyntaxFactory.MemberBindingExpression(SyntaxFactory.IdentifierName(nameof(Action.Invoke))), invocationExpression.ArgumentList)));
            newStatement = newStatement.WithPrependedLeadingTrivia(ifStatement.GetLeadingTrivia());

            if (ifStatement.Parent.IsKind(SyntaxKind.ElseClause) && ifStatement.Statement.IsKind(SyntaxKind.Block))
            {
                newStatement = ((BlockSyntax)ifStatement.Statement).WithStatements(SyntaxFactory.SingletonList(newStatement));
            }

            newStatement = newStatement.WithAdditionalAnnotations(Formatter.Annotation);

            var newRoot = root.ReplaceNode(ifStatement, newStatement);
            return document.WithSyntaxRoot(newRoot);
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:26,代码来源:InvokeDelegateWithConditionalAccessCodeFixProvider.cs

示例10: AddNonSerializedAttribute

 private Task<Document> AddNonSerializedAttribute(Document document, SemanticModel model, SyntaxNode root, SyntaxNode fieldNode, SyntaxGenerator generator)
 {
     var attr = generator.Attribute(generator.TypeExpression(WellKnownTypes.NonSerializedAttribute(model.Compilation)));
     var newNode = generator.AddAttributes(fieldNode, attr);
     var newDocument = document.WithSyntaxRoot(root.ReplaceNode(fieldNode, newNode));
     return Task.FromResult(newDocument);
 }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:7,代码来源:CA2235CodeFixProviderBase.cs

示例11: GetUpdatedDocumentAsync

        internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
        {
            //// We are going to add two operators:
            ////
            ////        public static bool operator ==(A left, A right)
            ////        {
            ////            throw new NotImplementedException();
            ////        }
            ////
            ////        public static bool operator !=(A left, A right)
            ////        {
            ////            throw new NotImplementedException();
            ////        }

            var syntaxNode = nodeToFix as StructDeclarationSyntax;
            if (syntaxNode == null)
            {
                return Task.FromResult(document);
            }

            var statement = CreateThrowNotImplementedStatement(model);
            if (statement == null)
            {
                return Task.FromResult(document);
            }

            var parameters = new[] { CreateParameter(syntaxNode.Identifier.ValueText, LeftName), CreateParameter(syntaxNode.Identifier.ValueText, RightName) };

            var op_equality = CreateOperatorDeclaration(SyntaxKind.EqualsEqualsToken, parameters, statement);
            var op_inequality = CreateOperatorDeclaration(SyntaxKind.ExclamationEqualsToken, parameters, statement);
            var newNode = syntaxNode.AddMembers(new[] { op_equality, op_inequality }).WithAdditionalAnnotations(Formatter.Annotation);

            return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(nodeToFix, newNode)));
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:34,代码来源:CA2231CSharpCodeFixProvider.cs

示例12: GetUpdatedDocumentAsync

        internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
        {
            // if nothing can be fixed, return the unchanged node
            var newRoot = root;
            var kind = nodeToFix.CSharpKind();
            var syntaxFactoryService = document.GetLanguageService<SyntaxGenerator>();
            switch (kind)
            {
                case SyntaxKind.Argument:
                    // StringComparison.CurrentCulture => StringComparison.Ordinal
                    // StringComparison.CurrentCultureIgnoreCase => StringComparison.OrdinalIgnoreCase
                    var argument = (ArgumentSyntax)nodeToFix;
                    var memberAccess = argument.Expression as MemberAccessExpressionSyntax;
                    if (memberAccess != null)
                    {
                        // preserve the "IgnoreCase" suffix if present
                        bool isIgnoreCase = memberAccess.Name.GetText().ToString().EndsWith(CA1309DiagnosticAnalyzer.IgnoreCaseText);
                        var newOrdinalText = isIgnoreCase ? CA1309DiagnosticAnalyzer.OrdinalIgnoreCaseText : CA1309DiagnosticAnalyzer.OrdinalText;
                        var newIdentifier = syntaxFactoryService.IdentifierName(newOrdinalText);
                        var newMemberAccess = memberAccess.WithName((SimpleNameSyntax)newIdentifier).WithAdditionalAnnotations(Formatter.Annotation);
                        newRoot = root.ReplaceNode(memberAccess, newMemberAccess);
                    }

                    break;
                case SyntaxKind.IdentifierName:
                    // string.Equals(a, b) => string.Equals(a, b, StringComparison.Ordinal)
                    // string.Compare(a, b) => string.Compare(a, b, StringComparison.Ordinal)
                    var identifier = (IdentifierNameSyntax)nodeToFix;
                    var invokeParent = identifier.GetAncestor<InvocationExpressionSyntax>();
                    if (invokeParent != null)
                    {
                        var methodSymbol = model.GetSymbolInfo(identifier).Symbol as IMethodSymbol;
                        if (methodSymbol != null && CanAddStringComparison(methodSymbol))
                        {
                            // append a new StringComparison.Ordinal argument
                            var newArg = syntaxFactoryService.Argument(CreateOrdinalMemberAccess(syntaxFactoryService, model))
                                .WithAdditionalAnnotations(Formatter.Annotation);
                            var newInvoke = invokeParent.AddArgumentListArguments((ArgumentSyntax)newArg).WithAdditionalAnnotations(Formatter.Annotation);
                            newRoot = root.ReplaceNode(invokeParent, newInvoke);
                        }
                    }

                    break;
                case SyntaxKind.EqualsExpression:
                case SyntaxKind.NotEqualsExpression:
                    // "a == b" => "string.Equals(a, b, StringComparison.Ordinal)"
                    // "a != b" => "!string.Equals(a, b, StringComparison.Ordinal)"
                    var binaryExpression = (BinaryExpressionSyntax)nodeToFix;
                    var invocation = CreateEqualsExpression(syntaxFactoryService, model, binaryExpression.Left, binaryExpression.Right, kind == SyntaxKind.EqualsExpression).WithAdditionalAnnotations(Formatter.Annotation);
                    newRoot = root.ReplaceNode(nodeToFix, invocation);
                    break;
            }

            if (newRoot == root)
            {
                return Task.FromResult(document);
            }

            return Task.FromResult(document.WithSyntaxRoot(newRoot));
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:60,代码来源:CA1309CSharpCodeFixProvider.cs

示例13: ConvertDocCommentsToRegularComments

        protected override async Task<Document> ConvertDocCommentsToRegularComments(Document document, IDocumentationCommentFormattingService docCommentFormattingService, CancellationToken cancellationToken)
        {
            var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var newSyntaxRoot = DocCommentConverter.ConvertToRegularComments(syntaxRoot, docCommentFormattingService, cancellationToken);

            return document.WithSyntaxRoot(newSyntaxRoot);
        }
开发者ID:noahfalk,项目名称:roslyn,代码行数:8,代码来源:CSharpMetadataAsSourceService.cs

示例14: 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:ehsansajjad465,项目名称:roslyn,代码行数:8,代码来源:CA1012CodeFixProvider.cs

示例15: OrganizeImportsAsync

        public async Task<Document> OrganizeImportsAsync(Document document, bool placeSystemNamespaceFirst, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var rewriter = new Rewriter(placeSystemNamespaceFirst);
            var newRoot = rewriter.Visit(root);

            return document.WithSyntaxRoot(newRoot);
        }
开发者ID:vslsnap,项目名称:roslyn,代码行数:8,代码来源:CSharpOrganizeImportsService.cs


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