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


C# Document.WithSyntaxRoot方法代码示例

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


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

示例1: MakeAutoPropertyAsync

 public async static Task<Solution> MakeAutoPropertyAsync(Document document, SyntaxNode root, PropertyDeclarationSyntax property, CancellationToken cancellationToken)
 {
     var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
     var getterReturn = (ReturnStatementSyntax)property.AccessorList.Accessors.First(a => a.Keyword.ValueText == "get").Body.Statements.First();
     var returnIdentifier = (IdentifierNameSyntax)(getterReturn.Expression is MemberAccessExpressionSyntax ? ((MemberAccessExpressionSyntax)getterReturn.Expression).Name : getterReturn.Expression);
     var returnIdentifierSymbol = semanticModel.GetSymbolInfo(returnIdentifier).Symbol;
     var variableDeclarator = (VariableDeclaratorSyntax)returnIdentifierSymbol.DeclaringSyntaxReferences.First().GetSyntax();
     var fieldDeclaration = variableDeclarator.FirstAncestorOfType<FieldDeclarationSyntax>();
     root = root.TrackNodes(returnIdentifier, fieldDeclaration, property);
     document = document.WithSyntaxRoot(root);
     root = await document.GetSyntaxRootAsync(cancellationToken);
     semanticModel = await document.GetSemanticModelAsync(cancellationToken);
     returnIdentifier = root.GetCurrentNode(returnIdentifier);
     returnIdentifierSymbol = semanticModel.GetSymbolInfo(returnIdentifier).Symbol;
     var newProperty = GetSimpleProperty(property, variableDeclarator)
         .WithTriviaFrom(property)
         .WithAdditionalAnnotations(Formatter.Annotation);
     var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, returnIdentifierSymbol, property.Identifier.ValueText, document.Project.Solution.Workspace.Options, cancellationToken);
     document = newSolution.GetDocument(document.Id);
     root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
     root = root.InsertNodesAfter(root.GetCurrentNode(property), new[] { newProperty });
     var multipleVariableDeclaration = fieldDeclaration.Declaration.Variables.Count > 1;
     if (multipleVariableDeclaration)
     {
         var newfieldDeclaration = fieldDeclaration.WithDeclaration(fieldDeclaration.Declaration.RemoveNode(variableDeclarator, SyntaxRemoveOptions.KeepNoTrivia));
         root = root.RemoveNode(root.GetCurrentNode<SyntaxNode>(property), SyntaxRemoveOptions.KeepNoTrivia);
         root = root.ReplaceNode(root.GetCurrentNode(fieldDeclaration), newfieldDeclaration);
     }
     else
     {
         root = root.RemoveNodes(root.GetCurrentNodes<SyntaxNode>(new SyntaxNode[] { fieldDeclaration, property }), SyntaxRemoveOptions.KeepNoTrivia);
     }
     document = document.WithSyntaxRoot(root);
     return document.Project.Solution;
 }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:35,代码来源:SwitchToAutoPropCodeFixProvider.cs

示例2: Fix

		static async Task<Document> Fix(Document document, AwaitExpressionSyntax node, CancellationToken cancellationToken)
		{
			var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
			var expression = Checker.FindExpressionForConfigureAwait(node);
			if (expression != null)
			{
				if (!Checker.IsConfigureAwait(expression.Expression))
				{
					var falseExpression = SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression);
					var newExpression = SyntaxFactory.InvocationExpression(
						SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expression, SyntaxFactory.IdentifierName(Checker.ConfigureAwaitIdentifier)),
						SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Argument(falseExpression) })));
					return document.WithSyntaxRoot(root.ReplaceNode(expression, newExpression.WithAdditionalAnnotations(Formatter.Annotation)));
				}
				if (!Checker.HasFalseArgument(expression.ArgumentList))
				{
					var falseExpression = SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression);
					var newExpression = SyntaxFactory.InvocationExpression(expression.Expression,
						SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Argument(falseExpression) })));
					return document.WithSyntaxRoot(root.ReplaceNode(expression, newExpression.WithAdditionalAnnotations(Formatter.Annotation)));
				}
			}
			else
			{
				var falseExpression = SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression);
				var newExpression = SyntaxFactory.InvocationExpression(
					SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, node.Expression, SyntaxFactory.IdentifierName(Checker.ConfigureAwaitIdentifier)),
					SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Argument(falseExpression) })));
				return document.WithSyntaxRoot(root.ReplaceNode(node.Expression, newExpression.WithAdditionalAnnotations(Formatter.Annotation)));
			}
			throw new InvalidOperationException();
		}
开发者ID:cincuranet,项目名称:ConfigureAwaitChecker,代码行数:32,代码来源:CodeFixProvider.cs

示例3: EnforceAsync

        public async Task<Solution> EnforceAsync(Document document)
        {
            if (document == null) { throw new ArgumentNullException(nameof(document)); }

            IReadOnlyList<string> headerComments = document.GetOption(HeaderComments);
            string newLineText = document.GetOption(GlobalOptions.NewLineText);
            SyntaxTriviaList commentTrivia = this.commentCache.GetOrAdd(
                headerComments, c => BuildCommentTrivia(headerComments, newLineText));

            SyntaxNode syntaxRoot = await document.GetSyntaxRootAsync();

            if (syntaxRoot.HasLeadingTrivia)
            {
                SyntaxTriviaList leadingTrivia = syntaxRoot.GetLeadingTrivia();
                if (!leadingTrivia.IsEquivalentTo(commentTrivia))
                {
                    Log.WriteInformation("{0}: Rewriting non-conforming header comment", document.Name);
                    syntaxRoot = syntaxRoot.WithLeadingTrivia().WithLeadingTrivia(commentTrivia);
                    document = document.WithSyntaxRoot(syntaxRoot);
                }
            }
            else if (commentTrivia.Count > 0)
            {
                Log.WriteInformation("{0}: Adding missing header comment", document.Name);
                syntaxRoot = syntaxRoot.WithLeadingTrivia(commentTrivia);
                document = document.WithSyntaxRoot(syntaxRoot);
            }

            return document.Project.Solution;
        }
开发者ID:nicholjy,项目名称:stylize,代码行数:30,代码来源:HeaderCommentStyleRule.cs

示例4: UseEmptyStringAsync

 private async static Task<Document> UseEmptyStringAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
 {
     var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
     var literal = root.FindNode(diagnostic.Location.SourceSpan).DescendantNodesAndSelf().OfType<MemberAccessExpressionSyntax>().First();
     var newRoot = root.ReplaceNode(literal, SyntaxFactory.ParseExpression(EmptyString).WithLeadingTrivia(literal.GetLeadingTrivia()).WithTrailingTrivia(literal.GetTrailingTrivia()));
     var newDocument = document.WithSyntaxRoot(newRoot);
     return document.WithSyntaxRoot(newRoot);
 }
开发者ID:JeanLLopes,项目名称:code-cracker,代码行数:8,代码来源:UseEmptyStringCodeFixProvider.cs

示例5: IntroduceFieldFromConstructorDocumentAsync

 public async static Task<Document> IntroduceFieldFromConstructorDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
 {
     var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
     var diagnosticSpan = diagnostic.Location.SourceSpan;
     var parameter = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<ParameterSyntax>().First();
     var constructor = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<ConstructorDeclarationSyntax>().First();
     var newRoot = IntroduceFieldFromConstructor(root, constructor, parameter);
     var newDocument = document.WithSyntaxRoot(newRoot);
     return document.WithSyntaxRoot(newRoot);
 }
开发者ID:Vossekop,项目名称:code-cracker,代码行数:10,代码来源:IntroduceFieldFromConstructorCodeFixProvider.cs

示例6: GetTransformedDocumentAsync

        private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic)
        {
            var syntaxRoot = await document.GetSyntaxRootAsync().ConfigureAwait(false);
            var node = syntaxRoot?.FindNode(diagnostic.Location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
            if (node != null && node.IsKind(SyntaxKind.RegionDirectiveTrivia))
            {
                var regionDirective = node as RegionDirectiveTriviaSyntax;

                var newSyntaxRoot = syntaxRoot.RemoveNodes(regionDirective.GetRelatedDirectives(), SyntaxRemoveOptions.AddElasticMarker);

                return document.WithSyntaxRoot(newSyntaxRoot);
            }

            return document.WithSyntaxRoot(syntaxRoot);
        }
开发者ID:robinsedlaczek,项目名称:StyleCopAnalyzers,代码行数:15,代码来源:RemoveRegionCodeFixProvider.cs

示例7: GetTransformedDocumentAsync

        private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var token = syntaxRoot.FindToken(diagnostic.Location.SourceSpan.Start);
            var triviaList = token.LeadingTrivia;

            var index = triviaList.Count - 1;
            while (!triviaList[index].IsKind(SyntaxKind.EndOfLineTrivia))
            {
                index--;
            }

            var lastEndOfLine = index;

            while (!triviaList[index].IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia))
            {
                index--;
            }

            var lastDocumentation = index;

            var newLeadingTrivia = triviaList.Take(lastDocumentation + 1).Concat(triviaList.Skip(lastEndOfLine + 1));
            var newSyntaxRoot = syntaxRoot.ReplaceToken(token, token.WithLeadingTrivia(newLeadingTrivia));

            return document.WithSyntaxRoot(newSyntaxRoot);
        }
开发者ID:nukefusion,项目名称:StyleCopAnalyzers,代码行数:27,代码来源:SA1506CodeFixProvider.cs

示例8: AddConfigureAwaitAsync

        private static async Task<Document> AddConfigureAwaitAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken, bool continueOnCapturedContext)
        {
            SyntaxKind continueOnCapturedContextSyntax;
            switch (continueOnCapturedContext)
            {
                case true:
                    continueOnCapturedContextSyntax = SyntaxKind.TrueLiteralExpression;
                    break;
                default:
                    continueOnCapturedContextSyntax = SyntaxKind.FalseLiteralExpression;
                    break;
            }

            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var awaitExpression = (AwaitExpressionSyntax)root.FindNode(diagnostic.Location.SourceSpan);
            var expression = awaitExpression.Expression;

            var newExpression = SyntaxFactory.InvocationExpression(
                SyntaxFactory.MemberAccessExpression(
                    SyntaxKind.SimpleMemberAccessExpression,
                    expression,
                    SyntaxFactory.IdentifierName(nameof(Task.ConfigureAwait))),
                SyntaxFactory.ArgumentList(
                    SyntaxFactory.SingletonSeparatedList(
                        SyntaxFactory.Argument(
                            SyntaxFactory.LiteralExpression(continueOnCapturedContextSyntax)))));

            var newRoot = root.ReplaceNode(expression, newExpression);
            var newDocument = document.WithSyntaxRoot(newRoot);
            return newDocument;
        }
开发者ID:Rocketmakers,项目名称:hubble,代码行数:31,代码来源:ConfigureAwaitCodeFixProvider.cs

示例9: EnforceAsync

        public async Task<Solution> EnforceAsync(Document document)
        {
            if (document == null) { throw new ArgumentNullException(nameof(document)); }

            // The compiler will actually do the heavy lifting for us on this one: when it generates the semantic model
            // it creates diagnostic notes for usings that are unused with the id "CS8019".
            SemanticModel semanticModel = await document.GetSemanticModelAsync();
            IEnumerable<Diagnostic> diagnostics = semanticModel.GetDiagnostics().Where(d => d.Id == "CS8019");

            // Save the leading trivia to reattach after we have removed the unused roots
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync();
            SyntaxTriviaList leadingTrivia = oldRoot.GetLeadingTrivia();

            // Now we need to go through the diagnostics in reverse order (so we don't corrupt our spans), find the
            // relevant SyntaxNodes, and remove them.
            diagnostics = diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start);
            SyntaxNode newRoot = oldRoot;

            foreach (Diagnostic diagnostic in diagnostics)
            {
                newRoot = newRoot.RemoveNodes(
                    newRoot.DescendantNodes(diagnostic.Location.SourceSpan),
                    SyntaxRemoveOptions.KeepNoTrivia);
            }

            if (newRoot != oldRoot)
            {
                Log.WriteInformation("{0}: Removing unused usings", document.Name);
                document = document.WithSyntaxRoot(newRoot.WithLeadingTrivia(leadingTrivia));
            }

            return document.Project.Solution;
        }
开发者ID:nicholjy,项目名称:stylize,代码行数:33,代码来源:UnusedUsingsStyleRule.cs

示例10: 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);
 }
开发者ID:nemec,项目名称:VSDiagnostics,代码行数:7,代码来源:TestMethodWithoutPublicModifierCodeFix.cs

示例11: GetTransformedDocumentAsync

        private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            SyntaxToken token = root.FindToken(diagnostic.Location.SourceSpan.Start);
            var replacements = new List<SyntaxToken>(2);

            if (!token.IsFirstInLine())
            {
                SyntaxToken precedingToken = token.GetPreviousToken();
                if (precedingToken.TrailingTrivia.Any(SyntaxKind.WhitespaceTrivia))
                {
                    replacements.Add(precedingToken);
                }
            }

            SyntaxTriviaList trailingTrivia = token.TrailingTrivia;
            if (!trailingTrivia.Any(SyntaxKind.EndOfLineTrivia) && trailingTrivia.Any(SyntaxKind.WhitespaceTrivia))
            {
                replacements.Add(token);
            }

            if (replacements.Count == 0)
            {
                return document;
            }

            var transformed = root.ReplaceTokens(replacements, (original, maybeRewritten) => maybeRewritten.WithoutTrailingWhitespace().WithoutFormatting());
            Document updatedDocument = document.WithSyntaxRoot(transformed);

            return updatedDocument;
        }
开发者ID:hickford,项目名称:StyleCopAnalyzers,代码行数:31,代码来源:SA1010CodeFixProvider.cs

示例12: MakeLambdaExpressionAsync

        private async Task<Document> MakeLambdaExpressionAsync(Document document, AnonymousMethodExpressionSyntax anonMethod, CancellationToken cancellationToken)
        {
            
            var parent = anonMethod.Parent;

            var parameterList = anonMethod.ParameterList != null ? anonMethod.ParameterList : SyntaxFactory.ParameterList();

            SyntaxNode body;

            if (anonMethod.Block != null && anonMethod.Block.Statements.Count == 1)
            {
                body = anonMethod.Block.Statements.ElementAt(0).ChildNodes().ElementAt(0);
            }
            else if (anonMethod.Block != null)
            {
                body = anonMethod.Body;
            }
            else
            {
                body = SyntaxFactory.Block();
            }

            var lambdaExpr = SyntaxFactory.
                ParenthesizedLambdaExpression(parameterList, (CSharpSyntaxNode)body);

            var newParent = parent.ReplaceNode(anonMethod, lambdaExpr);

            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var newRoot = root.ReplaceNode(parent, newParent);

            return document.WithSyntaxRoot(newRoot);

        }
开发者ID:Adyrhan,项目名称:delegate-lambda-replacer,代码行数:34,代码来源:CodeFixProvider.cs

示例13: ReplaceNodeAsync

 public static async Task<Document> ReplaceNodeAsync(Document document, SyntaxNode @old, SyntaxNode @new, CancellationToken cancellationToken)
 {
     var root = await document.GetSyntaxRootAsync(cancellationToken);
     var newRoot = root.ReplaceNode(@old, @new);
     var newDocument = document.WithSyntaxRoot(newRoot);
     return newDocument;
 }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:7,代码来源:ConvertToExpressionBodiedMemberCodeFixProvider.cs

示例14: GetTransformedDocumentAsync

        private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var indentationOptions = IndentationOptions.FromDocument(document);
            var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var violatingTrivia = syntaxRoot.FindTrivia(diagnostic.Location.SourceSpan.Start);

            var stringBuilder = new StringBuilder();

            var column = violatingTrivia.GetLineSpan().StartLinePosition.Character;
            foreach (var c in violatingTrivia.ToFullString())
            {
                if (c == '\t')
                {
                    var offsetWithinTabColumn = column % indentationOptions.TabSize;
                    var spaceCount = indentationOptions.TabSize - offsetWithinTabColumn;

                    stringBuilder.Append(' ', spaceCount);
                    column += spaceCount;
                }
                else
                {
                    stringBuilder.Append(c);
                    column++;
                }
            }

            var newSyntaxRoot = syntaxRoot.ReplaceTrivia(violatingTrivia, SyntaxFactory.Whitespace(stringBuilder.ToString()));
            return document.WithSyntaxRoot(newSyntaxRoot);
        }
开发者ID:hickford,项目名称:StyleCopAnalyzers,代码行数:30,代码来源:SA1027CodeFixProvider.cs

示例15: RemoveUnreachableCodeAsync

 private static async Task<Document> RemoveUnreachableCodeAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
 {
     var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
     var node = root.FindNode(diagnostic.Location.SourceSpan);
     var newDoc = document.WithSyntaxRoot(RemoveUnreachableStatement(root, node));
     return newDoc;
 }
开发者ID:JeanLLopes,项目名称:code-cracker,代码行数:7,代码来源:RemoveUnreachableCodeCodeFixProvider.cs


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