本文整理汇总了C#中Microsoft.CodeAnalysis.SyntaxNode类的典型用法代码示例。如果您正苦于以下问题:C# SyntaxNode类的具体用法?C# SyntaxNode怎么用?C# SyntaxNode使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SyntaxNode类属于Microsoft.CodeAnalysis命名空间,在下文中一共展示了SyntaxNode类的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: MakeMock
private static async Task<Document> MakeMock(Document document, SyntaxNode invokationSyntax,
CancellationToken cancellationToken)
{
var testSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var testInitMethodDecl = TestSemanticHelper.GetTestInitializeMethod(testSemanticModel);
var declaredFields = testInitMethodDecl.Parent.ChildNodes().OfType<FieldDeclarationSyntax>().ToArray();
var suts = testInitMethodDecl.GetSuts(testSemanticModel, declaredFields);
var memberAccessExpressions = invokationSyntax.DescendantNodes()
.OfType<ExpressionSyntax>()
.Where(x => x is InvocationExpressionSyntax || x is MemberAccessExpressionSyntax)
.Select(expr =>
{
var memberAccess = expr as MemberAccessExpressionSyntax;
var invokationExpression = expr as InvocationExpressionSyntax;
var expression = invokationExpression == null ? memberAccess : invokationExpression.Expression;
return expression;
});
var invokedMethodsOfMocks = memberAccessExpressions.SelectMany(expressionSyntax => MocksAnalyzingEngine.GetInvokedMethodsOfMock(expressionSyntax, testSemanticModel, suts))
.DistinctBy(x => string.Join(",", x.FieldsToSetup.SelectMany(y => y.Field.Select(z => z))) + "," + x.MethodOrPropertySymbol)
.ToArray();
if (invokedMethodsOfMocks.Length == 0)
return document;
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
ChangesMaker.ApplyChanges(invokationSyntax, editor, invokedMethodsOfMocks);
return editor.GetChangedDocument();
}
示例3: UpdateMainDocument
private static Solution UpdateMainDocument(Document document, SyntaxNode root, MethodDeclarationSyntax method, IEnumerable<IGrouping<Document, ReferenceLocation>> documentGroups)
{
var mainDocGroup = documentGroups.FirstOrDefault(dg => dg.Key.Equals(document));
SyntaxNode newRoot;
if (mainDocGroup == null)
{
newRoot = root.ReplaceNode(method, method.AddModifiers(staticToken));
}
else
{
var diagnosticNodes = mainDocGroup.Select(referenceLocation => root.FindNode(referenceLocation.Location.SourceSpan)).ToList();
newRoot = root.TrackNodes(diagnosticNodes.Union(new[] { method }));
newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(method), method.AddModifiers(staticToken));
foreach (var diagnosticNode in diagnosticNodes)
{
var token = newRoot.FindToken(diagnosticNode.GetLocation().SourceSpan.Start);
var tokenParent = token.Parent;
if (token.Parent.IsKind(SyntaxKind.IdentifierName)) continue;
var invocationExpression = newRoot.GetCurrentNode(diagnosticNode).FirstAncestorOrSelfOfType<InvocationExpressionSyntax>()?.Expression;
if (invocationExpression == null || invocationExpression.IsKind(SyntaxKind.IdentifierName)) continue;
var memberAccess = invocationExpression as MemberAccessExpressionSyntax;
if (memberAccess == null) continue;
var newMemberAccessParent = memberAccess.Parent.ReplaceNode(memberAccess, memberAccess.Name)
.WithAdditionalAnnotations(Formatter.Annotation);
newRoot = newRoot.ReplaceNode(memberAccess.Parent, newMemberAccessParent);
}
}
var newSolution = document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newRoot);
return newSolution;
}
示例4: 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));
}
示例5: UseExpressionBodiedMemberAsync
private Task<Solution> UseExpressionBodiedMemberAsync(Document document, SyntaxNode root, SyntaxNode statement)
{
var returnStatement = (ReturnStatementSyntax) statement;
var expression = returnStatement.Expression;
var arrowClause = SyntaxFactory.ArrowExpressionClause(expression);
var property = statement.AncestorsAndSelf().OfType<PropertyDeclarationSyntax>().FirstOrDefault();
if (property != null)
{
var newProperty = property.RemoveNode(property.AccessorList, SyntaxRemoveOptions.KeepNoTrivia)
.WithExpressionBody(arrowClause)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
root = root.ReplaceNode(property, newProperty);
}
var method = statement.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().FirstOrDefault();
if (method != null)
{
root = root.ReplaceNode(method, method.RemoveNode(method.Body, SyntaxRemoveOptions.KeepNoTrivia)
.WithExpressionBody(arrowClause)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
}
return Task.FromResult(document.WithSyntaxRoot(root).Project.Solution);
}
示例6: IsNameableNode
private static bool IsNameableNode(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMemberDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.StructDeclaration:
return true;
case SyntaxKind.VariableDeclarator:
// Could be a regular field or an event field.
return node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>() != null;
default:
return false;
}
}
示例7: GetValidMembers
private IReadOnlyList<MemberDeclarationSyntax> GetValidMembers(SyntaxNode node)
{
return CSharpCodeModelService
.GetChildMemberNodes(node)
.Where(n => !n.IsKind(SyntaxKind.IncompleteMember))
.ToArray();
}
示例8: 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;
}
示例9: AddCodeFixWithNewPublicConstructor
private static void AddCodeFixWithNewPublicConstructor(CodeFixContext context, SyntaxNode root,
Diagnostic diagnostic, ClassDeclarationSyntax classNode)
{
// Generated from http://roslynquoter.azurewebsites.net/
var constructor = SyntaxFactory.ConstructorDeclaration(classNode.Identifier)
.WithModifiers(
SyntaxFactory.TokenList(
SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
.WithParameterList(SyntaxFactory.ParameterList()
.WithOpenParenToken(
SyntaxFactory.Token(SyntaxKind.OpenParenToken))
.WithCloseParenToken(
SyntaxFactory.Token(
SyntaxKind.CloseParenToken)))
.WithBody(SyntaxFactory.Block()
.WithOpenBraceToken(
SyntaxFactory.Token(
SyntaxKind.OpenBraceToken))
.WithCloseBraceToken(
SyntaxFactory.Token(
SyntaxKind.CloseBraceToken))).NormalizeWhitespace().WithAdditionalAnnotations(Formatter.Annotation);
var newClassNode = classNode.AddMembers(constructor);
var newRoot = root.ReplaceNode(classNode, newClassNode);
context.RegisterCodeFix(
CodeAction.Create(
CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription,
_ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)),
CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription), diagnostic);
}
示例10: AddWarningCommentIf
public static SyntaxNode AddWarningCommentIf(this SyntaxGenerator g, bool condition, SyntaxNode node)
{
if (condition)
return g.AddWarningComment(node);
else
return node;
}
示例11: Calculate
public IEnumerable<IHalsteadMetrics> Calculate(SyntaxNode root)
{
var analyzer = new HalsteadAnalyzer();
var childNodes = root.ChildNodes().AsArray();
var types = childNodes.Where(n => n.IsKind(SyntaxKind.ClassDeclaration) || n.IsKind(SyntaxKind.StructDeclaration))
.AsArray();
var methods = types.SelectMany(n => n.ChildNodes().Where(_isMethod));
var getProperties = types.SelectMany(n => n.ChildNodes().Where(IsGetProperty));
var setProperties = types.SelectMany(n => n.ChildNodes().Where(IsSetProperty));
var looseMethods = childNodes.Where(_isMethod);
var looseGetProperties = childNodes.Where(IsGetProperty);
var looseSetProperties = childNodes.Where(IsSetProperty);
var members = methods.Concat(getProperties)
.Concat(setProperties)
.Concat(looseMethods)
.Concat(looseGetProperties)
.Concat(looseSetProperties)
.AsArray();
if (members.Any())
{
return members.Select(analyzer.Calculate);
}
var statements = childNodes.Length == 0
? root.DescendantNodesAndTokens().Select(x => SyntaxFactory.ParseStatement(x.ToFullString(), 0, new CSharpParseOptions(kind: SourceCodeKind.Script, preprocessorSymbols: new string[0])))
: childNodes.Select(x => SyntaxFactory.ParseStatement(x.ToFullString(), 0, new CSharpParseOptions(kind: SourceCodeKind.Script, preprocessorSymbols: new string[0])));
var fakeMethod = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "fake")
.WithBody(SyntaxFactory.Block(statements));
return new[]
{
analyzer.Calculate(fakeMethod)
};
}
示例12: AddCodeFix
private static void AddCodeFix(CodeFixContext context, SyntaxNode root,
Diagnostic diagnostic, ClassDeclarationSyntax classNode)
{
var newRoot = IsBusinessObjectSerializableMakeSerializableCodeFix.AddAttribute(
root, classNode, IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SerializableName);
if (!root.HasUsing(IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SystemNamespace))
{
newRoot = (newRoot as CompilationUnitSyntax).AddUsings(
SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(
IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SystemNamespace)));
}
if (!root.HasUsing(IsBusinessObjectSerializableMakeSerializableCodeFixConstants.CslaSerializationNamespace))
{
newRoot = (newRoot as CompilationUnitSyntax).AddUsings(
SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(
IsBusinessObjectSerializableMakeSerializableCodeFixConstants.CslaSerializationNamespace)));
}
context.RegisterCodeFix(
CodeAction.Create(
IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSerializableAndUsingDescription,
_ => Task.FromResult<Document>(context.Document.WithSyntaxRoot(newRoot))), diagnostic);
}
示例13: CreateResult
private ITriviaSavedResult CreateResult(
SyntaxNode root,
Dictionary<TriviaLocation, SyntaxAnnotation> annotations,
Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> triviaList)
{
return new Result(root, _endOfLineKind, annotations, triviaList);
}
示例14: ReplaceTokens
private SyntaxNode ReplaceTokens(
SyntaxNode root,
IEnumerable<SyntaxToken> oldTokens,
Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken)
{
return root.ReplaceTokens(oldTokens, (o, n) => computeReplacementToken(o, n));
}
示例15: CreateCodeFix
private Document CreateCodeFix(Document document, Diagnostic diagnostic, SyntaxNode syntaxRoot)
{
SyntaxNode newSyntaxRoot = syntaxRoot;
var node = syntaxRoot.FindNode(diagnostic.Location.SourceSpan);
var indentationOptions = IndentationOptions.FromDocument(document);
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
newSyntaxRoot = this.RegisterBaseTypeDeclarationCodeFix(syntaxRoot, (BaseTypeDeclarationSyntax)node, indentationOptions);
break;
case SyntaxKind.AccessorList:
newSyntaxRoot = this.RegisterPropertyLikeDeclarationCodeFix(syntaxRoot, (BasePropertyDeclarationSyntax)node.Parent, indentationOptions);
break;
case SyntaxKind.Block:
newSyntaxRoot = this.RegisterMethodLikeDeclarationCodeFix(syntaxRoot, (BaseMethodDeclarationSyntax)node.Parent, indentationOptions);
break;
case SyntaxKind.NamespaceDeclaration:
newSyntaxRoot = this.RegisterNamespaceDeclarationCodeFix(syntaxRoot, (NamespaceDeclarationSyntax)node, indentationOptions);
break;
}
return document.WithSyntaxRoot(newSyntaxRoot);
}