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


C# CSharpCompilation.GetSemanticModel方法代码示例

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


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

示例1: Rewriter

        public Rewriter(CSharpCompilation compilation, AnalyzerResult result)
        {
            tree = (CSharpSyntaxTree) compilation.SyntaxTrees.Single();
            model = compilation.GetSemanticModel(tree);

            this.compilation = compilation;
            this.result = result;
        }
开发者ID:jthelin,项目名称:Nake,代码行数:8,代码来源:Rewriter.cs

示例2: Parse

        private static void Parse(ParseResult disco, CSharpCompilation compilation, SyntaxTree tree)
        {
            var model = compilation.GetSemanticModel(tree);

            //we quite probably have errors but that is normal
            //var diags = model.GetDiagnostics();

            var classDecls = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>();
            foreach (var classSymbol in classDecls.Select(x => model.GetDeclaredSymbol(x)))
            {
                ParseClassSymbols(disco, classSymbol);

                var baseClassSymbol = classSymbol.BaseType;
                if (baseClassSymbol != null)
                    //disco.SetContentBaseClass(SymbolDisplay.ToDisplayString(classSymbol), SymbolDisplay.ToDisplayString(baseClassSymbol));
                    disco.SetContentBaseClass(classSymbol.Name, baseClassSymbol.Name);

                var interfaceSymbols = classSymbol.Interfaces;
                disco.SetContentInterfaces(classSymbol.Name, //SymbolDisplay.ToDisplayString(classSymbol),
                    interfaceSymbols.Select(x => x.Name)); //SymbolDisplay.ToDisplayString(x)));

                var hasCtor = classSymbol.Constructors
                    .Any(x =>
                    {
                        if (x.IsStatic) return false;
                        if (x.Parameters.Length != 1) return false;
                        var type1 = x.Parameters[0].Type;
                        var type2 = typeof (global::Umbraco.Core.Models.IPublishedContent);
                        return type1.ToDisplayString() == type2.FullName;
                    });

                if (hasCtor)
                    disco.SetHasCtor(classSymbol.Name);

                foreach (var propertySymbol in classSymbol.GetMembers().Where(x => x is IPropertySymbol))
                    ParsePropertySymbols(disco, classSymbol, propertySymbol);

                foreach (var staticMethodSymbol in classSymbol.GetMembers().Where(x => x is IMethodSymbol))
                    ParseMethodSymbol(disco, classSymbol, staticMethodSymbol);
            }

            var interfaceDecls = tree.GetRoot().DescendantNodes().OfType<InterfaceDeclarationSyntax>();
            foreach (var interfaceSymbol in interfaceDecls.Select(x => model.GetDeclaredSymbol(x)))
            {
                ParseClassSymbols(disco, interfaceSymbol);

                var interfaceSymbols = interfaceSymbol.Interfaces;
                disco.SetContentInterfaces(interfaceSymbol.Name, //SymbolDisplay.ToDisplayString(interfaceSymbol),
                    interfaceSymbols.Select(x => x.Name)); // SymbolDisplay.ToDisplayString(x)));
            }

            ParseAssemblySymbols(disco, compilation.Assembly);
        }
开发者ID:nul800sebastiaan,项目名称:Zbu.ModelsBuilder,代码行数:53,代码来源:CodeParser.cs

示例3: GetMembers

        private static IEnumerable<AnnotationMember> GetMembers(CSharpCompilation compilation)
        {
            foreach (var syntaxTree in compilation.SyntaxTrees)
            {
                var semanticModel = compilation.GetSemanticModel(syntaxTree, true);

                var nodes = syntaxTree.GetRoot().DescendantNodes();

                foreach (var member in GetMembers(semanticModel, nodes))
                {
                    yield return member;
                }
            }
        }
开发者ID:khellang,项目名称:JetBrains.Annotations.Dnx,代码行数:14,代码来源:AnnotationsCompileModule.cs

示例4: GetInfo

        internal static JToken GetInfo(CSharpCompilation compilation, string file, string symbolLoc)
        {
            var syntaxTree = compilation.SyntaxTrees.SingleOrDefault(s => s.FilePath == file);
            if (syntaxTree == null)
                return null;

            var parts = symbolLoc.Split(',');
            int start = int.Parse(parts[0]),
                end = int.Parse(parts[1]);

            var root = syntaxTree.GetRoot();
            var maybeToken = FindToken(root, start, end);
            if (!maybeToken.HasValue)
                return null;

            var token = maybeToken.Value;
            return GetTokenInfo(compilation.GetSemanticModel(syntaxTree), token);
        }
开发者ID:Runt-Editor,项目名称:Runt,代码行数:18,代码来源:TokenInfo.cs

示例5: GetReplacements

        public static ImmutableArray<TreeReplacement> GetReplacements(CSharpCompilation compilation, IEnumerable<SyntaxTree> trees)
        {
            //TODO remove trees argument (need add included files to trees dictionary in generator and rewrite code in them as well)
            return trees
                .Where(tree => {
                    return tree.GetText().Lines.First().ToString() == "#define META_REWRITE"; //TODO correct META_REWRITE check including meta project-level constants

                })
                .Select(tree => {
                    var root = tree.GetRoot();
                    var rewriter = new MetaRewriter(compilation.GetSemanticModel(tree));
                    var newRoot = rewriter.Visit(root);
                    var newTree = tree.WithRootAndOptions(newRoot, tree.Options);
                    return new TreeReplacement(tree, newTree);
                })
                .ToImmutableArray();
        }
开发者ID:VitalyTVA,项目名称:MetaSharp,代码行数:17,代码来源:Rewriter.cs

示例6: GetSourceAliasSymbols

 private static void GetSourceAliasSymbols(CSharpCompilation comp, List<ISymbol> list)
 {
     foreach (var tree in comp.SyntaxTrees)
     {
         var usingNodes = tree.GetRoot().DescendantNodes().OfType<UsingDirectiveSyntax>();
         var model = comp.GetSemanticModel(tree);
         foreach (var u in usingNodes)
         {
             if (u.Alias != null)
             {
                 // var sym = model.GetSymbolInfo(u.Alias.Identifier).Symbol;
                 var sym = model.GetDeclaredSymbol(u);
                 if (sym != null && !list.Contains(sym))
                 {
                     list.Add(sym);
                 }
             }
         }
     }
 }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:20,代码来源:SymbolKeyTestBase.cs

示例7: GenerateControllers

        public IEnumerable<NamespaceDeclarationSyntax> GenerateControllers(
			CSharpCompilation compiler,
			IEnumerable<ClassDeclarationSyntax> controllerNodes)
        {
            // controllers might be in different namespaces so should group by namespace
            var namespaceGroups =
                controllerNodes.GroupBy(x => x.Ancestors().OfType<NamespaceDeclarationSyntax>().First().Name.ToFullString());
            foreach (var namespaceControllers in namespaceGroups)
            {
                // create the namespace for the controllers
                var namespaceNode = SyntaxNodeHelpers.CreateNamespace(namespaceControllers.Key);

                // loop through the controllers and create a partial node for each
                foreach (var mvcControllerNode in namespaceControllers)
                {
                    var model = compiler.GetSemanticModel(mvcControllerNode.SyntaxTree);
                    var mvcSymbol = model.GetDeclaredSymbol(mvcControllerNode);

                    // build controller partial class node
                    // add a default constructor if there are some but none are zero length
                    var genControllerClass = SyntaxNodeHelpers.CreateClass(
                        mvcSymbol.Name,
                        mvcControllerNode.TypeParameterList?.Parameters.ToArray(),
                        SyntaxKind.PublicKeyword,
                        SyntaxKind.PartialKeyword);

                    if (!mvcSymbol.Constructors.IsEmpty || !mvcSymbol.Constructors.Any(x => x.Parameters.Length == 0))
                    {
                        genControllerClass = genControllerClass.WithDefaultConstructor(true, SyntaxKind.PublicKeyword);
                    }

                    // add all method stubs, TODO criteria for this: only public virtual actionresults?
                    // add subclasses, fields, properties, constants for action names
                    genControllerClass =
                        genControllerClass.WithMethods(mvcSymbol)
                            .WithStringField(
                                "Name",
                                mvcControllerNode.Identifier.ToString(),
                                true,
                                SyntaxKind.PublicKeyword,
                                SyntaxKind.ReadOnlyKeyword)
                            .WithStringField(
                                "NameConst",
                                mvcControllerNode.Identifier.ToString(),
                                true,
                                SyntaxKind.PublicKeyword,
                                SyntaxKind.ConstKeyword)
                            .WithStringField(
                                "Area",
                                mvcControllerNode.Identifier.ToString(),
                                true,
                                SyntaxKind.PublicKeyword,
                                SyntaxKind.ReadOnlyKeyword)
                            .WithField("s_actions", "ActionNamesClass", SyntaxKind.StaticKeyword, SyntaxKind.ReadOnlyKeyword)
                            .WithActionNameClass(mvcControllerNode)
                            .WithActionConstantsClass(mvcControllerNode)
                            .WithField("s_views", "ViewsClass", SyntaxKind.StaticKeyword, SyntaxKind.ReadOnlyKeyword)
                            .WithViewsClass(_viewLocator.FindViews());

                    // create R4MVC_[Controller] class inheriting from partial
                    // TODO chain base constructor call : base(Dummy.Instance)
                    // TODO create [method]overrides(T4MVC_System_Web_Mvc_ActionResult callInfo)
                    // TODO create method overrides that call above
                    var r4ControllerClass =
                        SyntaxNodeHelpers.CreateClass(
                            GetR4MVCControllerClassName(genControllerClass),
                            null,
                            SyntaxKind.PublicKeyword,
                            SyntaxKind.PartialKeyword)
                            .WithAttributes(SyntaxNodeHelpers.CreateGeneratedCodeAttribute(), SyntaxNodeHelpers.CreateDebugNonUserCodeAttribute())
                            .WithBaseTypes(mvcControllerNode.ToQualifiedName())
                            .WithDefaultConstructor(false, SyntaxKind.PublicKeyword);

                    namespaceNode = namespaceNode.AddMembers(genControllerClass).AddMembers(r4ControllerClass);
                }
                yield return namespaceNode;
            }
        }
开发者ID:kazuk,项目名称:R4MVC,代码行数:78,代码来源:ControllerGeneratorService.cs

示例8: Rewrite

        private CSharpCompilation Rewrite(CSharpCompilation compilation)
        {
            var rewrittenTrees = new List<SyntaxTree>();
            foreach (var tree in compilation.SyntaxTrees)
            {
                var semanticModel = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
                var rewriter = new ExpressionRewriter(semanticModel);

                var rewrittenTree = tree.WithRootAndOptions(rewriter.Visit(tree.GetRoot()), tree.Options);
                rewrittenTrees.Add(rewrittenTree);
            }

            return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(rewrittenTrees);
        }
开发者ID:phinq19,项目名称:git_example,代码行数:14,代码来源:RoslynCompilationService.cs

示例9: Rewrite

        public IEnumerable<SyntaxTree> Rewrite(SyntaxTree[] syntaxTrees, CSharpCompilation compilation, string[] excludedTypes=null)
        {
            _excludedTypes = new HashSet<ITypeSymbol>();

            // Handle the user-provided exclude list
            if (excludedTypes != null)
            {
                var excludedTypeSymbols = excludedTypes.Select(compilation.GetTypeByMetadataName).ToList();
                var notFound = excludedTypeSymbols.IndexOf(null);
                if (notFound != -1)
                    throw new ArgumentException($"Type {excludedTypes[notFound]} not found in compilation", nameof(excludedTypes));
                _excludedTypes.UnionWith(excludedTypeSymbols);
            }

            // And the builtin exclude list
            _excludedTypes.UnionWith(
                AlwaysExcludedTypes
                    .Select(compilation.GetTypeByMetadataName)
                    .Where(sym => sym != null)
            );

            foreach (var syntaxTree in syntaxTrees)
            {
                var semanticModel = compilation.GetSemanticModel(syntaxTree, true);
                if (semanticModel == null)
                    throw new ArgumentException("A provided syntax tree was compiled into the provided compilation");

                var usings = syntaxTree.GetCompilationUnitRoot().Usings;

                var asyncRewriterUsing = usings.SingleOrDefault(u => u.Name.ToString() == "AsyncRewriter");
                if (asyncRewriterUsing == null)
                    continue;   // No "using AsyncRewriter", skip this file

                usings = usings
                    // Remove the AsyncRewriter using directive
                    .Remove(asyncRewriterUsing)
                    // Add the extra using directives
                    .AddRange(ExtraUsingDirectives);

                // Add #pragma warning disable at the top of the file
                usings = usings.Replace(usings[0], usings[0].WithLeadingTrivia(SyntaxFactory.Trivia(SyntaxFactory.PragmaWarningDirectiveTrivia(SyntaxFactory.Token(SyntaxKind.DisableKeyword), true))));

                var namespaces = SyntaxFactory.List<MemberDeclarationSyntax>(
                    syntaxTree.GetRoot()
                    .DescendantNodes()
                    .OfType<MethodDeclarationSyntax>()
                    .Where(m => m.AttributeLists.SelectMany(al => al.Attributes).Any(a => a.Name.ToString() == "RewriteAsync"))
                    .GroupBy(m => m.FirstAncestorOrSelf<ClassDeclarationSyntax>())
                    .GroupBy(g => g.Key.FirstAncestorOrSelf<NamespaceDeclarationSyntax>())
                    .Select(nsGrp =>
                        SyntaxFactory.NamespaceDeclaration(nsGrp.Key.Name)
                        .WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(nsGrp.Select(clsGrp =>
                            SyntaxFactory.ClassDeclaration(clsGrp.Key.Identifier)
                            .WithModifiers(clsGrp.Key.Modifiers)
                            .WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(
                                clsGrp.Select(m => RewriteMethod(m, semanticModel))
                            ))
                        )))
                    )
                );

                yield return SyntaxFactory.SyntaxTree(
                    SyntaxFactory.CompilationUnit()
                        .WithUsings(SyntaxFactory.List(usings))
                        .WithMembers(namespaces)
                        .WithEndOfFileToken(SyntaxFactory.Token(SyntaxKind.EndOfFileToken))
                        .NormalizeWhitespace()
                );
            }
        }
开发者ID:kueiwa,项目名称:AsyncRewriter,代码行数:70,代码来源:Rewriter.cs

示例10: Rewrite

		public IEnumerable<SyntaxTree> Rewrite(SyntaxTree[] syntaxTrees, CSharpCompilation compilationNode, string[] excludeTypes = null)
		{
			this.methodAttributesSymbol = compilationNode.GetTypeByMetadataName(typeof(MethodAttributes).FullName);
			this.cancellationTokenSymbol = compilationNode.GetTypeByMetadataName(typeof(CancellationToken).FullName);
			
			this.excludedTypes = new HashSet<ITypeSymbol>();

			if (excludeTypes != null)
			{
				var excludedTypeSymbols = excludeTypes.Select(compilationNode.GetTypeByMetadataName).ToList();
				var notFound = excludedTypeSymbols.IndexOf(null);

				if (notFound != -1)
				{
					throw new ArgumentException($"Type {excludeTypes[notFound]} not found in compilation", nameof(excludeTypes));
				}

				this.excludedTypes.UnionWith(excludedTypeSymbols);
			}

			this.excludedTypes.UnionWith(alwaysExcludedTypeNames.Select(compilationNode.GetTypeByMetadataName).Where(sym => sym != null));

			foreach (var syntaxTree in syntaxTrees)
			{
				var semanticModel = compilationNode.GetSemanticModel(syntaxTree, true);

				if (semanticModel == null)
				{
					throw new ArgumentException("A provided syntax tree was compiled into the provided compilation");
				}
				
				var asyncMethods = syntaxTree
					.GetRoot()
					.DescendantNodes()
					.OfType<MethodDeclarationSyntax>()
					.Where(m => m.Modifiers.Any(c => c.Kind() == SyntaxKind.AsyncKeyword));

				foreach (var asyncMethod in asyncMethods)
				{
					ValidateAsyncMethod(asyncMethod, semanticModel);
				}

				if (syntaxTree.GetRoot().DescendantNodes().All(m => ((m as MethodDeclarationSyntax)?.AttributeLists ?? (m as TypeDeclarationSyntax)?.AttributeLists)?.SelectMany(al => al.Attributes).Any(a => a.Name.ToString().StartsWith("RewriteAsync")) == null))
				{
					continue;
				}
				
				var namespaces = SyntaxFactory.List<MemberDeclarationSyntax>
				(
					syntaxTree.GetRoot()
					.DescendantNodes()
					.OfType<MethodDeclarationSyntax>()
					.Where(m => (m.Parent as TypeDeclarationSyntax)?.AttributeLists.SelectMany(al => al.Attributes).Any(a => a.Name.ToString().StartsWith("RewriteAsync"))  == true || m.AttributeLists.SelectMany(al => al.Attributes).Any(a => a.Name.ToString().StartsWith("RewriteAsync")))
					.Where(c => (c.FirstAncestorOrSelf<ClassDeclarationSyntax>() as TypeDeclarationSyntax ?? c.FirstAncestorOrSelf<InterfaceDeclarationSyntax>() as TypeDeclarationSyntax) != null)
					.GroupBy(m => m.FirstAncestorOrSelf<ClassDeclarationSyntax>() as TypeDeclarationSyntax ?? m.FirstAncestorOrSelf<InterfaceDeclarationSyntax>())
					.GroupBy(g => g.Key.FirstAncestorOrSelf<NamespaceDeclarationSyntax>())
					.Select(namespaceGrouping =>
						SyntaxFactory.NamespaceDeclaration(namespaceGrouping.Key.Name)
						.WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>
						(
							namespaceGrouping.Select
							(
								typeGrouping => 
								typeGrouping.Key is ClassDeclarationSyntax
								?
									SyntaxFactory.ClassDeclaration(typeGrouping.Key.Identifier).WithModifiers(typeGrouping.Key.Modifiers)
									.WithTypeParameterList(typeGrouping.Key.TypeParameterList)
									.WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(typeGrouping.SelectMany(m => this.RewriteMethods(m, semanticModel))))
									as TypeDeclarationSyntax
								:
									SyntaxFactory.InterfaceDeclaration(typeGrouping.Key.Identifier).WithModifiers(typeGrouping.Key.Modifiers)
									.WithTypeParameterList(typeGrouping.Key.TypeParameterList)
									.WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(typeGrouping.SelectMany(m => this.RewriteMethods(m, semanticModel))))
									as TypeDeclarationSyntax
							)
						))
					)
				);

				yield return SyntaxFactory.SyntaxTree
				(
					SyntaxFactory.CompilationUnit()
						.WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(namespaces.OfType<NamespaceDeclarationSyntax>().Select(c => AmendUsings(c, syntaxTree.GetCompilationUnitRoot().Usings))))
						.WithEndOfFileToken(SyntaxFactory.Token(SyntaxKind.EndOfFileToken))
				);
			}
		}
开发者ID:tumtumtum,项目名称:Shaolinq,代码行数:87,代码来源:Rewriter.cs


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