本文整理汇总了C#中Microsoft.CodeAnalysis.SyntaxNode类的典型用法代码示例。如果您正苦于以下问题:C# SyntaxNode类的具体用法?C# SyntaxNode怎么用?C# SyntaxNode使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SyntaxNode类属于Microsoft.CodeAnalysis命名空间,在下文中一共展示了SyntaxNode类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
}
开发者ID:sushihangover,项目名称:monodevelop,代码行数:28,代码来源:CSharpImplementAbstractClassService.cs
示例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();
}
开发者ID:ycherkes,项目名称:MockIt,代码行数:35,代码来源:TestMethodCodeFixProvider.cs
示例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;
}
开发者ID:nagyistoce,项目名称:code-cracker,代码行数:30,代码来源:MakeMethodStaticCodeFixProvider.cs
示例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));
}
开发者ID:dbolkensteyn,项目名称:sonarlint-vs,代码行数:7,代码来源:FlagsEnumWithoutInitializerBase.cs
示例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);
}
开发者ID:nemec,项目名称:VSDiagnostics,代码行数:27,代码来源:SimplifyExpressionBodiedMemberCodeFix.cs
示例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;
}
}
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:29,代码来源:CSharpCodeModelService.cs
示例7: GetValidMembers
private IReadOnlyList<MemberDeclarationSyntax> GetValidMembers(SyntaxNode node)
{
return CSharpCodeModelService
.GetChildMemberNodes(node)
.Where(n => !n.IsKind(SyntaxKind.IncompleteMember))
.ToArray();
}
开发者ID:Rickinio,项目名称:roslyn,代码行数:7,代码来源:CSharpCodeModelService.CodeModelEventCollector.cs
示例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;
}
开发者ID:Rickinio,项目名称:roslyn,代码行数:26,代码来源:DeclarationComputer.cs
示例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);
}
开发者ID:JorgeArellano,项目名称:csla,代码行数:30,代码来源:CheckConstructorsAnalyzerPublicConstructorCodeFix.cs
示例10: AddWarningCommentIf
public static SyntaxNode AddWarningCommentIf(this SyntaxGenerator g, bool condition, SyntaxNode node)
{
if (condition)
return g.AddWarningComment(node);
else
return node;
}
开发者ID:modulexcite,项目名称:WcfClientProxyGenerator,代码行数:7,代码来源:LocalSyntaxGeneratorExtensions.cs
示例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)
};
}
开发者ID:henrylle,项目名称:ArchiMetrics,代码行数:35,代码来源:SyntaxMetricsCalculator.cs
示例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);
}
开发者ID:pombredanne,项目名称:csla,代码行数:25,代码来源:IsBusinessObjectSerializableMakeSerializableCodeFix.cs
示例13: CreateResult
private ITriviaSavedResult CreateResult(
SyntaxNode root,
Dictionary<TriviaLocation, SyntaxAnnotation> annotations,
Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> triviaList)
{
return new Result(root, _endOfLineKind, annotations, triviaList);
}
开发者ID:FreeBSD-DotNet,项目名称:monodevelop,代码行数:7,代码来源:AbstractSyntaxTriviaService.cs
示例14: ReplaceTokens
private SyntaxNode ReplaceTokens(
SyntaxNode root,
IEnumerable<SyntaxToken> oldTokens,
Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken)
{
return root.ReplaceTokens(oldTokens, (o, n) => computeReplacementToken(o, n));
}
开发者ID:FreeBSD-DotNet,项目名称:monodevelop,代码行数:7,代码来源:AbstractSyntaxTriviaService.cs
示例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);
}
开发者ID:JaRau,项目名称:StyleCopAnalyzers,代码行数:30,代码来源:SA1502CodeFixProvider.cs
示例16: AddNewModifier
SyntaxNode AddNewModifier(SyntaxNode node)
{
SyntaxToken newToken = SyntaxFactory.Token(SyntaxKind.NewKeyword);
switch (node.Kind())
{
//couldn't find a common base
case SyntaxKind.IndexerDeclaration:
var indexer = (IndexerDeclarationSyntax)node;
return indexer.AddModifiers(newToken);
case SyntaxKind.ClassDeclaration:
var classDecl = (ClassDeclarationSyntax)node;
return classDecl.AddModifiers(newToken);
case SyntaxKind.PropertyDeclaration:
var propDecl = (PropertyDeclarationSyntax)node;
return propDecl.AddModifiers(newToken);
case SyntaxKind.MethodDeclaration:
var methDecl = (MethodDeclarationSyntax)node;
return methDecl.AddModifiers(newToken);
case SyntaxKind.StructDeclaration:
var structDecl = (StructDeclarationSyntax)node;
return structDecl.AddModifiers(newToken);
case SyntaxKind.EnumDeclaration:
var enumDecl = (EnumDeclarationSyntax)node;
return enumDecl.AddModifiers(newToken);
case SyntaxKind.InterfaceDeclaration:
var intDecl = (InterfaceDeclarationSyntax)node;
return intDecl.AddModifiers(newToken);
case SyntaxKind.DelegateDeclaration:
var deleDecl = (DelegateDeclarationSyntax)node;
return deleDecl.AddModifiers(newToken);
default:
return node;
}
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:34,代码来源:CS0108UseNewKeywordIfHidingIntendedCodeFixProvider.cs
示例17: IsInitializer
private static bool IsInitializer(SyntaxNode node)
{
return node.IsKind(SyntaxKind.ArrayInitializerExpression) ||
node.IsKind(SyntaxKind.CollectionInitializerExpression) ||
node.IsKind(SyntaxKind.AnonymousObjectCreationExpression) ||
node.IsKind(SyntaxKind.ObjectInitializerExpression);
}
开发者ID:OsirisTerje,项目名称:sonarlint-vs,代码行数:7,代码来源:RightCurlyBraceStartsLine.cs
示例18: GetAsyncOrAwaitTokens
private static IEnumerable<SyntaxToken> GetAsyncOrAwaitTokens(SyntaxNode node)
{
return from token in node.DescendantTokens()
where token.IsKind(SyntaxKind.IdentifierToken) &&
AsyncOrAwait.Contains(token.ToString())
select token;
}
开发者ID:shrknt35,项目名称:sonarlint-vs,代码行数:7,代码来源:AsyncAwaitIdentifier.cs
示例19: AddNonSerializedAttribute
private async Task<Document> AddNonSerializedAttribute(Document document, SyntaxNode fieldNode, CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var attr = editor.Generator.Attribute(editor.Generator.TypeExpression(WellKnownTypes.NonSerializedAttribute(editor.SemanticModel.Compilation)));
editor.AddAttribute(fieldNode, attr);
return editor.GetChangedDocument();
}
开发者ID:GloryChou,项目名称:roslyn,代码行数:7,代码来源:MarkAllNonSerializableFields.Fixer.cs
示例20: CompareAttributes
private bool CompareAttributes(
AttributeSyntax oldAttribute,
AttributeSyntax newAttribute,
SyntaxNode newNodeParent,
CodeModelEventQueue eventQueue)
{
Debug.Assert(oldAttribute != null && newAttribute != null);
bool same = true;
if (!CompareNames(oldAttribute.Name, newAttribute.Name))
{
EnqueueChangeEvent(newAttribute, newNodeParent, CodeModelEventType.Rename, eventQueue);
same = false;
}
// If arguments have changed enqueue a element changed (arguments changed) node
if (!CompareAttributeArguments(oldAttribute.ArgumentList, newAttribute.ArgumentList))
{
EnqueueChangeEvent(newAttribute, newNodeParent, CodeModelEventType.ArgChange, eventQueue);
same = false;
}
return same;
}
开发者ID:Rickinio,项目名称:roslyn,代码行数:25,代码来源:CSharpCodeModelService.CodeModelEventCollector.cs
注:本文中的Microsoft.CodeAnalysis.SyntaxNode类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论