本文整理汇总了C#中SemanticModel.GetTypeInfo方法的典型用法代码示例。如果您正苦于以下问题:C# SemanticModel.GetTypeInfo方法的具体用法?C# SemanticModel.GetTypeInfo怎么用?C# SemanticModel.GetTypeInfo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SemanticModel
的用法示例。
在下文中一共展示了SemanticModel.GetTypeInfo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DetermineParameterType
public static ITypeSymbol DetermineParameterType(
this ArgumentSyntax argument,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
TypeInfo typeInfo;
if (argument.Expression.Kind() == SyntaxKind.DeclarationExpression)
{
var decl = (DeclarationExpressionSyntax)argument.Expression;
var component = decl.VariableComponent as TypedVariableComponentSyntax;
if (component == null) return semanticModel.Compilation.ObjectType;
typeInfo = semanticModel.GetTypeInfo(component.Type);
return typeInfo.Type?.IsErrorType() == false ? typeInfo.Type : semanticModel.Compilation.ObjectType;
}
// If a parameter appears to have a void return type, then just use 'object'
// instead.
typeInfo = semanticModel.GetTypeInfo(argument.Expression, cancellationToken);
if (typeInfo.Type != null && typeInfo.Type.SpecialType == SpecialType.System_Void)
{
return semanticModel.Compilation.ObjectType;
}
return semanticModel.GetType(argument.Expression, cancellationToken);
}
示例2: 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;
}
示例3: AnalyzeBinaryExpression
private static void AnalyzeBinaryExpression(BinaryExpressionSyntax node, SemanticModel model, Action<Diagnostic> addDiagnostic)
{
var leftType = model.GetTypeInfo(node.Left).Type;
var rightType = model.GetTypeInfo(node.Right).Type;
if (leftType != null && rightType != null && leftType.SpecialType == SpecialType.System_String && rightType.SpecialType == SpecialType.System_String)
{
addDiagnostic(node.OperatorToken.GetLocation().CreateDiagnostic(Rule));
}
}
示例4: 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;
}
示例5: IsTypeInferred
/// <summary>
/// Determines whether the specified TypeSyntax is actually 'var'.
/// </summary>
public static bool IsTypeInferred(this TypeSyntax typeSyntax, SemanticModel semanticModel)
{
if (!typeSyntax.IsVar)
{
return false;
}
if (semanticModel.GetAliasInfo(typeSyntax) != null)
{
return false;
}
var type = semanticModel.GetTypeInfo(typeSyntax).Type;
if (type == null)
{
return false;
}
if (type.Name == "var")
{
return false;
}
return true;
}
示例6: IsTypeApparentInDeclaration
/// <summary>
/// Returns true if type information could be gleaned by simply looking at the given statement.
/// This typically means that the type name occurs in right hand side of an assignment.
/// </summary>
private bool IsTypeApparentInDeclaration(VariableDeclarationSyntax variableDeclaration, SemanticModel semanticModel, TypeStylePreference stylePreferences, CancellationToken cancellationToken)
{
var initializer = variableDeclaration.Variables.Single().Initializer;
var initializerExpression = GetInitializerExpression(initializer);
var declaredTypeSymbol = semanticModel.GetTypeInfo(variableDeclaration.Type, cancellationToken).Type;
return TypeStyleHelper.IsTypeApparentInAssignmentExpression(stylePreferences, initializerExpression, semanticModel,cancellationToken, declaredTypeSymbol);
}
示例7: GetDiagnosticsForNode
protected void GetDiagnosticsForNode(SyntaxNode node, SemanticModel model, Action<Diagnostic> addDiagnostic)
{
var type = model.GetTypeInfo(node).Type;
if (type != null && TypeHasWeakIdentity(type, model))
{
addDiagnostic(node.CreateDiagnostic(Rule, type.ToDisplayString()));
}
}
示例8: TryGetExpressionType
protected static bool TryGetExpressionType(
SyntaxNode expression,
SemanticModel semanticModel,
out INamedTypeSymbol returnType)
{
var typeInfo = semanticModel.GetTypeInfo(expression);
returnType = typeInfo.Type as INamedTypeSymbol;
return returnType != null;
}
示例9: GetMethodGroupItems
private IEnumerable<SignatureHelpItem> GetMethodGroupItems(
InvocationExpressionSyntax invocationExpression,
SemanticModel semanticModel,
ISymbolDisplayService symbolDisplayService,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
IDocumentationCommentFormattingService documentationCommentFormattingService,
ISymbol within,
IEnumerable<IMethodSymbol> methodGroup,
CancellationToken cancellationToken)
{
ITypeSymbol throughType = null;
if (invocationExpression.Expression is MemberAccessExpressionSyntax)
{
var throughExpression = ((MemberAccessExpressionSyntax)invocationExpression.Expression).Expression;
var throughSymbol = semanticModel.GetSymbolInfo(throughExpression, cancellationToken).GetAnySymbol();
// if it is via a base expression "base.", we know the "throughType" is the base class but
// we need to be able to tell between "base.M()" and "new Base().M()".
// currently, Access check methods do not differentiate between them.
// so handle "base." primary-expression here by nulling out "throughType"
if (!(throughExpression is BaseExpressionSyntax))
{
throughType = semanticModel.GetTypeInfo(throughExpression, cancellationToken).Type;
}
var includeInstance = !throughExpression.IsKind(SyntaxKind.IdentifierName) ||
semanticModel.LookupSymbols(throughExpression.SpanStart, name: throughSymbol.Name).Any(s => !(s is INamedTypeSymbol)) ||
(!(throughSymbol is INamespaceOrTypeSymbol) && semanticModel.LookupSymbols(throughExpression.SpanStart, container: throughSymbol.ContainingType).Any(s => !(s is INamedTypeSymbol)));
var includeStatic = throughSymbol is INamedTypeSymbol ||
(throughExpression.IsKind(SyntaxKind.IdentifierName) &&
semanticModel.LookupNamespacesAndTypes(throughExpression.SpanStart, name: throughSymbol.Name).Any(t => t.GetSymbolType() == throughType));
Contract.ThrowIfFalse(includeInstance || includeStatic);
methodGroup = methodGroup.Where(m => (m.IsStatic && includeStatic) || (!m.IsStatic && includeInstance));
}
else if (invocationExpression.Expression is SimpleNameSyntax &&
invocationExpression.IsInStaticContext())
{
methodGroup = methodGroup.Where(m => m.IsStatic);
}
var accessibleMethods = methodGroup.Where(m => m.IsAccessibleWithin(within, throughTypeOpt: throughType)).ToList();
if (accessibleMethods.Count == 0)
{
return null;
}
var methodSet = accessibleMethods.ToSet();
accessibleMethods = accessibleMethods.Where(m => !IsHiddenByOtherMethod(m, methodSet)).ToList();
return accessibleMethods.Select(m =>
ConvertMethodGroupMethod(m, invocationExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, cancellationToken));
}
示例10: TryDetermineReturnType
public override bool TryDetermineReturnType(SyntaxToken startToken, SemanticModel semanticModel, CancellationToken cancellationToken, out ITypeSymbol returnType, out SyntaxToken nextToken)
{
nextToken = startToken;
returnType = null;
if (startToken.Parent is TypeSyntax)
{
var typeSyntax = (TypeSyntax)startToken.Parent;
// 'partial' is actually an identifier. If we see it just bail. This does mean
// we won't handle overrides that actually return a type called 'partial'. And
// not a single tear was shed.
if (typeSyntax is IdentifierNameSyntax &&
((IdentifierNameSyntax)typeSyntax).Identifier.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword))
{
return false;
}
returnType = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type;
nextToken = typeSyntax.GetFirstToken().GetPreviousToken();
}
return true;
}
示例11: ClassifyUsingDirectiveSyntax
private IEnumerable<ClassifiedSpan> ClassifyUsingDirectiveSyntax(
UsingDirectiveSyntax usingDirective,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// For using aliases, we bind the target on the right of the equals and use that
// binding to classify the alias.
if (usingDirective.Alias != null)
{
var info = semanticModel.GetTypeInfo(usingDirective.Name, cancellationToken);
if (info.Type != null)
{
var classification = GetClassificationForType(info.Type);
if (classification != null)
{
var token = usingDirective.Alias.Name;
return SpecializedCollections.SingletonEnumerable(new ClassifiedSpan(token.Span, classification));
}
}
}
return null;
}
示例12: VerifySpeculativeSemanticModelForMethodBody
private static void VerifySpeculativeSemanticModelForMethodBody(BlockSyntax blockStatement, SemanticModel speculativeModel)
{
var localDecl = (LocalDeclarationStatementSyntax)blockStatement.Statements[0];
var declarator = localDecl.Declaration.Variables.First();
var local = speculativeModel.GetDeclaredSymbol(declarator);
Assert.NotNull(local);
Assert.Equal("z", local.Name);
Assert.Equal(SymbolKind.Local, local.Kind);
Assert.Equal("Int32", ((LocalSymbol)local).Type.Name);
var typeInfo = speculativeModel.GetTypeInfo(localDecl.Declaration.Type);
Assert.NotNull(typeInfo.Type);
Assert.Equal("Int32", typeInfo.Type.Name);
var call = (InvocationExpressionSyntax)((ExpressionStatementSyntax)blockStatement.Statements[1]).Expression;
var arg = call.ArgumentList.Arguments[0].Expression;
var info = speculativeModel.GetSymbolInfo(arg);
Assert.NotNull(info.Symbol);
Assert.Equal("z", info.Symbol.Name);
Assert.Equal(SymbolKind.Local, info.Symbol.Kind);
// Shouldn't bind to local y in the original method as we are replacing the method body.
var call2 = (InvocationExpressionSyntax)((ExpressionStatementSyntax)((BlockSyntax)blockStatement).Statements[2]).Expression;
var arg2 = call2.ArgumentList.Arguments[0].Expression;
var info2 = speculativeModel.GetSymbolInfo(arg2);
Assert.Null(info2.Symbol);
}
示例13: VerifyModelForOutVar
private static void VerifyModelForOutVar(
SemanticModel model,
DeclarationExpressionSyntax decl,
bool isDelegateCreation,
bool isExecutableCode,
bool isShadowed,
bool verifyDataFlow = true,
params IdentifierNameSyntax[] references)
{
var variableDeclaratorSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDeclaratorSyntax);
Assert.NotNull(symbol);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(variableDeclaratorSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(LocalDeclarationKind.RegularVariable, ((LocalSymbol)symbol).DeclarationKind);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax));
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));
var local = (SourceLocalSymbol)symbol;
var typeSyntax = decl.Type();
Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax));
Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax));
if (typeSyntax.IsVar && local.IsVar && local.Type.IsErrorType())
{
Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol);
}
else
{
Assert.Equal(local.Type, model.GetSymbolInfo(typeSyntax).Symbol);
}
Assert.Same(symbol, model.GetSymbolInfo(decl).Symbol);
Assert.Equal(local.Type, model.GetTypeInfo(decl).Type);
Assert.Null(model.GetDeclaredSymbol(decl));
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));
Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
}
if (verifyDataFlow)
{
VerifyDataFlow(model, decl, isDelegateCreation, isExecutableCode, references, symbol);
}
}
示例14: VerifyModelNotSupported
private static void VerifyModelNotSupported(SemanticModel model, params IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
Assert.Null(model.GetSymbolInfo(reference).Symbol);
Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any());
Assert.DoesNotContain(reference.Identifier.ValueText, model.LookupNames(reference.SpanStart));
Assert.True(((TypeSymbol)model.GetTypeInfo(reference).Type).IsErrorType());
}
}
示例15: VerifyModelForOutField
private static void VerifyModelForOutField(
SemanticModel model,
DeclarationExpressionSyntax decl,
bool duplicate,
params IdentifierNameSyntax[] references)
{
var variableDesignationSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDesignationSyntax);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(SymbolKind.Field, symbol.Kind);
Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax));
var symbols = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText);
var names = model.LookupNames(decl.SpanStart);
if (duplicate)
{
Assert.True(symbols.Count() > 1);
Assert.Contains(symbol, symbols);
}
else
{
Assert.Same(symbol, symbols.Single());
}
Assert.Contains(decl.Identifier().ValueText, names);
var local = (FieldSymbol)symbol;
var typeSyntax = decl.Type();
Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax));
Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax));
if (typeSyntax.IsVar && local.Type.IsErrorType())
{
Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol);
}
else
{
Assert.Equal(local.Type, model.GetSymbolInfo(typeSyntax).Symbol);
}
var declarator = decl.Ancestors().OfType<VariableDeclaratorSyntax>().FirstOrDefault();
var inFieldDeclaratorArgumentlist = declarator != null && declarator.Parent.Parent.Kind() != SyntaxKind.LocalDeclarationStatement &&
(declarator.ArgumentList?.Contains(decl)).GetValueOrDefault();
if (inFieldDeclaratorArgumentlist)
{
Assert.Null(model.GetSymbolInfo(decl).Symbol);
Assert.Null(model.GetSymbolInfo(decl).Symbol);
}
else
{
Assert.Same(symbol, model.GetSymbolInfo(decl).Symbol);
Assert.Same(symbol, model.GetSymbolInfo(decl).Symbol);
}
Assert.Null(model.GetDeclaredSymbol(decl));
foreach (var reference in references)
{
var referenceInfo = model.GetSymbolInfo(reference);
symbols = model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText);
if (duplicate)
{
Assert.Null(referenceInfo.Symbol);
Assert.Contains(symbol, referenceInfo.CandidateSymbols);
Assert.True(symbols.Count() > 1);
Assert.Contains(symbol, symbols);
}
else
{
Assert.Same(symbol, referenceInfo.Symbol);
Assert.Same(symbol, symbols.Single());
Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
}
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText));
}
if (!inFieldDeclaratorArgumentlist)
{
var dataFlowParent = (ExpressionSyntax)decl.Parent.Parent.Parent;
if (model.IsSpeculativeSemanticModel)
{
Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent));
}
else
{
var dataFlow = model.AnalyzeDataFlow(dataFlowParent);
if (dataFlow.Succeeded)
{
Assert.False(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance));
//.........这里部分代码省略.........