本文整理汇总了C#中SyntaxNode类的典型用法代码示例。如果您正苦于以下问题:C# SyntaxNode类的具体用法?C# SyntaxNode怎么用?C# SyntaxNode使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SyntaxNode类属于命名空间,在下文中一共展示了SyntaxNode类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: GetContainingMember
private static SyntaxNode GetContainingMember(SyntaxNode oldNode)
{
foreach (var node in oldNode.Ancestors())
{
switch (node.Kind())
{
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
if ((node as AnonymousFunctionExpressionSyntax)?.AsyncKeyword.Kind() != SyntaxKind.AsyncKeyword)
{
return node;
}
break;
case SyntaxKind.MethodDeclaration:
if ((node as MethodDeclarationSyntax)?.Modifiers.Any(SyntaxKind.AsyncKeyword) == false)
{
return node;
}
break;
default:
continue;
}
}
return null;
}
开发者ID:RoryVL,项目名称:roslyn,代码行数:27,代码来源:CSharpAddAsyncCodeFixProvider.cs
示例2: GetOutsideTypeQualifiedName
private string GetOutsideTypeQualifiedName(SyntaxNode node)
{
// Get the name space name enclosing this node.
string namespaceName = node.AncestorsAndSelf().
// ancestors whose kind is name space node.
Where(n => n.Kind == SyntaxKind.NamespaceDeclaration).
// conver to the syntax and get the name.
Select(n => (NamespaceDeclarationSyntax)n).First().Name.PlainName;
// Get the class name enclosing this node.
var classesNames = node.AncestorsAndSelf().
// ancestors whose kind is class node.
Where(n => n.Kind == SyntaxKind.ClassDeclaration).
// convert each one to the kind class node syntax.
Select(n => (ClassDeclarationSyntax)n).
// order all the class decs by their length, in decending order.
OrderByDescending(n => n.Span.Length).
// select their names.
Select(n => n.Identifier.ValueText);
// Combine all the names to get the scope string.
var qualifiedName = namespaceName + "." + StringUtil.ConcatenateAll(".", classesNames);
logger.Info(qualifiedName);
return qualifiedName;
}
开发者ID:nkcsgexi,项目名称:ghostfactor1,代码行数:25,代码来源:QualifiedNameAnalyzer.cs
示例3: PathSyntaxReference
public PathSyntaxReference(SyntaxNode node)
{
_tree = node.SyntaxTree;
_kind = node.Kind();
_textSpan = node.Span;
_pathFromRoot = ComputePathFromRoot(node);
}
开发者ID:Rickinio,项目名称:roslyn,代码行数:7,代码来源:CSharpSyntaxTreeFactory.PathSyntaxReference.cs
示例4: GetCurrentArgumentState
public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken)
{
if (GetOuterMostTupleExpressionInSpan(root, position, syntaxFacts, currentSpan, cancellationToken, out var expression))
{
return CommonSignatureHelpUtilities.GetSignatureHelpState(expression, position,
getOpenToken: s_getOpenToken,
getCloseToken: s_getCloseToken,
getArgumentsWithSeparators: s_getArgumentsWithSeparators,
getArgumentNames: s_getArgumentNames);
}
if (GetOuterMostParenthesizedExpressionInSpan(root, position, syntaxFacts, currentSpan, cancellationToken, out var parenthesizedExpression))
{
if (currentSpan.Start == parenthesizedExpression.SpanStart)
{
return new SignatureHelpState(
argumentIndex: 0,
argumentCount: 0,
argumentName: string.Empty,
argumentNames: null);
}
}
return null;
}
开发者ID:XieShuquan,项目名称:roslyn,代码行数:25,代码来源:TupleConstructionSignatureHelpProvider.cs
示例5: AddEdits
private void AddEdits(
SyntaxNode root,
SyntaxEditor editor,
Diagnostic diagnostic,
CancellationToken cancellationToken)
{
var localDeclarationLocation = diagnostic.AdditionalLocations[0];
var ifStatementLocation = diagnostic.AdditionalLocations[1];
var conditionLocation = diagnostic.AdditionalLocations[2];
var asExpressionLocation = diagnostic.AdditionalLocations[3];
var localDeclaration = (LocalDeclarationStatementSyntax)localDeclarationLocation.FindNode(cancellationToken);
var ifStatement = (IfStatementSyntax)ifStatementLocation.FindNode(cancellationToken);
var condition = (BinaryExpressionSyntax)conditionLocation.FindNode(cancellationToken);
var asExpression = (BinaryExpressionSyntax)asExpressionLocation.FindNode(cancellationToken);
var updatedCondition = SyntaxFactory.IsPatternExpression(
asExpression.Left, SyntaxFactory.DeclarationPattern(
((TypeSyntax)asExpression.Right).WithoutTrivia(),
localDeclaration.Declaration.Variables[0].Identifier.WithoutTrivia()));
var trivia = localDeclaration.GetLeadingTrivia().Concat(localDeclaration.GetTrailingTrivia())
.Where(t => t.IsSingleOrMultiLineComment())
.SelectMany(t => ImmutableArray.Create(t, SyntaxFactory.ElasticCarriageReturnLineFeed))
.ToImmutableArray();
var updatedIfStatement = ifStatement.ReplaceNode(condition, updatedCondition)
.WithPrependedLeadingTrivia(trivia)
.WithAdditionalAnnotations(Formatter.Annotation);
editor.RemoveNode(localDeclaration);
editor.ReplaceNode(ifStatement, updatedIfStatement);
}
开发者ID:otawfik-ms,项目名称:roslyn,代码行数:33,代码来源:CSharpAsAndNullCheckCodeFixProvider.cs
示例6: OnCodeBlockStarted
public ICodeBlockEndedAnalyzer OnCodeBlockStarted(SyntaxNode codeBlock, ISymbol ownerSymbol, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
{
var methodSymbol = ownerSymbol as IMethodSymbol;
if (methodSymbol == null ||
methodSymbol.ReturnsVoid ||
methodSymbol.ReturnType.Kind == SymbolKind.ArrayType ||
methodSymbol.Parameters.Length > 0 ||
!(methodSymbol.DeclaredAccessibility == Accessibility.Public || methodSymbol.DeclaredAccessibility == Accessibility.Protected) ||
methodSymbol.IsAccessorMethod() ||
!IsPropertyLikeName(methodSymbol.Name))
{
return null;
}
// Fxcop has a few additional checks to reduce the noise for this diagnostic:
// Ensure that the method is non-generic, non-virtual/override, has no overloads and doesn't have special names: 'GetHashCode' or 'GetEnumerator'.
// Also avoid generating this diagnostic if the method body has any invocation expressions.
if (methodSymbol.IsGenericMethod ||
methodSymbol.IsVirtual ||
methodSymbol.IsOverride ||
methodSymbol.ContainingType.GetMembers(methodSymbol.Name).Length > 1 ||
methodSymbol.Name == GetHashCodeName ||
methodSymbol.Name == GetEnumeratorName)
{
return null;
}
return GetCodeBlockEndedAnalyzer();
}
开发者ID:pheede,项目名称:roslyn,代码行数:30,代码来源:CA1024DiagnosticAnalyzer.cs
示例7: DefaultVisit
public override void DefaultVisit(SyntaxNode node)
{
foreach (var child in node.ChildNodes())
{
child.Accept(this);
}
}
开发者ID:modulexcite,项目名称:CSharpSyntax,代码行数:7,代码来源:SyntaxWalker.cs
示例8: State
private State(SyntaxNode node, INamedTypeSymbol classType, INamedTypeSymbol abstractClassType, IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers)
{
this.Location = node;
this.ClassType = classType;
this.AbstractClassType = abstractClassType;
this.UnimplementedMembers = unimplementedMembers;
}
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:7,代码来源:AbstractImplementAbstractClassService.State.cs
示例9: PathSyntaxReference
public PathSyntaxReference(SyntaxNode node)
{
this.tree = node.SyntaxTree;
this.kind = node.CSharpKind();
this.textSpan = node.Span;
this.pathFromRoot = ComputePathFromRoot(node);
}
开发者ID:EkardNT,项目名称:Roslyn,代码行数:7,代码来源:CSharpSyntaxTreeFactory.PathSyntaxReference.cs
示例10: GetNewNode
private SyntaxNode GetNewNode(Document document, SyntaxNode node, CancellationToken cancellationToken)
{
SyntaxNode newNode = null;
var propertyStatement = node as PropertyDeclarationSyntax;
if (propertyStatement != null)
{
newNode = propertyStatement.AddModifiers(SyntaxFactory.Token(SyntaxKind.NewKeyword)) as SyntaxNode;
}
var methodStatement = node as MethodDeclarationSyntax;
if (methodStatement != null)
{
newNode = methodStatement.AddModifiers(SyntaxFactory.Token(SyntaxKind.NewKeyword));
}
var fieldDeclaration = node as FieldDeclarationSyntax;
if (fieldDeclaration != null)
{
newNode = fieldDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.NewKeyword));
}
//Make sure we preserve any trivia from the original node
newNode = newNode.WithTriviaFrom(node);
return newNode.WithAdditionalAnnotations(Formatter.Annotation);
}
开发者ID:RoryVL,项目名称:roslyn,代码行数:27,代码来源:HideBaseCodeFixProvider.AddNewKeywordAction.cs
示例11: AddOrAccess
public void AddOrAccess(SyntaxNode instance, IWeakAction<SyntaxNode> evictor)
{
if (!trees.ContainsKey(instance))
{
trees[instance] = evictor;
}
}
开发者ID:riversky,项目名称:roslyn,代码行数:7,代码来源:TestSyntaxTreeCacheService.cs
示例12: RenameThenRemoveAsyncTokenAsync
private async Task<Solution> RenameThenRemoveAsyncTokenAsync(Document document, SyntaxNode node, IMethodSymbol methodSymbol, CancellationToken cancellationToken)
{
var name = methodSymbol.Name;
var newName = name.Substring(0, name.Length - AsyncSuffix.Length);
var solution = document.Project.Solution;
var options = solution.Workspace.Options;
// Store the path to this node. That way we can find it post rename.
var syntaxPath = new SyntaxPath(node);
// Rename the method to remove the 'Async' suffix, then remove the 'async' keyword.
var newSolution = await Renamer.RenameSymbolAsync(solution, methodSymbol, newName, options, cancellationToken).ConfigureAwait(false);
var newDocument = newSolution.GetDocument(document.Id);
var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
SyntaxNode newNode;
if (syntaxPath.TryResolve<SyntaxNode>(newRoot, out newNode))
{
var semanticModel = await newDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var newMethod = (IMethodSymbol)semanticModel.GetDeclaredSymbol(newNode, cancellationToken);
return await RemoveAsyncTokenAsync(newDocument, newMethod, newNode, cancellationToken).ConfigureAwait(false);
}
return newSolution;
}
开发者ID:rgani,项目名称:roslyn,代码行数:25,代码来源:AbstractMakeMethodSynchronousCodeFixProvider.cs
示例13: SourceLocationWithAssociatedNode
// This constructor can be used to have the span and associated node be arbitrarily different.
public SourceLocationWithAssociatedNode(SyntaxTree syntaxTree, TextSpan span, SyntaxNode associatedNode, bool associateInParent)
: base(syntaxTree, span)
{
Debug.Assert(associatedNode != null); //if it's null, construct a SourceLocation instead
this.associatedNode = new WeakReference<SyntaxNode>(associatedNode);
this.associateInParent = associateInParent;
}
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:8,代码来源:SourceLocationWithAssociatedNode.cs
示例14: FindPartner
public static SyntaxNode FindPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode)
{
// Finding a partner of a zero-width node is complicated and not supported atm:
Debug.Assert(leftNode.FullSpan.Length > 0);
Debug.Assert(leftNode.SyntaxTree == leftRoot.SyntaxTree);
SyntaxNode originalLeftNode = leftNode;
int leftPosition = leftNode.SpanStart;
leftNode = leftRoot;
SyntaxNode rightNode = rightRoot;
while (leftNode != originalLeftNode)
{
Debug.Assert(leftNode.RawKind == rightNode.RawKind);
var leftChild = leftNode.ChildThatContainsPosition(leftPosition, out var childIndex);
// Can only happen when searching for zero-width node.
Debug.Assert(!leftChild.IsToken);
rightNode = rightNode.ChildNodesAndTokens()[childIndex].AsNode();
leftNode = leftChild.AsNode();
}
return rightNode;
}
开发者ID:XieShuquan,项目名称:roslyn,代码行数:25,代码来源:SyntaxUtilities.cs
示例15: AddFix
private void AddFix(string codeFixTitle, CodeFixContext context, SyntaxNode root, SyntaxNode classDecl, SyntaxGenerator generator, params string[] languages)
{
var fix = new MyCodeAction(
codeFixTitle,
c => GetFix(context.Document, root, classDecl, generator, languages));
context.RegisterCodeFix(fix, context.Diagnostics);
}
开发者ID:GloryChou,项目名称:roslyn,代码行数:7,代码来源:ApplyDiagnosticAnalyzerAttributeFix.cs
示例16: Statement
/// <summary>
/// Constructor.
/// </summary>
/// <param name="syntaxNode">SyntaxNode</param>
/// <param name="node">IControlFlowNode</param>
/// <param name="summary">MethodSummary</param>
private Statement(SyntaxNode syntaxNode, IControlFlowNode node,
MethodSummary summary)
{
this.SyntaxNode = syntaxNode;
this.ControlFlowNode = node;
this.Summary = summary;
}
开发者ID:yonglehou,项目名称:PSharp,代码行数:13,代码来源:Statement.cs
示例17: DefaultVisit
public override void DefaultVisit(SyntaxNode node)
{
foreach (var child in node.ChildNodes())
{
Visit(child);
}
}
开发者ID:Rickinio,项目名称:roslyn,代码行数:7,代码来源:LabelConflictVisitor.cs
示例18: GetFixesAsync
internal override Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, CancellationToken cancellationToken)
{
var actions = ImmutableArray.CreateBuilder<CodeAction>();
// Fix 1: Add a NonSerialized attribute to the field
var fieldNode = GetFieldDeclarationNode(nodeToFix);
if (fieldNode != null)
{
var generator = SyntaxGenerator.GetGenerator(document);
var codeAction = new MyDocumentCodeAction(FxCopFixersResources.AddNonSerializedAttribute,
async ct => await AddNonSerializedAttribute(document, model, root, fieldNode, generator).ConfigureAwait(false));
actions.Add(codeAction);
// Fix 2: If the type of the field is defined in source, then add the serializable attribute to the type.
var fieldSymbol = model.GetDeclaredSymbol(nodeToFix, cancellationToken) as IFieldSymbol;
var type = fieldSymbol.Type;
if (type.Locations.Any(l => l.IsInSource))
{
var typeCodeAction = new MySolutionCodeAction(FxCopFixersResources.AddSerializableAttribute,
async ct => await AddSerializableAttributeToType(document, model, generator, type, cancellationToken).ConfigureAwait(false));
actions.Add(typeCodeAction);
}
}
return Task.FromResult<IEnumerable<CodeAction>>(actions.ToImmutable());
}
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:27,代码来源:CA2235CodeFixProviderBase.cs
示例19: BindGlobalDeclaration
private BoundNode BindGlobalDeclaration(SyntaxNode declaration, Symbol parent)
{
switch (declaration.Kind)
{
case SyntaxKind.VariableDeclarationStatement:
return BindVariableDeclarationStatement((VariableDeclarationStatementSyntax) declaration, parent);
case SyntaxKind.FunctionDeclaration:
return BindFunctionDeclaration((FunctionDeclarationSyntax) declaration, parent);
case SyntaxKind.FunctionDefinition:
return BindFunctionDefinition((FunctionDefinitionSyntax) declaration, parent);
case SyntaxKind.ConstantBufferDeclaration:
return BindConstantBufferDeclaration((ConstantBufferSyntax) declaration);
case SyntaxKind.TypeDeclarationStatement:
return BindTypeDeclaration((TypeDeclarationStatementSyntax) declaration, parent);
case SyntaxKind.Namespace:
return BindNamespace((NamespaceSyntax) declaration);
case SyntaxKind.TechniqueDeclaration:
return BindTechniqueDeclaration((TechniqueSyntax) declaration);
case SyntaxKind.TypedefStatement:
return BindTypedefStatement((TypedefStatementSyntax) declaration);
case SyntaxKind.EmptyStatement:
return BindEmptyStatement((EmptyStatementSyntax) declaration);
default:
throw new ArgumentOutOfRangeException(declaration.Kind.ToString());
}
}
开发者ID:tgjones,项目名称:HlslTools,代码行数:26,代码来源:Binder.Declarations.cs
示例20: 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);
}
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:7,代码来源:CA2235CodeFixProviderBase.cs
注:本文中的SyntaxNode类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论