本文整理汇总了C#中SemanticModel.GetSymbolInfo方法的典型用法代码示例。如果您正苦于以下问题:C# SemanticModel.GetSymbolInfo方法的具体用法?C# SemanticModel.GetSymbolInfo怎么用?C# SemanticModel.GetSymbolInfo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SemanticModel
的用法示例。
在下文中一共展示了SemanticModel.GetSymbolInfo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AnalyzeInvocationExpression
private void AnalyzeInvocationExpression(InvocationExpressionSyntax node, SemanticModel model, Action<Diagnostic> reportDiagnostic)
{
if (node.Expression.Kind() == SyntaxKind.SimpleMemberAccessExpression)
{
var memberAccess = (MemberAccessExpressionSyntax)node.Expression;
if (memberAccess.Name != null && IsEqualsOrCompare(memberAccess.Name.Identifier.ValueText))
{
var methodSymbol = model.GetSymbolInfo(memberAccess.Name).Symbol as IMethodSymbol;
if (methodSymbol != null && methodSymbol.ContainingType.SpecialType == SpecialType.System_String)
{
Debug.Assert(IsEqualsOrCompare(methodSymbol.Name));
if (!IsAcceptableOverload(methodSymbol, model))
{
// wrong overload
reportDiagnostic(memberAccess.Name.GetLocation().CreateDiagnostic(Rule));
}
else
{
var lastArgument = node.ArgumentList.Arguments.Last();
var lastArgSymbol = model.GetSymbolInfo(lastArgument.Expression).Symbol;
if (lastArgSymbol != null && lastArgSymbol.ContainingType != null &&
lastArgSymbol.ContainingType.Equals(StringComparisonType) &&
!IsOrdinalOrOrdinalIgnoreCase(lastArgument, model))
{
// right overload, wrong value
reportDiagnostic(lastArgument.GetLocation().CreateDiagnostic(Rule));
}
}
}
}
}
}
示例2: GetSymbolInfo
public static SymbolInfo GetSymbolInfo(SemanticModel model, SyntaxNode node, CancellationToken cancellationToken)
{
var nodeCache = GetNodeCache(model);
if (nodeCache == null)
{
return model.GetSymbolInfo(node, cancellationToken);
}
return nodeCache.GetOrAdd(node, n => model.GetSymbolInfo(n, cancellationToken));
}
示例3: GetUpdatedDocumentAsync
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
// if nothing can be fixed, return the unchanged node
var newRoot = root;
var kind = nodeToFix.CSharpKind();
var syntaxFactoryService = document.GetLanguageService<SyntaxGenerator>();
switch (kind)
{
case SyntaxKind.Argument:
// StringComparison.CurrentCulture => StringComparison.Ordinal
// StringComparison.CurrentCultureIgnoreCase => StringComparison.OrdinalIgnoreCase
var argument = (ArgumentSyntax)nodeToFix;
var memberAccess = argument.Expression as MemberAccessExpressionSyntax;
if (memberAccess != null)
{
// preserve the "IgnoreCase" suffix if present
bool isIgnoreCase = memberAccess.Name.GetText().ToString().EndsWith(CA1309DiagnosticAnalyzer.IgnoreCaseText);
var newOrdinalText = isIgnoreCase ? CA1309DiagnosticAnalyzer.OrdinalIgnoreCaseText : CA1309DiagnosticAnalyzer.OrdinalText;
var newIdentifier = syntaxFactoryService.IdentifierName(newOrdinalText);
var newMemberAccess = memberAccess.WithName((SimpleNameSyntax)newIdentifier).WithAdditionalAnnotations(Formatter.Annotation);
newRoot = root.ReplaceNode(memberAccess, newMemberAccess);
}
break;
case SyntaxKind.IdentifierName:
// string.Equals(a, b) => string.Equals(a, b, StringComparison.Ordinal)
// string.Compare(a, b) => string.Compare(a, b, StringComparison.Ordinal)
var identifier = (IdentifierNameSyntax)nodeToFix;
var invokeParent = identifier.GetAncestor<InvocationExpressionSyntax>();
if (invokeParent != null)
{
var methodSymbol = model.GetSymbolInfo(identifier).Symbol as IMethodSymbol;
if (methodSymbol != null && CanAddStringComparison(methodSymbol))
{
// append a new StringComparison.Ordinal argument
var newArg = syntaxFactoryService.Argument(CreateOrdinalMemberAccess(syntaxFactoryService, model))
.WithAdditionalAnnotations(Formatter.Annotation);
var newInvoke = invokeParent.AddArgumentListArguments((ArgumentSyntax)newArg).WithAdditionalAnnotations(Formatter.Annotation);
newRoot = root.ReplaceNode(invokeParent, newInvoke);
}
}
break;
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
// "a == b" => "string.Equals(a, b, StringComparison.Ordinal)"
// "a != b" => "!string.Equals(a, b, StringComparison.Ordinal)"
var binaryExpression = (BinaryExpressionSyntax)nodeToFix;
var invocation = CreateEqualsExpression(syntaxFactoryService, model, binaryExpression.Left, binaryExpression.Right, kind == SyntaxKind.EqualsExpression).WithAdditionalAnnotations(Formatter.Annotation);
newRoot = root.ReplaceNode(nodeToFix, invocation);
break;
}
if (newRoot == root)
{
return Task.FromResult(document);
}
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
示例4: GetSymbolsTouchingPosition
internal static IEnumerable<ISymbol> GetSymbolsTouchingPosition(
int position, SemanticModel semanticModel, Workspace workspace, CancellationToken cancellationToken)
{
var bindableToken = semanticModel.SyntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true);
var semanticInfo = semanticModel.GetSemanticInfo(bindableToken, workspace, cancellationToken);
var symbols = semanticInfo.DeclaredSymbol != null
? ImmutableArray.Create<ISymbol>(semanticInfo.DeclaredSymbol)
: semanticInfo.GetSymbols(includeType: false);
// if there are more than one symbol, then remove the alias symbols.
// When using (not declaring) an alias, the alias symbol and the target symbol are returned
// by GetSymbols
if (symbols.Length > 1)
{
symbols = symbols.WhereAsArray(s => s.Kind != SymbolKind.Alias);
}
if (symbols.Length == 0)
{
var info = semanticModel.GetSymbolInfo(bindableToken, cancellationToken);
if (info.CandidateReason == CandidateReason.MemberGroup)
{
return info.CandidateSymbols;
}
}
return symbols;
}
示例5: GetMethodDeclaration
private async Task<MethodDeclarationSyntax> GetMethodDeclaration(
SyntaxNode node,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var invocationExpression = node.ChildNodes().FirstOrDefault(n => n.IsKind(SyntaxKind.InvocationExpression));
var methodSymbol = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol as IMethodSymbol;
if (methodSymbol == null)
{
return null;
}
var methodReference = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault();
if (methodReference == null)
{
return null;
}
var methodDeclaration = (await methodReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false)) as MethodDeclarationSyntax;
if (methodDeclaration == null)
{
return null;
}
if (!methodDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
return null;
}
return methodDeclaration;
}
示例6: GetDelegateInvokeItems
private IEnumerable<SignatureHelpItem> GetDelegateInvokeItems(
InvocationExpressionSyntax invocationExpression, SemanticModel semanticModel, ISymbolDisplayService symbolDisplayService, IAnonymousTypeDisplayService anonymousTypeDisplayService,
IDocumentationCommentFormattingService documentationCommentFormattingService, ISymbol within, INamedTypeSymbol delegateType, CancellationToken cancellationToken)
{
var invokeMethod = delegateType.DelegateInvokeMethod;
if (invokeMethod == null)
{
return null;
}
// Events can only be invoked directly from the class they were declared in.
var expressionSymbol = semanticModel.GetSymbolInfo(invocationExpression.Expression, cancellationToken).GetAnySymbol();
if (expressionSymbol.IsKind(SymbolKind.Event) &&
!expressionSymbol.ContainingType.OriginalDefinition.Equals(within.OriginalDefinition))
{
return null;
}
var position = invocationExpression.SpanStart;
var item = CreateItem(
invokeMethod, semanticModel, position,
symbolDisplayService, anonymousTypeDisplayService,
isVariadic: invokeMethod.IsParams(),
documentation: SpecializedCollections.EmptyEnumerable<SymbolDisplayPart>(),
prefixParts: GetDelegateInvokePreambleParts(invokeMethod, semanticModel, position),
separatorParts: GetSeparatorParts(),
suffixParts: GetDelegateInvokePostambleParts(),
parameters: GetDelegateInvokeParameters(invokeMethod, semanticModel, position, documentationCommentFormattingService, cancellationToken));
return SpecializedCollections.SingletonEnumerable(item);
}
示例7: TryGetTaskAndExpressionTypes
protected static bool TryGetTaskAndExpressionTypes(
SyntaxNode expression,
SemanticModel semanticModel,
out INamedTypeSymbol source,
out INamedTypeSymbol destination)
{
source = null;
destination = null;
var info = semanticModel.GetSymbolInfo(expression);
var methodSymbol = info.Symbol as IMethodSymbol;
if (methodSymbol == null)
{
return false;
}
var compilation = semanticModel.Compilation;
var taskType = compilation.GetTypeByMetadataName("System.Threading.Tasks.Task");
if (taskType == null)
{
return false;
}
var returnType = methodSymbol.ReturnType as INamedTypeSymbol;
if (returnType == null)
{
return false;
}
source = taskType;
destination = returnType;
return true;
}
示例8: AnalyzeMember
private Issue AnalyzeMember(MemberInfo memberInfo, SemanticModel model, ClassInfo classInfo)
{
foreach (BlockSyntax block in memberInfo.Blocks)
{
var identifiers = block.DescendantNodes().OfType<IdentifierNameSyntax>().ToList();
foreach (IdentifierNameSyntax identifierName in identifiers)
{
SymbolInfo identifierSymbol = model.GetSymbolInfo(identifierName);
//Does this symbol refer to a GuardedField?
GuardedFieldInfo foundGuardedField = classInfo.GuardedFields.FirstOrDefault(field => field.Symbol == identifierSymbol.Symbol);
if (foundGuardedField != null)
{
//We must be inside a lock statement
LockHierarchy controlFlowHierarchy = CreateLockHiearchyFromIdentifier(identifierName);
bool lockHierarchySatisfied = LockHierarchy.IsSatisfiedBy(foundGuardedField.DeclaredLockHierarchy, controlFlowHierarchy);
if (!lockHierarchySatisfied)
{
return new Issue(
ErrorCode.GUARDED_FIELD_ACCESSED_OUTSIDE_OF_LOCK,
identifierName,
identifierSymbol.Symbol);
}
}
}
}
return null;
}
示例9: GetCompletionsOffOfExplicitInterfaceAsync
private async Task<IEnumerable<CompletionItem>> GetCompletionsOffOfExplicitInterfaceAsync(
Document document, SemanticModel semanticModel, int position, NameSyntax name, CancellationToken cancellationToken)
{
// Bind the interface name which is to the left of the dot
var syntaxTree = semanticModel.SyntaxTree;
var nameBinding = semanticModel.GetSymbolInfo(name, cancellationToken);
var context = CSharpSyntaxContext.CreateContext(document.Project.Solution.Workspace, semanticModel, position, cancellationToken);
var symbol = nameBinding.Symbol as ITypeSymbol;
if (symbol == null || symbol.TypeKind != TypeKind.Interface)
{
return SpecializedCollections.EmptyEnumerable<CompletionItem>();
}
var members = semanticModel.LookupSymbols(
position: name.SpanStart,
container: symbol)
.Where(s => !s.IsStatic)
.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation);
// We're going to create a entry for each one, including the signature
var completions = new List<CompletionItem>();
var signatureDisplayFormat =
new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
var namePosition = name.SpanStart;
var text = await context.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
var textChangeSpan = CompletionUtilities.GetTextChangeSpan(text, context.Position);
foreach (var member in members)
{
var displayString = member.ToMinimalDisplayString(semanticModel, namePosition, signatureDisplayFormat);
var memberCopied = member;
var insertionText = displayString;
completions.Add(new SymbolCompletionItem(
this,
displayString,
insertionText: insertionText,
filterSpan: textChangeSpan,
position: position,
symbols: new List<ISymbol> { member },
context: context,
rules: ItemRules.Instance));
}
return completions;
}
示例10: GetExplicitNamespaceSymbol
private INamespaceSymbol GetExplicitNamespaceSymbol(ExpressionSyntax fullName, ExpressionSyntax namespacePart, SemanticModel model)
{
// name must refer to something that is not a namespace, but be qualified with a namespace.
var symbol = model.GetSymbolInfo(fullName).Symbol;
var nsSymbol = model.GetSymbolInfo(namespacePart).Symbol as INamespaceSymbol;
if (symbol != null && symbol.Kind != SymbolKind.Namespace && nsSymbol != null)
{
// use the symbols containing namespace, and not the potentially less than fully qualified namespace in the full name expression.
var ns = symbol.ContainingNamespace;
if (ns != null)
{
return model.Compilation.GetCompilationNamespace(ns);
}
}
return null;
}
示例11: GetUpdatedDocumentAsync
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var charSetType = WellKnownTypes.CharSet(model.Compilation);
var dllImportType = WellKnownTypes.DllImportAttribute(model.Compilation);
var marshalAsType = WellKnownTypes.MarshalAsAttribute(model.Compilation);
var unmanagedType = WellKnownTypes.UnmanagedType(model.Compilation);
if (charSetType == null || dllImportType == null || marshalAsType == null || unmanagedType == null)
{
return Task.FromResult(document);
}
var syntaxFactoryService = document.Project.LanguageServices.GetService<SyntaxGenerator>();
// return the unchanged root if no fix is available
var newRoot = root;
if (nodeToFix.CSharpKind() == SyntaxKind.Attribute)
{
// could be either a [DllImport] or [MarshalAs] attribute
var attribute = (AttributeSyntax)nodeToFix;
var attributeType = model.GetSymbolInfo(attribute).Symbol;
var arguments = attribute.ArgumentList.Arguments;
if (dllImportType.Equals(attributeType.ContainingType))
{
// [DllImport] attribute, add or replace CharSet named parameter
var argumentValue = CreateCharSetArgument(syntaxFactoryService, charSetType).WithAdditionalAnnotations(Formatter.Annotation);
var namedParameter = arguments.FirstOrDefault(arg => arg.NameEquals != null && arg.NameEquals.Name.Identifier.Text == CharSetText);
if (namedParameter == null)
{
// add the parameter
namedParameter = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(CharSetText), null, (ExpressionSyntax)argumentValue)
.WithAdditionalAnnotations(Formatter.Annotation);
var newArguments = arguments.Add(namedParameter);
var newArgumentList = attribute.ArgumentList.WithArguments(newArguments);
newRoot = root.ReplaceNode(attribute.ArgumentList, newArgumentList);
}
else
{
// replace the parameter
var newNamedParameter = namedParameter.WithExpression((ExpressionSyntax)argumentValue);
newRoot = root.ReplaceNode(namedParameter, newNamedParameter);
}
}
else if (marshalAsType.Equals(attributeType.ContainingType) && arguments.Count == 1)
{
// [MarshalAs] attribute, replace the only argument
var newExpression = CreateMarshalAsArgument(syntaxFactoryService, unmanagedType)
.WithLeadingTrivia(arguments[0].GetLeadingTrivia())
.WithTrailingTrivia(arguments[0].GetTrailingTrivia());
var newArgument = arguments[0].WithExpression((ExpressionSyntax)newExpression);
newRoot = root.ReplaceNode(arguments[0], newArgument);
}
}
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
示例12: GetOuterCastType
private static ITypeSymbol GetOuterCastType(ExpressionSyntax expression, SemanticModel semanticModel, out bool parentIsOrAsExpression)
{
expression = expression.WalkUpParentheses();
parentIsOrAsExpression = false;
var parentNode = expression.Parent;
if (parentNode == null)
{
return null;
}
if (parentNode.IsKind(SyntaxKind.CastExpression))
{
var castExpression = (CastExpressionSyntax)parentNode;
return semanticModel.GetTypeInfo(castExpression).Type;
}
if (parentNode.IsKind(SyntaxKind.IsExpression) ||
parentNode.IsKind(SyntaxKind.AsExpression))
{
parentIsOrAsExpression = true;
return null;
}
if (parentNode.IsKind(SyntaxKind.ArrayRankSpecifier))
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Int32);
}
if (parentNode.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
var memberAccess = (MemberAccessExpressionSyntax)parentNode;
if (memberAccess.Expression == expression)
{
var memberSymbol = semanticModel.GetSymbolInfo(memberAccess).Symbol;
if (memberSymbol != null)
{
return memberSymbol.ContainingType;
}
}
}
if (parentNode.IsKind(SyntaxKind.ConditionalExpression) &&
((ConditionalExpressionSyntax)parentNode).Condition == expression)
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean);
}
if ((parentNode is PrefixUnaryExpressionSyntax || parentNode is PostfixUnaryExpressionSyntax) &&
!semanticModel.GetConversion(expression).IsUserDefined)
{
var parentEpression = (ExpressionSyntax)parentNode;
return GetOuterCastType(parentEpression, semanticModel, out parentIsOrAsExpression) ?? semanticModel.GetTypeInfo(parentEpression).ConvertedType;
}
return null;
}
示例13: VerifyModelForDeclarationPattern
protected static void VerifyModelForDeclarationPattern(
SemanticModel model,
DeclarationPatternSyntax decl,
bool isShadowed,
params IdentifierNameSyntax[] references)
{
var symbol = model.GetDeclaredSymbol(decl);
Assert.Equal(decl.Identifier.ValueText, symbol.Name);
Assert.Equal(decl, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(LocalDeclarationKind.PatternVariable, ((LocalSymbol)symbol).DeclarationKind);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)decl));
if (isShadowed)
{
Assert.NotEqual(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single());
}
else
{
Assert.Same(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single());
}
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText));
Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(decl.Type));
Assert.True(SyntaxFacts.IsInTypeOnlyContext(decl.Type));
var local = ((SourceLocalSymbol)symbol);
var type = local.Type;
if (type.IsErrorType())
{
Assert.Null(model.GetSymbolInfo(decl.Type).Symbol);
}
else
{
Assert.Equal(type, model.GetSymbolInfo(decl.Type).Symbol);
}
foreach (var reference in references)
{
Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol);
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText));
}
}
示例14: GetImportedNamespaceSymbol
protected override INamespaceSymbol GetImportedNamespaceSymbol(SyntaxNode import, SemanticModel model)
{
var @using = import as UsingDirectiveSyntax;
if (@using != null && @using.Alias == null)
{
return model.GetSymbolInfo(@using.Name).Symbol as INamespaceSymbol;
}
return null;
}
示例15: GetExistingNamespaces
private IList<INamespaceSymbol> GetExistingNamespaces(
SemanticModel semanticModel, CompilationUnitSyntax compilationUnit, CancellationToken cancellationToken)
{
var q = from u in compilationUnit.Usings
let symbol = semanticModel.GetSymbolInfo(u.Name, cancellationToken).Symbol as INamespaceSymbol
where symbol != null && !symbol.IsGlobalNamespace
select symbol;
return q.ToList();
}