當前位置: 首頁>>代碼示例>>C#>>正文


C# CodeAnalysis.SyntaxTree類代碼示例

本文整理匯總了C#中Microsoft.CodeAnalysis.SyntaxTree的典型用法代碼示例。如果您正苦於以下問題:C# SyntaxTree類的具體用法?C# SyntaxTree怎麽用?C# SyntaxTree使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


SyntaxTree類屬於Microsoft.CodeAnalysis命名空間,在下文中一共展示了SyntaxTree類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: OneSide

        private static void OneSide(Repo repo, SyntaxTree local, SyntaxTree remote, SyntaxTree ancestor, string path)
        {
            //Fake a call te to GetRemoteChange() by placeing the remote and ancestor trees into the RemoteChangesData list
            repo.PullRequests.Clear();
            repo.PullRequests.Add(new PullRequest
            {
                Updated = DateTime.Now,
                Files = new[] { new Core.RepoFile {
                    BaseTree = ancestor,
                    HeadTree = remote,
                    Filename = path,
                    Status = RepoFile.StatusEnum.Modified,
                } },
                Title = "Fake Pull Request",
                Url = "http://github.com/example/repo",
                Number = 1,
                State = "open",
                LastWrite = DateTime.MinValue,
                Base = new PullRequest.HeadBase { Sha = "" },
                Head = new PullRequest.HeadBase { Sha = "" },
            });
            var pr = repo.PullRequests.First();
            pr.ParentRepo = repo;
            pr.ValidFiles.First().ParentPullRequst = pr;

            var res = Analysis.ForFalsePositive(repo, local);
            Assert.IsTrue(res.Any());
        }
開發者ID:semdiffdotnet,項目名稱:semdiff,代碼行數:28,代碼來源:FalsePositiveAnalysisTests.cs

示例2: GetAssembly

        /// <summary>
        /// Get assembly from the given text.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>Assembly</returns>
        protected Assembly GetAssembly(SyntaxTree tree)
        {
            Assembly assembly = null;
            
            var references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Machine).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(PSharpBugFindingRuntime).Assembly.Location)
            };

            var compilation = CSharpCompilation.Create(
                "PSharpTestAssembly", new[] { tree }, references,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);
                if (result.Success)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    assembly = Assembly.Load(ms.ToArray());
                }
            }

            return assembly;
        }
開發者ID:huangpf,項目名稱:PSharp,代碼行數:33,代碼來源:BasePSharpTest.cs

示例3: GetCompilation

        public CSharpCompilation GetCompilation(string assemblyName, IDictionary<string, string> files, out SyntaxTree[] trees)
        {
            var options = new CSharpParseOptions(_languageVersion);
            trees = files.Select(x =>
            {
                var text = x.Value;
                var tree = CSharpSyntaxTree.ParseText(text, options: options);
                if (tree.GetDiagnostics().Any())
                    throw new Exception(string.Format("Syntax error in file \"{0}\".", x.Key));
                return tree;
            }).ToArray();

            // adding everything is going to cause issues with dynamic assemblies
            // so we would want to filter them anyway... but we don't need them really
            //var refs = AssemblyUtility.GetAllReferencedAssemblyLocations().Select(x => new MetadataFileReference(x));
            // though that one is not ok either since we want our own reference
            //var refs = Enumerable.Empty<MetadataReference>();
            // so use the bare minimum
            var asms = ReferencedAssemblies;
            var a1 = typeof(Builder).Assembly;
            asms.Add(a1);
            foreach (var a in GetDeepReferencedAssemblies(a1)) asms.Add(a);
            var refs = asms.Select(x => MetadataReference.CreateFromFile(x.Location));

            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var compilation = CSharpCompilation.Create(
                assemblyName,
                /*syntaxTrees:*/ trees,
                /*references:*/ refs,
                compilationOptions);

            return compilation;
        }
開發者ID:nul800sebastiaan,項目名稱:Zbu.ModelsBuilder,代碼行數:33,代碼來源:Compiler.cs

示例4: 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

示例5: GetConflicts

        private static IEnumerable<Conflict> GetConflicts(IEnumerable<Diff> local, IEnumerable<Diff> remote,
            SyntaxTree ancestorTree, SyntaxTree localTree, SyntaxTree remoteTree)
        {
            var localChanges = local.Select(DiffWithOrigin.Local);
            var remoteChanges = remote.Select(DiffWithOrigin.Remote);

            var changes = Extensions.GetMergedQueue(localChanges, remoteChanges,
                                                            d => d.Diff.Ancestor.Span.Start);
            var potentialConflict = new List<DiffWithOrigin>();
            while (changes.Count > 0)
            {
                potentialConflict.Clear();
                do
                {
                    var change = changes.Dequeue();
                    potentialConflict.Add(change);
                }
                while (changes.Count > 0
                      && Diff.IntersectsAny(changes.Peek().Diff,
                                                   potentialConflict.Select(dwo => dwo.Diff)));

                if (potentialConflict.Count >= 2)
                    yield return Conflict.Create(potentialConflict, ancestorTree, localTree, remoteTree);
            }
            yield break;
        }
開發者ID:semdiffdotnet,項目名稱:semdiff,代碼行數:26,代碼來源:Diff3.cs

示例6: Run

 public IEnumerable<Match> Run(SyntaxTree tree)
 {
     return tree.GetRoot()
                .DescendantNodesAndTokensAndSelf()
                .Select(CreateMatch)
                .Where(n => n.IsMatch);
 }
開發者ID:terrajobst,項目名稱:apiporter,代碼行數:7,代碼來源:Matcher.Run.cs

示例7: Compile

        /// <summary>
        /// Creates a fresh new compilation of source files.
        /// Does not load any assembly.
        /// </summary>
        /// <returns>Success if no compilation erros were encountered.</returns>
        public bool Compile()
        {
            if (SourceFiles.Count == 0 && SourceTexts.Count == 0) return false;

            SyntaxTree [] syntaxTrees = new SyntaxTree[SourceFiles.Count + SourceTexts.Count];
            int currentIndex = 0;

            try
            {
                foreach (string sourceFile in SourceFiles)
                {
                    using (StreamReader reader = new StreamReader(MyFileSystem.OpenRead(sourceFile)))
                    {
                        var text = reader.ReadToEnd();
                        syntaxTrees[currentIndex] = CSharpSyntaxTree.ParseText(text);
                        currentIndex++;
                    }
                }

                foreach (var sourceText in SourceTexts)
                    syntaxTrees[currentIndex++] = CSharpSyntaxTree.ParseText(sourceText);

                m_compilation = CSharpCompilation.Create(AssemblyName, syntaxTrees, 
                    DependencyCollector.References, m_defaultCompilationOptions);

            }
            catch (Exception e)
            {
                Debug.Fail(e.ToString());
                return false;
            }

            return true;
        }
開發者ID:2asoft,項目名稱:SpaceEngineers,代碼行數:39,代碼來源:MyVSCompiler.cs

示例8: 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

示例9: 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

示例10: CodeProvider

		internal CodeProvider(SyntaxTree tree, Compilation compilation)
		{
			this.SyntaxTree = tree;	//project.GetCompilationAsync().Result;
			this.Compilation = compilation;

			this.SemanticModel = this.Compilation.GetSemanticModel(tree);
		}
開發者ID:TubaKayaDev,項目名稱:Call-Graph-Builder-DotNet,代碼行數:7,代碼來源:CodeProvider.cs

示例11: 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

示例12: DumpSyntaxTree

 public static void DumpSyntaxTree(SyntaxTree syntaxTree, string declarationFilter, string description)
 {
     if (syntaxTree != null)
     {
         PanelManager.DisplayControl(new SyntaxTreePanel(syntaxTree, declarationFilter), description ?? "Syntax Tree");
     }
 }
開發者ID:modulexcite,項目名稱:LINQPad.CodeAnalysis,代碼行數:7,代碼來源:CodeAnalysisUtil.cs

示例13: GetIndenter

 protected override AbstractIndenter GetIndenter(
     ISyntaxFactsService syntaxFacts, SyntaxTree syntaxTree, TextLine lineToBeIndented, IEnumerable<IFormattingRule> formattingRules, OptionSet optionSet, CancellationToken cancellationToken)
 {
     return new Indenter(
         syntaxFacts, syntaxTree, formattingRules,
         optionSet, lineToBeIndented, cancellationToken);
 }
開發者ID:manojdjoshi,項目名稱:dnSpy,代碼行數:7,代碼來源:CSharpIndentationService.cs

示例14: GetSemanticModel

        public static SemanticModel GetSemanticModel(SyntaxTree tree, string extDll)
        {
            var Mscorlib = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
            var current = PortableExecutableReference.CreateFromFile(Assembly.GetExecutingAssembly().Location);
            var current2 = PortableExecutableReference.CreateFromFile(typeof(Hide).Assembly.Location);
            var current3 = PortableExecutableReference.CreateFromFile(extDll);
            var current4 = PortableExecutableReference.CreateFromFile(@"D:\ghostnguyen\daccf960-44f9-4f95-91c4-b1aba37effe1\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll");
            var current5 = PortableExecutableReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Web.dll");
            var current6 = PortableExecutableReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Xml.Linq.dll");
            var current7 = PortableExecutableReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Xml.dll");
            var current8 = PortableExecutableReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Core.dll");
            var current9 = PortableExecutableReference.CreateFromFile(@"D:\ghostnguyen\daccf960-44f9-4f95-91c4-b1aba37effe1\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll");

            var compilation = CSharpCompilation.Create("MyCompilation",
                syntaxTrees: new[] { tree }, references: new[] { Mscorlib,
                    current,
                    current2,
                    current3,
                    current4,
                    current5,
                    current6,
                    current7,
                    current8,
                    current9
                });

            var model = compilation.GetSemanticModel(tree);
            var dia1 = model.GetDiagnostics();
            var dia2 = compilation.GetDiagnostics();

            return model;
        }
開發者ID:ghostnguyen,項目名稱:daccf960-44f9-4f95-91c4-b1aba37effe1,代碼行數:32,代碼來源:Program.cs

示例15: 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


注:本文中的Microsoft.CodeAnalysis.SyntaxTree類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。