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


C# SemanticModel.GetDeclaredSymbol方法代码示例

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


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

示例1: TryInitializeState

		protected override bool TryInitializeState(
			Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken,
			out INamedTypeSymbol classType, out INamedTypeSymbol abstractClassType)
		{
			var baseClassNode = node as TypeSyntax;
			if (baseClassNode != null && baseClassNode.Parent is BaseTypeSyntax &&
				baseClassNode.Parent.IsParentKind(SyntaxKind.BaseList) &&
				((BaseTypeSyntax)baseClassNode.Parent).Type == baseClassNode)
			{
				if (baseClassNode.Parent.Parent.IsParentKind(SyntaxKind.ClassDeclaration))
				{
					abstractClassType = model.GetTypeInfo(baseClassNode, cancellationToken).Type as INamedTypeSymbol;
					cancellationToken.ThrowIfCancellationRequested();

					if (abstractClassType.IsAbstractClass())
					{
						var classDecl = baseClassNode.Parent.Parent.Parent as ClassDeclarationSyntax;
						classType = model.GetDeclaredSymbol(classDecl, cancellationToken) as INamedTypeSymbol;

						return classType != null && abstractClassType != null;
					}
				}
			}

			classType = null;
			abstractClassType = null;
			return false;
		}
开发者ID:sushihangover,项目名称:monodevelop,代码行数:28,代码来源:CSharpImplementAbstractClassService.cs

示例2: GetDeclaredSymbols

		internal static IEnumerable<ISymbol> GetDeclaredSymbols(SemanticModel semanticModel, MemberDeclarationSyntax memberDeclaration, CancellationToken cancellationToken)
		{
			if (memberDeclaration is FieldDeclarationSyntax)
			{
				return ((FieldDeclarationSyntax)memberDeclaration).Declaration.Variables.Select(
					v => semanticModel.GetDeclaredSymbol(v, cancellationToken));
			}

			return SpecializedCollections.SingletonEnumerable(
				semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken));
		}
开发者ID:FreeBSD-DotNet,项目名称:monodevelop,代码行数:11,代码来源:GenerateFromMembersHelpers.cs

示例3: InheritDocEstCorrect

        /// <summary>
        /// Détermine si le inheritDoc du symbole méthode est présent et correct.
        /// </summary>
        /// <param name="racine">Le nœud racine de l'arbre syntaxtique courant.</param>
        /// <param name="modèleSémantique">Le modèle sémantique lié.</param>
        /// <param name="méthode">La méthode concernée.</param>
        /// <returns>La ligne inheritDoc correcte dans le cas où l'actuelle est manquante/incorrecte, sinon null.</returns>
        public static string InheritDocEstCorrect(SyntaxNode racine, SemanticModel modèleSémantique, MethodDeclarationSyntax méthode)
        {
            var classe = méthode?.Parent as ClassDeclarationSyntax;

            // Si on est bien dans une méthode de classe.
            if (méthode != null && classe != null)
            {
                // On récupère la version sémantique de la méthode pour identifier ses paramètres.
                var méthodeSémantique = modèleSémantique.GetDeclaredSymbol(méthode);

                // On liste toutes les méthodes des interfaces de la classe puis on cherche l'unique méthode avec la même signature.
                var méthodeCorrespondantes = modèleSémantique.GetDeclaredSymbol(classe).Interfaces
                    .SelectMany(contrat => contrat.GetMembers())
                    .Where(méthodeInterface => méthodeInterface.Name == méthode.Identifier.Text
                        && ((méthodeInterface as IMethodSymbol)?.Parameters.SequenceEqual(méthodeSémantique.Parameters, (p1, p2) => p1.Name == p2.Name) ?? false));

                var méthodeCorrespondante = (méthodeCorrespondantes.Count() == 1 ? méthodeCorrespondantes.Single() : null) as IMethodSymbol;

                // S'il y a bien une méthode correspondante, on continue.
                if (méthodeCorrespondante != null)
                {
                    // On récupère le nombre de méthode du même nom dans l'interface pour savoir s'il faut spécifier les paramètres ou non.
                    var nombreMéthodesSurchargées = (méthodeCorrespondante.ContainingSymbol as INamedTypeSymbol).GetMembers()
                        .Count(méthodeInterface => méthodeInterface.Name == méthode.Identifier.Text);

#pragma warning disable SA1013, SA1513

                    // On génère la ligne de documentation.
                    var inheritDoc = [email protected]"/// <inheritdoc cref=""{
                        RécupérerNomType(méthode, méthodeCorrespondante, modèleSémantique)
                    }.{
                        RécupérerNomMéthode(méthode, méthodeCorrespondante)
                      + RécupérerParamètres(méthode, méthodeCorrespondante, modèleSémantique, nombreMéthodesSurchargées)
                    }"" />";

#pragma warning restore SA1013, SA1513

                    // On récupère la documentation actuelle de la classe.
                    var documentationActuelle = méthode.GetLeadingTrivia().ToString().Replace("\n", string.Empty).Replace("\r", string.Empty).Replace(" ", string.Empty);

                    // On la compare avec la ligne existante de façon bien crade, parce qu'en vrai elle n'est pas générée correctement.
                    // Désolé. J'ai vraiment essayé de faire proprement mais la génération propre de commentaires XML est odieuse.
                    // Si la ligne est différente et ne contient pas le mot "summary", on retourne la ligne de commentaire attendue.
                    if (!inheritDoc.Replace("\n", string.Empty).Replace("\r", string.Empty).Replace(" ", string.Empty)
                            .Equals(documentationActuelle) && !documentationActuelle.Contains("summary"))
                        return inheritDoc;
                }
            }

            // Sinon on renvoie null, pour affirmer au diagnostic que tout va bien.
            return null;
        }
开发者ID:JabX,项目名称:controle-point-virgule,代码行数:59,代码来源:Partagé.cs

示例4: EvaluateImpl

		protected override async Task<EvaluationResult> EvaluateImpl(SyntaxNode node, SemanticModel semanticModel, Solution solution)
		{
			var symbol = (ITypeSymbol)semanticModel.GetDeclaredSymbol(node);
			var efferent = GetReferencedTypes(node, symbol, semanticModel).AsArray();
			var awaitable = SymbolFinder.FindCallersAsync(symbol, solution, CancellationToken.None).ConfigureAwait(false);
			var callers = (await awaitable).AsArray();
			var testCallers = callers
				.Where(c => c.CallingSymbol.GetAttributes()
				.Any(x => x.AttributeClass.Name.IsKnownTestAttribute()))
				.AsArray();
			var afferent = callers.Except(testCallers)
				.Select(x => x.CallingSymbol.ContainingType)
				.DistinctBy(s => s.ToDisplayString())
				.AsArray();

			var efferentLength = (double)efferent.Length;
			var stability = efferentLength / (efferentLength + afferent.Length);
			if (stability >= 0.8)
			{
				return new EvaluationResult
				{
					ImpactLevel = ImpactLevel.Project,
					Quality = CodeQuality.NeedsReview,
					QualityAttribute = QualityAttribute.CodeQuality | QualityAttribute.Conformance,
					Snippet = node.ToFullString()
				};
			}

			return null;
		}
开发者ID:jjrdk,项目名称:ArchiMetrics,代码行数:30,代码来源:ClassInstabilityRule.cs

示例5: GetActions

        protected IEnumerable<CodeAction> GetActions(Document document, SemanticModel semanticModel, SyntaxNode root, TextSpan span, ParameterSyntax node)
        {
            if (!node.Identifier.Span.Contains(span))
                yield break;

            var parameter = node;
            var bodyStatement = parameter.Parent.Parent.ChildNodes().OfType<BlockSyntax>().FirstOrDefault();
            if (bodyStatement == null)
                yield break;

            var parameterSymbol = semanticModel.GetDeclaredSymbol(node);
            var type = parameterSymbol.Type;
            if (type == null || type.IsValueType || HasNotNullContract(semanticModel, parameterSymbol, bodyStatement))
                yield break;

            yield return CreateAction(
                node.Identifier.Span
                , t2 => {
                    var newBody = bodyStatement.WithStatements(SyntaxFactory.List<StatementSyntax>(new[] { CreateContractRequiresCall(node.Identifier.ToString()) }.Concat(bodyStatement.Statements)));

                    var newRoot = (CompilationUnitSyntax)root.ReplaceNode((SyntaxNode)bodyStatement, newBody);

                    if (UsingStatementNotPresent(newRoot)) newRoot = AddUsingStatement(node, newRoot);

                    return Task.FromResult(document.WithSyntaxRoot(newRoot));
                }
                , "Add contract requiring parameter must not be null"
            );
        }
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:29,代码来源:ContractRequiresNotNullCodeRefactoringProvider.cs

示例6: GetDiagnosticsForNode

        protected sealed override IEnumerable<Diagnostic> GetDiagnosticsForNode(SyntaxNode node, SemanticModel model)
        {
            var typeSymbol = model.GetDeclaredSymbol(node);
            var namedType = typeSymbol as INamedTypeSymbol;

            // static holder types are not already static/sealed and must be public or protected
            if (namedType != null && !namedType.IsStatic && !namedType.IsSealed
                && (namedType.DeclaredAccessibility == Accessibility.Public || namedType.DeclaredAccessibility == Accessibility.Protected))
            {
                // only get the explicitly declared members
                var allMembers = namedType.GetMembers().Where(member => !member.IsImplicitlyDeclared);
                if (!allMembers.Any())
                {
                    return null;
                }

                // to be a static holder type, all members must be static and not operator overloads
                if (allMembers.All(member => member.IsStatic && !IsUserdefinedOperator(member)))
                {
                    var diagnostic = typeSymbol.CreateDiagnostic(Rule, string.Format(FxCopRulesResources.TypeIsStaticHolderButNotSealed, namedType.Name));
                    return SpecializedCollections.SingletonEnumerable(diagnostic);
                }
            }

            return null;
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:26,代码来源:CA1052DiagnosticProviderBase.cs

示例7: GetTypesToRemove

		internal static ImmutableArray<TypeToRemove> GetTypesToRemove(
			this SyntaxNode @this, SemanticModel model, 
			string documentFileNameWithoutExtension)
		{
			var typesToRemove = new List<TypeToRemove>();
			TypeDeclarationSyntax typeToPreserve = null;

			var typeNodes = @this.DescendantNodes(_ => true)
				.OfType<TypeDeclarationSyntax>();

			foreach(var typeNode in typeNodes)
			{
				var type = model.GetDeclaredSymbol(typeNode) as ITypeSymbol;

				if(type.ContainingType == null)
				{
					if(type.Name != documentFileNameWithoutExtension)
					{
						typesToRemove.Add(new TypeToRemove(
							typeNode, type));
					}
					else
					{
						typeToPreserve = typeNode;
					}
				}
			}

			return typesToRemove.ToImmutableArray();
		}
开发者ID:JasonBock,项目名称:CompilerAPIBook,代码行数:30,代码来源:SyntaxNodeExtensions.cs

示例8: HasFlagsAttribute

        internal static bool HasFlagsAttribute(SyntaxNode node, SemanticModel semanticModel)
        {
            var symbol = semanticModel.GetDeclaredSymbol(node);

            return symbol != null && 
                symbol.GetAttributes().Any(attribute => attribute.AttributeClass.Is(KnownType.System_FlagsAttribute));
        }
开发者ID:dbolkensteyn,项目名称:sonarlint-vs,代码行数:7,代码来源:FlagsEnumWithoutInitializerBase.cs

示例9: GetDeclaredSymbol

        private static ISymbol GetDeclaredSymbol(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken)
        {
            if (!getSymbol)
            {
                return null;
            }

            var declaredSymbol = model.GetDeclaredSymbol(node, cancellationToken);

            // For namespace declarations, GetDeclaredSymbol returns a compilation scoped namespace symbol,
            // which includes declarations across the compilation, including those in referenced assemblies.
            // However, we are only interested in the namespace symbol scoped to the compilation's source assembly.
            var namespaceSymbol = declaredSymbol as INamespaceSymbol;
            if (namespaceSymbol != null && namespaceSymbol.ConstituentNamespaces.Length > 1)
            {
                var assemblyToScope = model.Compilation.Assembly;
                var assemblyScopedNamespaceSymbol = namespaceSymbol.ConstituentNamespaces.FirstOrDefault(ns => ns.ContainingAssembly == assemblyToScope);
                if (assemblyScopedNamespaceSymbol != null)
                {
                    Debug.Assert(assemblyScopedNamespaceSymbol.ConstituentNamespaces.Length == 1);
                    declaredSymbol = assemblyScopedNamespaceSymbol;
                }
            }

            return declaredSymbol;
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:26,代码来源:DeclarationComputer.cs

示例10: SimplifyASTForMethod

        /// <summary>
        /// This is jus a test to check the ability to preprocess the AST
        /// </summary>
        /// <param name="methodNode"></param>
        /// <param name="semanticModel"></param>
        /// <returns></returns>
        public static IMethodSymbol SimplifyASTForMethod(ref SyntaxNode methodNode, ref SemanticModel semanticModel)
        {
            var oldMethod = semanticModel.GetDeclaredSymbol(methodNode) as IMethodSymbol;

            var newMethodNode = MethodSimpifier.Test(methodNode);

            var annotation = new SyntaxAnnotation("Hi");

            newMethodNode = newMethodNode.WithAdditionalAnnotations(annotation);

            var root = methodNode.SyntaxTree.GetRoot();
            var newRoot = root.ReplaceNode(methodNode, newMethodNode);

            var oldCompilation = semanticModel.Compilation;

            var newCompilation = oldCompilation.ReplaceSyntaxTree(root.SyntaxTree, newRoot.SyntaxTree);
            var newSemanticModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree);

            var recoveredMethodNode = newRoot.GetAnnotatedNodes(annotation).Single();

            var method = newSemanticModel.GetDeclaredSymbol(recoveredMethodNode) as IMethodSymbol;

            methodNode = recoveredMethodNode;
            semanticModel = newSemanticModel;

            return method;
        }
开发者ID:TubaKayaDev,项目名称:Call-Graph-Builder-DotNet,代码行数:33,代码来源:MethodSimpifier.cs

示例11: GetDeclarationInfo

 internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, IEnumerable<SyntaxNode> executableCodeBlocks, CancellationToken cancellationToken)
 {
     var declaredSymbol = getSymbol ? model.GetDeclaredSymbol(node, cancellationToken) : null;
     var codeBlocks = executableCodeBlocks == null ?
         ImmutableArray<SyntaxNode>.Empty :
         executableCodeBlocks.Where(c => c != null).AsImmutableOrEmpty();
     return new DeclarationInfo(node, codeBlocks, declaredSymbol);
 }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:8,代码来源:DeclarationComputer.cs

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

示例13: GetSymbols

		protected override IEnumerable<ISymbol> GetSymbols(SyntaxNode node, SemanticModel semanticModel)
		{
			var declaration = (VariableDeclarationSyntax)node;

			var symbols = declaration.Variables.Select(x => semanticModel.GetDeclaredSymbol(x)).AsArray();

			return symbols;
		}
开发者ID:jjrdk,项目名称:ArchiMetrics,代码行数:8,代码来源:UnreadVariableRule.cs

示例14: FlowsIntoTarget

 /// <summary>
 /// Returns true if the given expression flows in the target.
 /// </summary>
 /// <param name="variable">Variable</param>
 /// <param name="target">Target</param>
 /// <param name="syntaxNode">SyntaxNode</param>
 /// <param name="cfgNode">ControlFlowGraphNode</param>
 /// <param name="targetSyntaxNode">Target syntaxNode</param>
 /// <param name="targetCfgNode">Target controlFlowGraphNode</param>
 /// <param name="model">SemanticModel</param>
 /// <returns>Boolean</returns>
 internal static bool FlowsIntoTarget(VariableDeclaratorSyntax variable, ISymbol target,
     SyntaxNode syntaxNode, ControlFlowGraphNode cfgNode, SyntaxNode targetSyntaxNode,
     ControlFlowGraphNode targetCfgNode, SemanticModel model)
 {
     ISymbol reference = model.GetDeclaredSymbol(variable);
     return DataFlowAnalysis.FlowsIntoTarget(reference, target, syntaxNode,
         cfgNode, targetSyntaxNode, targetCfgNode);
 }
开发者ID:huangpf,项目名称:PSharp,代码行数:19,代码来源:DataFlowAnalysis.cs

示例15: AreVariablesOnlyWrittenInsideDeclaration

 static bool AreVariablesOnlyWrittenInsideDeclaration(LocalDeclarationStatementSyntax declaration, SemanticModel semanticModel)
 {
     var dfa = semanticModel.AnalyzeDataFlow(declaration);
     var symbols = from variable in declaration.Declaration.Variables
                   select semanticModel.GetDeclaredSymbol(variable);
     var result = !symbols.Any(s => dfa.WrittenOutside.Contains(s));
     return result;
 }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:8,代码来源:MakeLocalVariableConstWhenItIsPossibleAnalyzer.cs


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