本文整理汇总了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;
}
示例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));
}
示例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;
}
示例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;
}
示例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;
}
示例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();
}
示例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));
}
示例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;
}
示例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;
}
示例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);
}
示例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));
}
示例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;
}
示例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);
}
示例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;
}