本文整理汇总了C#中Microsoft.CodeAnalysis.SemanticModel.GetSymbolInfo方法的典型用法代码示例。如果您正苦于以下问题:C# SemanticModel.GetSymbolInfo方法的具体用法?C# SemanticModel.GetSymbolInfo怎么用?C# SemanticModel.GetSymbolInfo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CodeAnalysis.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: HasCheckForNullThatReturns
private static bool HasCheckForNullThatReturns(InvocationExpressionSyntax invocation, SemanticModel semanticModel, ISymbol symbol)
{
var method = invocation.FirstAncestorOfKind(SyntaxKind.MethodDeclaration) as MethodDeclarationSyntax;
if (method != null && method.Body != null)
{
var ifs = method.Body.Statements.OfKind(SyntaxKind.IfStatement);
foreach (IfStatementSyntax @if in ifs)
{
if ([email protected]?.IsKind(SyntaxKind.EqualsExpression) ?? true) continue;
var equals = (BinaryExpressionSyntax)@if.Condition;
if (equals.Left == null || equals.Right == null) continue;
if (@if.GetLocation().SourceSpan.Start > invocation.GetLocation().SourceSpan.Start) return false;
ISymbol identifierSymbol;
if (equals.Right.IsKind(SyntaxKind.NullLiteralExpression) && equals.Left.IsKind(SyntaxKind.IdentifierName))
identifierSymbol = semanticModel.GetSymbolInfo(equals.Left).Symbol;
else if (equals.Left.IsKind(SyntaxKind.NullLiteralExpression) && equals.Right.IsKind(SyntaxKind.IdentifierName))
identifierSymbol = semanticModel.GetSymbolInfo(equals.Right).Symbol;
else continue;
if (!symbol.Equals(identifierSymbol)) continue;
if (@if.Statement == null) continue;
if (@if.Statement.IsKind(SyntaxKind.Block))
{
var ifBlock = (BlockSyntax)@if.Statement;
if (ifBlock.Statements.OfKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement).Any()) return true;
}
else
{
if (@if.Statement.IsAnyKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement)) return true;
}
}
}
return false;
}
示例3: TrouverAssignations
/// <summary>
/// Retourne les assignations dans une listes d'expressions.
/// </summary>
/// <param name="expressions">Liste d'expressions.</param>
/// <param name="modèleSémantique">Modèle sémantique.</param>
/// <returns>La liste d'assignations.</returns>
public static IEnumerable<StatementSyntax> TrouverAssignations(SyntaxList<StatementSyntax> expressions, SemanticModel modèleSémantique) =>
expressions.Where(e =>
{
var expression = (e as ExpressionStatementSyntax)?.Expression as AssignmentExpressionSyntax;
return expression?.Kind() == SyntaxKind.SimpleAssignmentExpression
&& modèleSémantique.GetSymbolInfo(expression.Left).Symbol?.Kind == SymbolKind.Field
&& modèleSémantique.GetSymbolInfo(expression.Right).Symbol?.Kind == SymbolKind.Parameter;
});
示例4: AnalyzeOwnershipInAssignment
/// <summary>
/// Analyzes the ownership of the given-up symbol
/// in the assignment expression.
/// </summary>
/// <param name="givenUpSymbol">GivenUpOwnershipSymbol</param>
/// <param name="assignment">AssignmentExpressionSyntax</param>
/// <param name="statement">Statement</param>
/// <param name="machine">StateMachine</param>
/// <param name="model">SemanticModel</param>
/// <param name="trace">TraceInfo</param>
protected override void AnalyzeOwnershipInAssignment(GivenUpOwnershipSymbol givenUpSymbol,
AssignmentExpressionSyntax assignment, Statement statement, StateMachine machine,
SemanticModel model, TraceInfo trace)
{
var leftIdentifier = base.AnalysisContext.GetRootIdentifier(assignment.Left);
ISymbol leftSymbol = model.GetSymbolInfo(leftIdentifier).Symbol;
if (assignment.Right is IdentifierNameSyntax)
{
var rightIdentifier = base.AnalysisContext.GetRootIdentifier(assignment.Right);
ISymbol rightSymbol = model.GetSymbolInfo(rightIdentifier).Symbol;
if (statement.Summary.DataFlowAnalysis.FlowsIntoSymbol(rightSymbol,
givenUpSymbol.ContainingSymbol, statement, givenUpSymbol.Statement))
{
var type = model.GetTypeInfo(assignment.Right).Type;
if (leftSymbol != null && leftSymbol.Kind == SymbolKind.Field &&
base.IsFieldAccessedInSuccessor(leftSymbol as IFieldSymbol, statement.Summary, machine) &&
!base.AnalysisContext.IsTypePassedByValueOrImmutable(type))
{
TraceInfo newTrace = new TraceInfo();
newTrace.Merge(trace);
newTrace.AddErrorTrace(statement.SyntaxNode);
AnalysisErrorReporter.ReportGivenUpOwnershipFieldAssignment(newTrace, leftSymbol);
}
return;
}
}
else if (assignment.Right is MemberAccessExpressionSyntax)
{
this.AnalyzeOwnershipInExpression(givenUpSymbol, assignment.Right, statement,
machine, model, trace);
}
else if (assignment.Right is InvocationExpressionSyntax ||
assignment.Right is ObjectCreationExpressionSyntax)
{
trace.InsertCall(statement.Summary.Method, assignment.Right);
base.AnalyzeOwnershipInCall(givenUpSymbol, assignment.Right, statement,
machine, model, trace);
}
if (assignment.Left is MemberAccessExpressionSyntax)
{
ISymbol outerLeftMemberSymbol = model.GetSymbolInfo(assignment.Left).Symbol;
if (!outerLeftMemberSymbol.Equals(leftSymbol) &&
statement.Summary.DataFlowAnalysis.FlowsIntoSymbol(givenUpSymbol.ContainingSymbol,
leftSymbol, givenUpSymbol.Statement, statement))
{
TraceInfo newTrace = new TraceInfo();
newTrace.Merge(trace);
newTrace.AddErrorTrace(statement.SyntaxNode);
AnalysisErrorReporter.ReportGivenUpOwnershipAccess(newTrace);
}
}
}
示例5: ShouldReportOnCollectionNode
internal static bool ShouldReportOnCollectionNode(SemanticModel semanticModel, SyntaxNode argument) {
const bool returnIfUnknown = false;
// if the variable is an invocation syntax we can assume that it was returned materialized, if it's not an extension method
switch(argument.Kind()) {
case SyntaxKind.InvocationExpression:
var methodCallInfo = semanticModel.GetSymbolInfo(argument);
if((methodCallInfo.Symbol != null) && (methodCallInfo.Symbol.Kind == SymbolKind.Method)) {
var mSymbol = (IMethodSymbol)methodCallInfo.Symbol;
var typeInfo = semanticModel.GetTypeInfo(argument);
// If the method is not an extension method, we assume it returned a materialized collection
return IsAbstractCollectionType(typeInfo) && mSymbol.IsExtensionMethod && mSymbol.ContainingNamespace.ToDisplayString().Equals("System.Linq");
}
break;
case SyntaxKind.IdentifierName:
var identifierInfo = semanticModel.GetSymbolInfo(argument);
// if this identifier came straight from a parameter, assume it is materialized
if(identifierInfo.Symbol != null && identifierInfo.Symbol.Kind == SymbolKind.Parameter) {
//TODO(2016-02-24, yurig): if parameter is modified locally, we should warn
return false;
}
// if this is a local identifier, look at where it is defined
if(identifierInfo.Symbol != null && identifierInfo.Symbol.Kind == SymbolKind.Local) {
var declaration = identifierInfo.Symbol.DeclaringSyntaxReferences.FirstOrDefault();
// if the declaration is an equals expression, dive into it.
var equalsExpression = declaration?.GetSyntax()
.ChildNodes()
.FirstOrDefault(x => x.Kind() == SyntaxKind.EqualsValueClause);
var firstChild = equalsExpression?.ChildNodes().FirstOrDefault();
if(firstChild != null) {
return ShouldReportOnCollectionNode(semanticModel, firstChild);
}
// if the variable was assigned somewhere else, find it
var containingClass = declaration?.GetSyntax().FirstAncestorOrSelf<MethodDeclarationSyntax>();
var localAssignment = containingClass?.DescendantNodes().OfType<AssignmentExpressionSyntax>()
.Where(x => x.Left.IsKind(SyntaxKind.IdentifierName))
.LastOrDefault(x => (x.Left as IdentifierNameSyntax).Identifier.Text.Equals(((IdentifierNameSyntax)argument).Identifier.Text));
if(localAssignment != null) {
return ShouldReportOnCollectionNode(semanticModel, localAssignment.Right);
}
}
break;
case SyntaxKind.SimpleMemberAccessExpression:
// Assume that member accesses are returned materialized
return false;
}
return returnIfUnknown;
}
示例6: TrouveConditionsParametres
/// <summary>
/// Retourne les conditions sur les paramètres dans une listes d'expressions.
/// </summary>
/// <param name="expressions">Liste d'expressions.</param>
/// <param name="paramètres">Les paramètres du constructeur.</param>
/// <param name="modèleSémantique">Modèle sémantique.</param>
/// <returns>La liste d'assignations.</returns>
public static IEnumerable<IfStatementSyntax> TrouveConditionsParametres(SyntaxList<StatementSyntax> expressions, ParameterListSyntax paramètres, SemanticModel modèleSémantique) =>
expressions
.OfType<IfStatementSyntax>()
.Where(e =>
(e.Condition
?.DescendantNodes()?.OfType<IdentifierNameSyntax>()
?.Any(identifiant => modèleSémantique.GetSymbolInfo(identifiant).Symbol?.Kind == SymbolKind.Parameter)
?? false)
&& (e.Statement
?.DescendantNodes()?.OfType<IdentifierNameSyntax>()
?.All(identifiant => modèleSémantique.GetSymbolInfo(identifiant).Symbol?.Kind != SymbolKind.Field)
?? false));
示例7: GetActions
public IEnumerable<CodeAction> GetActions(Document document, SemanticModel model, SyntaxNode root, TextSpan span)
{
var token = root.FindToken(span.Start);
var lambdaExpression = token.GetAncestor<LambdaExpressionSyntax>();
if ((lambdaExpression != null) && (lambdaExpression.ArrowToken.FullSpan.Contains(span)))
{
if (ContainsLocalReferences(model, lambdaExpression, lambdaExpression.Body))
yield break;
var lambdaSymbol = model.GetSymbolInfo(lambdaExpression).Symbol as IMethodSymbol;
if (lambdaSymbol == null)
yield break;
bool noReturn = false;
BlockSyntax body;
if (lambdaExpression.Body is BlockSyntax)
{
body = SyntaxFactory.Block(((BlockSyntax)lambdaExpression.Body).Statements);
}
else
{
if (!(lambdaExpression.Body is ExpressionSyntax))
yield break;
body = SyntaxFactory.Block();
if ((lambdaSymbol.ReturnType == null) || lambdaSymbol.ReturnsVoid)
{
body = body.AddStatements(SyntaxFactory.ExpressionStatement((ExpressionSyntax)lambdaExpression.Body));
}
else
{
body = body.AddStatements(SyntaxFactory.ReturnStatement((ExpressionSyntax)lambdaExpression.Body));
}
}
var method = GetMethod(model, span, lambdaSymbol, body);
yield return GetAction(document, model, root, lambdaExpression, method);
}
// anonymous method
var anonymousMethod = token.GetAncestor<AnonymousMethodExpressionSyntax>();
if ((anonymousMethod != null) && anonymousMethod.DelegateKeyword.FullSpan.Contains(span))
{
if (ContainsLocalReferences(model, anonymousMethod, anonymousMethod.Body))
yield break;
var lambdaSymbol = model.GetSymbolInfo(anonymousMethod).Symbol as IMethodSymbol;
if (lambdaSymbol == null)
yield break;
var method = GetMethod(model, span, lambdaSymbol, SyntaxFactory.Block(((BlockSyntax)anonymousMethod.Body).Statements));
yield return GetAction(document, model, root, anonymousMethod, method);
}
}
开发者ID:ceddlyburge,项目名称:RefactoringEssentials,代码行数:52,代码来源:ExtractAnonymousMethodCodeRefactoringProvider.cs
示例8: ComputeReplacement
private static SyntaxNode ComputeReplacement(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
{
var memberAccess = node.Parent as MemberAccessExpressionSyntax;
if (memberAccess != null)
{
if (node == memberAccess.Name)
{
node = memberAccess;
}
}
var type = semanticModel.GetSymbolInfo(node, cancellationToken).Symbol as INamedTypeSymbol;
PredefinedTypeSyntax typeSyntax;
if (!PredefinedSpecialTypes.TryGetValue(type.SpecialType, out typeSyntax))
{
return node;
}
SyntaxNode newNode;
if (node is CrefSyntax)
{
newNode = SyntaxFactory.TypeCref(typeSyntax);
}
else
{
newNode = typeSyntax;
}
return newNode.WithTriviaFrom(node).WithoutFormatting();
}
示例9: GetMemberAccessExpressionFromAssignment
private static MemberAccessExpressionSyntax GetMemberAccessExpressionFromAssignment(SemanticModel semanticModel, AssignmentExpressionSyntax assignmentExpression, AssignmentExpressionSyntax nullLiteralAssignment)
{
if (assignmentExpression == null || nullLiteralAssignment == null
|| !assignmentExpression.IsKind(SyntaxKind.SimpleAssignmentExpression)
|| !assignmentExpression.IsKind(SyntaxKind.SimpleAssignmentExpression))
return null;
if (!nullLiteralAssignment.Right.IsKind(SyntaxKind.NullLiteralExpression)) return null;
if (!nullLiteralAssignment.Left.IsKind(SyntaxKind.IdentifierName)) return null;
if (!assignmentExpression.Left.IsKind(SyntaxKind.IdentifierName)) return null;
var assignmentIdentifier = semanticModel.GetSymbolInfo(assignmentExpression.Left);
var nullLiteralAssignmentIdentifier = semanticModel.GetSymbolInfo(nullLiteralAssignment.Left);
if ((assignmentIdentifier.Symbol ?? nullLiteralAssignmentIdentifier.Symbol) == null) return null;
if (!assignmentIdentifier.Equals(nullLiteralAssignmentIdentifier)) return null;
var memberAccessExpression = assignmentExpression.Right as MemberAccessExpressionSyntax;
return memberAccessExpression;
}
示例10: Applicable
public static bool Applicable(SemanticModel semanticModel, ArgumentSyntax argument, IEnumerable<ParameterSyntax> parameters)
{
var symbolInfo = semanticModel.GetSymbolInfo(argument.Expression);
var symbol = symbolInfo.Symbol;
if (symbol == null)
{
return true;
}
if (symbol.Kind != SymbolKind.Field &&
symbol.Kind != SymbolKind.Parameter &&
symbol.Kind != SymbolKind.Local)
{
return false;
}
var field = symbol as IFieldSymbol;
if (field != null)
{
return !field.IsReadOnly;
}
return true;
}
示例11: GetMissingEnumMembers
//--- Class Methods ---
public static IEnumerable<ISymbol> GetMissingEnumMembers(SwitchStatementSyntax switchNode, SemanticModel semanticModel, out IdentifierNameSyntax switchVariable)
{
// TODO (2016-02-25, steveb): what if the swich calls a function instead?
switchVariable = switchNode.Expression as IdentifierNameSyntax;
if(switchVariable == null) {
return Enumerable.Empty<ISymbol>();
}
var switchVariableTypeInfo = semanticModel.GetTypeInfo(switchVariable);
// check if we are switching over an enum
if((switchVariableTypeInfo.Type != null) && (switchVariableTypeInfo.Type.TypeKind == TypeKind.Enum)) {
// get all the enum values
var enumMembers = switchVariableTypeInfo.Type.GetMembers().Where(x => x.Kind == SymbolKind.Field).ToImmutableArray();
// get all case statements
var caseSwitchLabels = switchNode.Sections
.SelectMany(section => section.Labels)
.Select(label => label.DescendantNodes().OfType<MemberAccessExpressionSyntax>().FirstOrDefault())
.Where(memberAccess => memberAccess != null)
.Select(memberAccess => semanticModel.GetSymbolInfo(memberAccess).Symbol)
.ToImmutableHashSet();
// make sure we have all cases covered
return enumMembers.Where(x => !caseSwitchLabels.Contains(x)).ToImmutableArray();
}
return Enumerable.Empty<ISymbol>();
}
示例12: GenerateUsingDirectives
internal static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(
this SyntaxNode @this, SemanticModel model)
{
var namespacesForType = new SortedSet<string>();
foreach (var childNode in @this.DescendantNodes(_ => true))
{
var symbol = model.GetSymbolInfo(childNode).Symbol;
if (symbol != null && symbol.Kind != SymbolKind.Namespace &&
symbol.ContainingNamespace != null)
{
if ((symbol as ITypeSymbol)?.SpecialType ==
SpecialType.System_Void)
{
continue;
}
var containingNamespace = symbol.GetContainingNamespace();
if (!string.IsNullOrWhiteSpace(containingNamespace))
{
namespacesForType.Add(containingNamespace);
}
}
}
return SyntaxFactory.List(
namespacesForType.Select(_ => SyntaxFactory.UsingDirective(
SyntaxFactory.IdentifierName(_))));
}
示例13: TryGetTypes
protected bool TryGetTypes(
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;
}
示例14: CreateUsing
public static SyntaxNode CreateUsing(SyntaxNode root, ObjectCreationExpressionSyntax objectCreation, SemanticModel semanticModel)
{
SyntaxNode newRoot;
if (objectCreation.Parent.IsKind(SyntaxKind.SimpleAssignmentExpression))
{
var assignmentExpression = (AssignmentExpressionSyntax)objectCreation.Parent;
var statement = assignmentExpression.Parent as ExpressionStatementSyntax;
var identitySymbol = (ILocalSymbol)semanticModel.GetSymbolInfo(assignmentExpression.Left).Symbol;
newRoot = UsedOutsideParentBlock(semanticModel, statement, identitySymbol)
? CreateRootAddingDisposeToEndOfMethod(root, statement, identitySymbol)
: CreateRootWithUsing(root, statement, u => u.WithExpression(assignmentExpression));
}
else if (objectCreation.Parent.IsKind(SyntaxKind.EqualsValueClause) && objectCreation.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator))
{
var variableDeclarator = (VariableDeclaratorSyntax)objectCreation.Parent.Parent;
var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent;
var statement = (LocalDeclarationStatementSyntax)variableDeclaration.Parent;
newRoot = CreateRootWithUsing(root, statement, u => u.WithDeclaration(variableDeclaration));
}
else
{
newRoot = CreateRootWithUsing(root, (ExpressionStatementSyntax)objectCreation.Parent, u => u.WithExpression(objectCreation));
}
return newRoot;
}
示例15: IsDelegate
static bool IsDelegate(SemanticModel semanticModel, SyntaxNode node)
{
var info = semanticModel.GetSymbolInfo(node);
if (info.Symbol == null || info.Symbol.IsKind(SymbolKind.Event))
return false;
var type = info.Symbol.GetReturnType();
return type != null && type.TypeKind == TypeKind.Delegate;
}