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


C# SyntaxTree.GetRoot方法代码示例

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


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

示例1: Rewrite

        /// <summary>
        /// Rewrites the syntax tree with create machine expressions.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>SyntaxTree</returns>
        internal SyntaxTree Rewrite(SyntaxTree tree)
        {
            var statements = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().
                Where(val => val.Expression is IdentifierNameSyntax).
                Where(val => (val.Expression as IdentifierNameSyntax).Identifier.ValueText.Equals("create")).
                ToList();

            if (statements.Count == 0)
            {
                return tree;
            }

            var root = tree.GetRoot().ReplaceNodes(
                nodes: statements,
                computeReplacementNode: (node, rewritten) => this.RewriteStatement(rewritten));

            var models = root.DescendantNodes().
                Where(val => val is LocalDeclarationStatementSyntax).
                Where(val => this.ToReplace.Any(n => n.IsEquivalentTo(val)));

            root = root.ReplaceNodes(
                nodes: models,
                computeReplacementNode: (node, rewritten) => SyntaxFactory.ParseStatement(";"));

            root = root.RemoveNodes(this.ToRemove, SyntaxRemoveOptions.KeepNoTrivia);

            return base.UpdateSyntaxTree(tree, root.ToString());
        }
开发者ID:ashwini-mnnit,项目名称:PSharp,代码行数:33,代码来源:CreateMachineRewriter.cs

示例2: TestSetup

        public void TestSetup()
        {
            syntaxTree = CSharpSyntaxTree.ParseText(Source);

            ifMethod = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "IfMethod");
            switchMethod = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "SwitchMethod");
        }
开发者ID:shrknt35,项目名称:sonarlint-vs,代码行数:7,代码来源:NavigationHelperTest.cs

示例3: Rewrite

        /// <summary>
        /// Rewrites the syntax tree with raise statements.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>SyntaxTree</returns>
        internal SyntaxTree Rewrite(SyntaxTree tree)
        {
            var stmts1 = tree.GetRoot().DescendantNodes().OfType<ExpressionStatementSyntax>().
                Where(val => val.Expression is InvocationExpressionSyntax).
                Where(val => (val.Expression as InvocationExpressionSyntax).Expression is IdentifierNameSyntax).
                Where(val => ((val.Expression as InvocationExpressionSyntax).Expression as IdentifierNameSyntax).
                    Identifier.ValueText.Equals("Raise")).
                ToList();

            var stmts2 = tree.GetRoot().DescendantNodes().OfType<ExpressionStatementSyntax>().
                Where(val => val.Expression is InvocationExpressionSyntax).
                Where(val => (val.Expression as InvocationExpressionSyntax).Expression is MemberAccessExpressionSyntax).
                Where(val => ((val.Expression as InvocationExpressionSyntax).Expression as MemberAccessExpressionSyntax).
                    Name.Identifier.ValueText.Equals("Raise")).
                ToList();

            var statements = stmts1;
            statements.AddRange(stmts2);

            if (statements.Count == 0)
            {
                return tree;
            }

            var root = tree.GetRoot().ReplaceNodes(
                nodes: statements,
                computeReplacementNode: (node, rewritten) => this.RewriteStatement(rewritten));

            return base.UpdateSyntaxTree(tree, root.ToString());
        }
开发者ID:jerickmsft,项目名称:PSharp,代码行数:35,代码来源:RaiseRewriter.cs

示例4: Rewrite

        /// <summary>
        /// Rewrites the syntax tree with raise statements.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>SyntaxTree</returns>
        internal SyntaxTree Rewrite(SyntaxTree tree)
        {
            var statements = tree.GetRoot().DescendantNodes().OfType<ExpressionStatementSyntax>().
                Where(val => val.Expression is InvocationExpressionSyntax).
                Where(val => (val.Expression as InvocationExpressionSyntax).Expression is IdentifierNameSyntax).
                Where(val => ((val.Expression as InvocationExpressionSyntax).Expression as IdentifierNameSyntax).
                    Identifier.ValueText.Equals("raise")).
                ToList();

            if (statements.Count == 0)
            {
                return tree;
            }

            var root = tree.GetRoot().ReplaceNodes(
                nodes: statements,
                computeReplacementNode: (node, rewritten) => this.RewriteStatement(rewritten));

            var raiseStmts = root.DescendantNodes().OfType<ExpressionStatementSyntax>().
                Where(val => this.RaiseStmts.Any(v => SyntaxFactory.AreEquivalent(v, val))).ToList();

            foreach (var stmt in raiseStmts)
            {
                root = root.InsertNodesAfter(stmt, new List<SyntaxNode> { this.CreateReturnStatement() });
            }

            return base.UpdateSyntaxTree(tree, root.ToString());
        }
开发者ID:jerickmsft,项目名称:PSharp,代码行数:33,代码来源:RaiseRewriter.cs

示例5: ReportAllErrors

 protected override IEnumerable<string> ReportAllErrors(SyntaxTree userSolution)
 {
     var recursiveMethods = userSolution.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Where(IsRecursive).ToList();
     if (requireRecursion && !recursiveMethods.Any())
         yield return Report(userSolution.GetRoot(), "Решение должно быть рекурсивным");
     if (!requireRecursion && recursiveMethods.Any())
         yield return Report(userSolution.GetRoot(), "Решение должно быть нерекурсивным");
 }
开发者ID:kontur-edu,项目名称:uLearn,代码行数:8,代码来源:RecursionStyleValidator.cs

示例6: BuildBlockFrom

		public ExerciseBlock BuildBlockFrom(SyntaxTree tree)
		{
			ExerciseClassName = null;
			Exercise.ExerciseInitialCode = GetUncomment(tree.GetRoot()) ?? ""; //for uncomment-comment without exercise method
			SyntaxNode result = Visit(tree.GetRoot());
			var exerciseInsertIndex = GetExerciseInsertIndex(result);
			const string pragma = "\n#line 1\n";
			Exercise.ExerciseCode = prelude + result.ToFullString().Insert(exerciseInsertIndex, pragma);
			Exercise.IndexToInsertSolution = prelude.Length + exerciseInsertIndex + pragma.Length;
			return Exercise;
		}
开发者ID:kontur-edu,项目名称:uLearn,代码行数:11,代码来源:ExerciseBuilder.cs

示例7: Run

 public IEnumerable<Match> Run(SyntaxTree tree)
 {
     return tree.GetRoot()
                .DescendantNodesAndTokensAndSelf()
                .Select(CreateMatch)
                .Where(n => n.IsMatch);
 }
开发者ID:terrajobst,项目名称:apiporter,代码行数:7,代码来源:Matcher.Run.cs

示例8: FromIndentBlockOperations

        public int? FromIndentBlockOperations(
            SyntaxTree tree, SyntaxToken token, int position, CancellationToken cancellationToken)
        {
            // we use operation service to see whether it is a starting point of new indentation.
            // ex)
            //  if (true)
            //  {
            //     | <= this is new starting point of new indentation
            var operation = GetIndentationDataFor(tree.GetRoot(cancellationToken), token, position);

            // try find indentation based on indentation operation
            if (operation != null)
            {
                // make sure we found new starting point of new indentation.
                // such operation should start span after the token (a token that is right before the new indentation),
                // contains current position, and position should be before the existing next token
                if (token.Span.End <= operation.TextSpan.Start &&
                    operation.TextSpan.IntersectsWith(position) &&
                    position <= token.GetNextToken(includeZeroWidth: true).SpanStart)
                {
                    return GetIndentationOfCurrentPosition(tree, token, position, cancellationToken);
                }
            }

            return null;
        }
开发者ID:GloryChou,项目名称:roslyn,代码行数:26,代码来源:BottomUpBaseIndentationFinder.cs

示例9: GetAttributeListsNodes

 public IEnumerable<AttributeListSyntax> GetAttributeListsNodes(SyntaxTree syntaxTree)
 {
     if (syntaxTree == null) throw new ArgumentNullException(nameof(syntaxTree));
     return syntaxTree.GetRoot()
        .DescendantNodes()
        .OfType<AttributeListSyntax>();
 }
开发者ID:t-denis,项目名称:DarkAttributes,代码行数:7,代码来源:SyntaxTreeProcessor.cs

示例10: Rewrite

        /// <summary>
        /// Rewrites the syntax tree with field access expressions.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>SyntaxTree</returns>
        internal SyntaxTree Rewrite(SyntaxTree tree)
        {
            var expressions = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().
                ToList();

            if (expressions.Count == 0)
            {
                return tree;
            }

            var root = tree.GetRoot().ReplaceNodes(
                nodes: expressions,
                computeReplacementNode: (node, rewritten) => this.RewriteExpression(rewritten));

            return base.UpdateSyntaxTree(tree, root.ToString());
        }
开发者ID:jerickmsft,项目名称:PSharp,代码行数:21,代码来源:FieldAccessRewriter.cs

示例11: IsEntirelyWithinStringLiteral

        public static bool IsEntirelyWithinStringLiteral(
            SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true);

            // If we ask right at the end of the file, we'll get back nothing. We handle that case
            // specially for now, though SyntaxTree.FindToken should work at the end of a file.
            if (IsKind(token, SyntaxKind.EndOfDirectiveToken, SyntaxKind.EndOfFileToken))
            {
                token = token.GetPreviousToken(includeSkipped: true, includeDirectives: true);
            }

            if (token.IsKind(SyntaxKind.StringLiteralToken))
            {
                var span = token.Span;

                // cases:
                // "|"
                // "|  (e.g. incomplete string literal)
                return (position > span.Start && position < span.End)
                       || AtEndOfIncompleteStringOrCharLiteral(token, position, '"');
            }

            if (IsKind(token, SyntaxKind.InterpolatedStringStartToken, SyntaxKind.InterpolatedStringTextToken,
                SyntaxKind.InterpolatedStringEndToken))
            {
                return token.SpanStart < position && token.Span.End > position;
            }

            return false;
        }
开发者ID:mjheitland,项目名称:TableTweaker,代码行数:31,代码来源:ReferenceDirectiveCompletionProvider.cs

示例12: PrintMethodContentViaSemanticModel

		private static void PrintMethodContentViaSemanticModel(SyntaxTree tree)
		{
			Console.Out.WriteLine(nameof(Program.PrintMethodContentViaSemanticModel));
			var compilation = CSharpCompilation.Create(
				"MethodContent",
				syntaxTrees: new[] { tree },
				references: new[]
				{
					MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
				});

			var model = compilation.GetSemanticModel(tree, true);

			var methods = tree.GetRoot().DescendantNodes(_ => true)
				.OfType<MethodDeclarationSyntax>();

			foreach (var method in methods)
			{
				var methodInfo = model.GetDeclaredSymbol(method) as IMethodSymbol;
				var parameters = new List<string>();

				foreach (var parameter in methodInfo.Parameters)
				{
					var isRef = parameter.RefKind == RefKind.Ref ? "ref " : string.Empty;
					parameters.Add($"{isRef}{parameter.Type.Name} {parameter.Name}");
				}

				Console.Out.WriteLine(
					$"{methodInfo.Name}({string.Join(", ", parameters)})");
			}
		}
开发者ID:JasonBock,项目名称:CompilerAPIBook,代码行数:31,代码来源:Program.cs

示例13: AbstractIndenter

            public AbstractIndenter(
                ISyntaxFactsService syntaxFacts,
                SyntaxTree syntaxTree,
                IEnumerable<IFormattingRule> rules,
                OptionSet optionSet,
                TextLine lineToBeIndented,
                CancellationToken cancellationToken)
            {
                var syntaxRoot = syntaxTree.GetRoot(cancellationToken);

                this._syntaxFacts = syntaxFacts;
                this.OptionSet = optionSet;
                this.Tree = syntaxTree;
                this.LineToBeIndented = lineToBeIndented;
                this.TabSize = this.OptionSet.GetOption(FormattingOptions.TabSize, syntaxRoot.Language);
                this.CancellationToken = cancellationToken;

                this.Rules = rules;
                this.Finder = new BottomUpBaseIndentationFinder(
                         new ChainedFormattingRules(this.Rules, OptionSet),
                         this.TabSize,
                         this.OptionSet.GetOption(FormattingOptions.IndentationSize, syntaxRoot.Language),
                         tokenStream: null,
                         lastToken: default(SyntaxToken));
            }
开发者ID:manojdjoshi,项目名称:dnSpy,代码行数:25,代码来源:AbstractIndentationService.AbstractIndenter.cs

示例14: GetProperties

 public static IEnumerable<PropertyDeclarationSyntax> GetProperties(SyntaxTree syntaxTree)
 {
     var result = syntaxTree.GetRoot().DescendantNodes()
         .Where(node => node.IsKind(SyntaxKind.PropertyDeclaration))
         .Cast<PropertyDeclarationSyntax>();
     return result;
 }
开发者ID:Felorati,项目名称:AutoGetHashCode,代码行数:7,代码来源:SyntaxAnalyzer.cs

示例15: GetNamespace

 public static string GetNamespace(SyntaxTree syntaxTree)
 {
     return syntaxTree.GetRoot().DescendantNodes()
         .Where(node => node.IsKind(SyntaxKind.NamespaceDeclaration))
         .Cast<NamespaceDeclarationSyntax>()
         .First()
         .Name.ToString();
 }
开发者ID:Felorati,项目名称:AutoGetHashCode,代码行数:8,代码来源:SyntaxAnalyzer.cs


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