本文整理汇总了C#中SemanticModel类的典型用法代码示例。如果您正苦于以下问题:C# SemanticModel类的具体用法?C# SemanticModel怎么用?C# SemanticModel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SemanticModel类属于命名空间,在下文中一共展示了SemanticModel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Walker
public Walker(SemanticModel semanticModel, SemanticMap map, CancellationToken cancellationToken) :
base(SyntaxWalkerDepth.Token)
{
_semanticModel = semanticModel;
_map = map;
_cancellationToken = cancellationToken;
}
示例2: GetDelegateTypeConstructors
private IEnumerable<SignatureHelpItem> GetDelegateTypeConstructors(
ObjectCreationExpressionSyntax objectCreationExpression,
SemanticModel semanticModel,
ISymbolDisplayService symbolDisplayService,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
INamedTypeSymbol delegateType,
INamedTypeSymbol containingType,
CancellationToken cancellationToken)
{
var invokeMethod = delegateType.DelegateInvokeMethod;
if (invokeMethod == null)
{
return null;
}
var position = objectCreationExpression.SpanStart;
var item = CreateItem(
invokeMethod, semanticModel, position,
symbolDisplayService, anonymousTypeDisplayService,
isVariadic: false,
documentationFactory: null,
prefixParts: GetDelegateTypePreambleParts(invokeMethod, semanticModel, position),
separatorParts: GetSeparatorParts(),
suffixParts: GetDelegateTypePostambleParts(invokeMethod),
parameters: GetDelegateTypeParameters(invokeMethod, semanticModel, position, cancellationToken));
return SpecializedCollections.SingletonEnumerable(item);
}
开发者ID:daking2014,项目名称:roslyn,代码行数:28,代码来源:ObjectCreationExpressionSignatureHelpProvider_DelegateType.cs
示例3: 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);
}
示例4: 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;
}
示例5: AreSemanticallyEquivalent
public static bool AreSemanticallyEquivalent(
SemanticModel semanticModel1,
SemanticModel semanticModel2,
SyntaxNode node1,
SyntaxNode node2,
Func<SyntaxNode, bool> predicate = null)
{
// First check for syntactic equivalency. If two nodes aren't structurally equivalent,
// then they're not semantically equivalent.
if (node1 == null && node2 == null)
{
return true;
}
if (node1 == null || node2 == null)
{
return false;
}
if (!node1.IsEquivalentTo(node2, topLevel: false))
{
return false;
}
// From this point on we can assume the tree structure is the same. So no need to check
// kinds, child counts or token contents.
return AreSemanticallyEquivalentWorker(
semanticModel1, semanticModel2, node1, node2, predicate);
}
示例6: AddNonSerializedAttribute
private Task<Document> AddNonSerializedAttribute(Document document, SemanticModel model, SyntaxNode root, SyntaxNode fieldNode, SyntaxGenerator generator)
{
var attr = generator.Attribute(generator.TypeExpression(WellKnownTypes.NonSerializedAttribute(model.Compilation)));
var newNode = generator.AddAttributes(fieldNode, attr);
var newDocument = document.WithSyntaxRoot(root.ReplaceNode(fieldNode, newNode));
return Task.FromResult(newDocument);
}
示例7: TypeInferrer
internal TypeInferrer(
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
this.semanticModel = semanticModel;
this.cancellationToken = cancellationToken;
}
示例8: CheckStatement
private bool CheckStatement(SemanticModel semanticModel, StatementSyntax statement, CancellationToken cancellationToken)
{
if (statement is CheckedStatementSyntax ||
statement is DoStatementSyntax ||
statement is EmptyStatementSyntax ||
statement is ExpressionStatementSyntax ||
statement is FixedStatementSyntax ||
statement is ForEachStatementSyntax ||
statement is ForStatementSyntax ||
statement is IfStatementSyntax ||
statement is LocalDeclarationStatementSyntax ||
statement is LockStatementSyntax ||
statement is ReturnStatementSyntax ||
statement is SwitchStatementSyntax ||
statement is ThrowStatementSyntax ||
statement is TryStatementSyntax ||
statement is UnsafeStatementSyntax ||
statement is UsingStatementSyntax ||
statement is WhileStatementSyntax)
{
return true;
}
return false;
}
示例9: IsAcceptableOverload
protected static bool IsAcceptableOverload(IMethodSymbol methodSymbol, SemanticModel model)
{
var stringComparisonType = WellKnownTypes.StringComparison(model.Compilation);
return methodSymbol.IsStatic
? IsAcceptableStaticOverload(methodSymbol, stringComparisonType)
: IsAcceptableInstanceOverload(methodSymbol, stringComparisonType);
}
示例10: getProperty
/// <summary>
/// Checks if any property in the class given as parameter has a getter for the field we are moving.
/// </summary>
/// <param name="node">Syntax node of the class the field belongs to.</param>
/// <param name="semanticModel">Semantic model for the code we are processing.</param>
/// <returns></returns>
private PropertyDeclarationSyntax getProperty(ClassDeclarationSyntax node, SemanticModel semanticModel)
{
foreach (var p in node.Members.Where(m => m.Kind == SyntaxKind.PropertyDeclaration))
{
var property = p as PropertyDeclarationSyntax;
var accessors = property.AccessorList.Accessors;
var getter = accessors.FirstOrDefault(ad => ad.Kind == SyntaxKind.GetAccessorDeclaration);
var statements = getter.BodyOpt.Statements;
if (statements.Count != 0)
{
var returnStatement = statements.FirstOrDefault() as ReturnStatementSyntax;
if (returnStatement != null && returnStatement.ExpressionOpt != null)
{
var semanticInfo = document.GetSemanticModel().GetSemanticInfo(returnStatement.ExpressionOpt);
var fieldSymbol = semanticInfo.Symbol as FieldSymbol;
if (fieldSymbol != null && fieldSymbol == semanticModel.GetDeclaredSymbol(field))
{
return property;
}
}
}
}
return null;
}
示例11: GetAnonymousTypeParts
public override IEnumerable<SymbolDisplayPart> GetAnonymousTypeParts(
INamedTypeSymbol anonymousType, SemanticModel semanticModel, int position, ISymbolDisplayService displayService)
{
var members = new List<SymbolDisplayPart>();
members.Add(Keyword(SyntaxFacts.GetText(SyntaxKind.NewKeyword)));
members.AddRange(Space());
members.Add(Punctuation(SyntaxFacts.GetText(SyntaxKind.OpenBraceToken)));
members.AddRange(Space());
bool first = true;
foreach (var property in anonymousType.GetValidAnonymousTypeProperties())
{
if (!first)
{
members.Add(Punctuation(SyntaxFacts.GetText(SyntaxKind.CommaToken)));
members.AddRange(Space());
}
first = false;
members.AddRange(displayService.ToMinimalDisplayParts(semanticModel, position, property.Type).Select(p => p.MassageErrorTypeNames("?")));
members.AddRange(Space());
members.Add(new SymbolDisplayPart(SymbolDisplayPartKind.PropertyName, property, property.Name));
}
members.AddRange(Space());
members.Add(Punctuation(SyntaxFacts.GetText(SyntaxKind.CloseBraceToken)));
return members;
}
示例12: 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));
}
示例13: IsRequiredCastForReferenceEqualityComparison
private static bool IsRequiredCastForReferenceEqualityComparison(ITypeSymbol outerType, CastExpressionSyntax castExpression, SemanticModel semanticModel, out ExpressionSyntax other)
{
if (outerType.SpecialType == SpecialType.System_Object)
{
var expression = castExpression.WalkUpParentheses();
var parentNode = expression.Parent;
if (parentNode.IsKind(SyntaxKind.EqualsExpression) || parentNode.IsKind(SyntaxKind.NotEqualsExpression))
{
// Reference comparison.
var binaryExpression = (BinaryExpressionSyntax)parentNode;
other = binaryExpression.Left == expression ?
binaryExpression.Right :
binaryExpression.Left;
// Explicit cast not required if we are comparing with type parameter with a class constraint.
var otherType = semanticModel.GetTypeInfo(other).Type;
if (otherType != null && otherType.TypeKind != TypeKind.TypeParameter)
{
return !other.WalkDownParentheses().IsKind(SyntaxKind.CastExpression);
}
}
}
other = null;
return false;
}
示例14: AddNamespaceImportsAsync
private async Task<SyntaxNode> AddNamespaceImportsAsync(
Document document,
SemanticModel model,
OptionSet options,
IEnumerable<INamespaceSymbol> namespaces,
CancellationToken cancellationToken)
{
var existingNamespaces = new HashSet<INamespaceSymbol>();
await this.GetExistingImportedNamespacesAsync(document, model, existingNamespaces, cancellationToken).ConfigureAwait(false);
var namespacesToAdd = new HashSet<INamespaceSymbol>(namespaces);
namespacesToAdd.RemoveAll(existingNamespaces);
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
if (namespacesToAdd.Count == 0)
{
return root;
}
var gen = SyntaxGenerator.GetGenerator(document);
var newRoot = root;
foreach (var import in namespacesToAdd.Select(ns => gen.NamespaceImportDeclaration(ns.ToDisplayString()).WithAdditionalAnnotations(Simplifier.Annotation)))
{
newRoot = this.InsertNamespaceImport(newRoot, gen, import, options);
}
return newRoot;
}
示例15: TryClassifySymbol
private bool TryClassifySymbol(
NameSyntax name,
SymbolInfo symbolInfo,
SemanticModel semanticModel,
CancellationToken cancellationToken,
out IEnumerable<ClassifiedSpan> result)
{
if (symbolInfo.CandidateReason == CandidateReason.Ambiguous)
{
return TryClassifyAmbiguousSymbol(name, symbolInfo, semanticModel, cancellationToken, out result);
}
// Only classify if we get one good symbol back, or if it bound to a constructor symbol with
// overload resolution/accessibility errors, or bound to type/constructor and type wasn't creatable.
var symbol = TryGetSymbol(name, symbolInfo, semanticModel);
ClassifiedSpan classifiedSpan;
if (TryClassifySymbol(name, symbol, semanticModel, cancellationToken, out classifiedSpan))
{
result = SpecializedCollections.SingletonEnumerable(classifiedSpan);
return true;
}
result = null;
return false;
}