-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
SyntaxNode.cs
1548 lines (1350 loc) · 61 KB
/
SyntaxNode.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
#pragma warning disable CA1200 // Avoid using cref tags with a prefix
/// <summary>
/// Represents a non-terminal node in the syntax tree. This is the language agnostic equivalent of <see
/// cref="T:Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode"/> and <see cref="T:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode"/>.
/// </summary>
#pragma warning restore CA1200 // Avoid using cref tags with a prefix
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
public abstract partial class SyntaxNode
{
private readonly SyntaxNode? _parent;
internal SyntaxTree? _syntaxTree;
internal SyntaxNode(GreenNode green, SyntaxNode? parent, int position)
{
RoslynDebug.Assert(position >= 0, "position cannot be negative");
RoslynDebug.Assert(parent?.Green.IsList != true, "list cannot be a parent");
Position = position;
Green = green;
_parent = parent;
}
/// <summary>
/// Used by structured trivia which has "parent == null", and therefore must know its
/// SyntaxTree explicitly when created.
/// </summary>
internal SyntaxNode(GreenNode green, int position, SyntaxTree syntaxTree)
: this(green, null, position)
{
this._syntaxTree = syntaxTree;
}
private string GetDebuggerDisplay()
{
return GetType().Name + " " + KindText + " " + ToString();
}
/// <summary>
/// An integer representing the language specific kind of this node.
/// </summary>
public int RawKind => Green.RawKind;
protected string KindText => Green.KindText;
/// <summary>
/// The language name that this node is syntax of.
/// </summary>
public abstract string Language { get; }
internal GreenNode Green { get; }
internal int Position { get; }
internal int EndPosition => Position + Green.FullWidth;
/// <summary>
/// Returns SyntaxTree that owns the node or null if node does not belong to a
/// SyntaxTree
/// </summary>
public SyntaxTree SyntaxTree => this.SyntaxTreeCore;
internal bool IsList => this.Green.IsList;
/// <summary>
/// The absolute span of this node in characters, including its leading and trailing trivia.
/// </summary>
public TextSpan FullSpan => new TextSpan(this.Position, this.Green.FullWidth);
internal int SlotCount => this.Green.SlotCount;
/// <summary>
/// The absolute span of this node in characters, not including its leading and trailing trivia.
/// </summary>
public TextSpan Span
{
get
{
// Start with the full span.
var start = Position;
var width = this.Green.FullWidth;
// adjust for preceding trivia (avoid calling this twice, do not call Green.Width)
var precedingWidth = this.Green.GetLeadingTriviaWidth();
start += precedingWidth;
width -= precedingWidth;
// adjust for following trivia width
width -= this.Green.GetTrailingTriviaWidth();
Debug.Assert(width >= 0);
return new TextSpan(start, width);
}
}
/// <summary>
/// Same as accessing <see cref="TextSpan.Start"/> on <see cref="Span"/>.
/// </summary>
/// <remarks>
/// Slight performance improvement.
/// </remarks>
public int SpanStart => Position + Green.GetLeadingTriviaWidth();
/// <summary>
/// The width of the node in characters, not including leading and trailing trivia.
/// </summary>
/// <remarks>
/// The Width property returns the same value as Span.Length, but is somewhat more efficient.
/// </remarks>
internal int Width => this.Green.Width;
/// <summary>
/// The complete width of the node in characters, including leading and trailing trivia.
/// </summary>
/// <remarks>The FullWidth property returns the same value as FullSpan.Length, but is
/// somewhat more efficient.</remarks>
internal int FullWidth => this.Green.FullWidth;
// this is used in cases where we know that a child is a node of particular type.
internal SyntaxNode? GetRed(ref SyntaxNode? field, int slot)
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(slot);
if (green != null)
{
Interlocked.CompareExchange(ref field, green.CreateRed(this, this.GetChildPosition(slot)), null);
result = field;
}
}
return result;
}
// special case of above function where slot = 0, does not need GetChildPosition
internal SyntaxNode? GetRedAtZero(ref SyntaxNode? field)
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(0);
if (green != null)
{
Interlocked.CompareExchange(ref field, green.CreateRed(this, this.Position), null);
result = field;
}
}
return result;
}
protected T? GetRed<T>(ref T? field, int slot) where T : SyntaxNode
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(slot);
if (green != null)
{
Interlocked.CompareExchange(ref field, (T)green.CreateRed(this, this.GetChildPosition(slot)), null);
result = field;
}
}
return result;
}
// special case of above function where slot = 0, does not need GetChildPosition
protected T? GetRedAtZero<T>(ref T? field) where T : SyntaxNode
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(0);
if (green != null)
{
Interlocked.CompareExchange(ref field, (T)green.CreateRed(this, this.Position), null);
result = field;
}
}
return result;
}
/// <summary>
/// This works the same as GetRed, but intended to be used in lists
/// The only difference is that the public parent of the node is not the list,
/// but the list's parent. (element's grand parent).
/// </summary>
internal SyntaxNode? GetRedElement(ref SyntaxNode? element, int slot)
{
Debug.Assert(this.IsList);
var result = element;
if (result == null)
{
var green = this.Green.GetRequiredSlot(slot);
// passing list's parent
Interlocked.CompareExchange(ref element, green.CreateRed(this.Parent, this.GetChildPosition(slot)), null);
result = element;
}
return result;
}
/// <summary>
/// special cased helper for 2 and 3 children lists where child #1 may map to a token
/// </summary>
internal SyntaxNode? GetRedElementIfNotToken(ref SyntaxNode? element)
{
Debug.Assert(this.IsList);
var result = element;
if (result == null)
{
var green = this.Green.GetRequiredSlot(1);
if (!green.IsToken)
{
// passing list's parent
Interlocked.CompareExchange(ref element, green.CreateRed(this.Parent, this.GetChildPosition(1)), null);
result = element;
}
}
return result;
}
internal SyntaxNode GetWeakRedElement(ref WeakReference<SyntaxNode>? slot, int index)
{
SyntaxNode? value = null;
if (slot?.TryGetTarget(out value) == true)
{
return value!;
}
return CreateWeakItem(ref slot, index);
}
// handle a miss
private SyntaxNode CreateWeakItem(ref WeakReference<SyntaxNode>? slot, int index)
{
var greenChild = this.Green.GetRequiredSlot(index);
var newNode = greenChild.CreateRed(this.Parent, GetChildPosition(index));
var newWeakReference = new WeakReference<SyntaxNode>(newNode);
while (true)
{
SyntaxNode? previousNode = null;
WeakReference<SyntaxNode>? previousWeakReference = slot;
if (previousWeakReference?.TryGetTarget(out previousNode) == true)
{
return previousNode!;
}
if (Interlocked.CompareExchange(ref slot, newWeakReference, previousWeakReference) == previousWeakReference)
{
return newNode;
}
}
}
/// <summary>
/// Returns the string representation of this node, not including its leading and trailing trivia.
/// </summary>
/// <returns>The string representation of this node, not including its leading and trailing trivia.</returns>
/// <remarks>The length of the returned string is always the same as Span.Length</remarks>
public override string ToString()
{
return this.Green.ToString();
}
/// <summary>
/// Returns full string representation of this node including its leading and trailing trivia.
/// </summary>
/// <returns>The full string representation of this node including its leading and trailing trivia.</returns>
/// <remarks>The length of the returned string is always the same as FullSpan.Length</remarks>
public virtual string ToFullString()
{
return this.Green.ToFullString();
}
/// <summary>
/// Writes the full text of this node to the specified <see cref="TextWriter"/>.
/// </summary>
public virtual void WriteTo(TextWriter writer)
{
this.Green.WriteTo(writer, leading: true, trailing: true);
}
/// <summary>
/// Gets the full text of this node as a new <see cref="SourceText"/> instance.
/// </summary>
/// <param name="encoding">
/// Encoding of the file that the text was read from or is going to be saved to.
/// <c>null</c> if the encoding is unspecified.
/// If the encoding is not specified the <see cref="SourceText"/> isn't debuggable.
/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
public SourceText GetText(Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
{
var builder = new StringBuilder();
this.WriteTo(new StringWriter(builder));
return new StringBuilderText(builder, encoding, checksumAlgorithm);
}
/// <summary>
/// Determine whether this node is structurally equivalent to another.
/// </summary>
public bool IsEquivalentTo([NotNullWhen(true)] SyntaxNode? other)
{
if (this == other)
{
return true;
}
if (other == null)
{
return false;
}
return this.Green.IsEquivalentTo(other.Green);
}
/// <summary>
/// Returns true if these two nodes are considered "incrementally identical". An incrementally identical node
/// occurs when a <see cref="SyntaxTree"/> is incrementally parsed using <see cref="SyntaxTree.WithChangedText"/>
/// and the incremental parser is able to take the node from the original tree and use it in its entirety in the
/// new tree. In this case, the <see cref="SyntaxNode.ToFullString()"/> of each node will be the same, though
/// they could have different parents, and may occur at different positions in their respective trees. If two nodes are
/// incrementally identical, all children of each node will be incrementally identical as well.
/// </summary>
/// <remarks>
/// Incrementally identical nodes can also appear within the same syntax tree, or syntax trees that did not arise
/// from <see cref="SyntaxTree.WithChangedText"/>. This can happen as the parser is allowed to construct parse
/// trees from shared nodes for efficiency. In all these cases though, it will still remain true that the incrementally
/// identical nodes could have different parents and may occur at different positions in their respective trees.
/// </remarks>
public bool IsIncrementallyIdenticalTo([NotNullWhen(true)] SyntaxNode? other)
=> this.Green != null && this.Green == other?.Green;
/// <summary>
/// Determines whether the node represents a language construct that was actually parsed
/// from the source code. Missing nodes are generated by the parser in error scenarios to
/// represent constructs that should have been present in the source code in order to
/// compile successfully but were actually missing.
/// </summary>
public bool IsMissing
{
get
{
return this.Green.IsMissing;
}
}
/// <summary>
/// Determines whether this node is a descendant of a structured trivia.
/// </summary>
public bool IsPartOfStructuredTrivia()
{
for (SyntaxNode? node = this; node != null; node = node.Parent)
{
if (node.IsStructuredTrivia)
return true;
}
return false;
}
/// <summary>
/// Determines whether this node represents a structured trivia.
/// </summary>
public bool IsStructuredTrivia
{
get
{
return this.Green.IsStructuredTrivia;
}
}
/// <summary>
/// Determines whether a descendant trivia of this node is structured.
/// </summary>
public bool HasStructuredTrivia
{
get
{
return this.Green.ContainsStructuredTrivia && !this.Green.IsStructuredTrivia;
}
}
/// <summary>
/// Determines whether this node has any descendant skipped text.
/// </summary>
public bool ContainsSkippedText
{
get
{
return this.Green.ContainsSkippedText;
}
}
/// <summary>
/// Determines whether this node has any descendant preprocessor directives.
/// </summary>
public bool ContainsDirectives
{
get
{
return this.Green.ContainsDirectives;
}
}
/// <summary>
/// Determines whether this node or any of its descendant nodes, tokens or trivia have any diagnostics on them.
/// </summary>
public bool ContainsDiagnostics
{
get
{
return this.Green.ContainsDiagnostics;
}
}
/// <summary>
/// Determines if the specified node is a descendant of this node.
/// Returns true for current node.
/// </summary>
public bool Contains(SyntaxNode? node)
{
if (node == null || !this.FullSpan.Contains(node.FullSpan))
{
return false;
}
while (node != null)
{
if (node == this)
{
return true;
}
if (node.Parent != null)
{
node = node.Parent;
}
else if (node.IsStructuredTrivia)
{
node = ((IStructuredTriviaSyntax)node).ParentTrivia.Token.Parent;
}
else
{
node = null;
}
}
return false;
}
/// <summary>
/// Determines whether this node has any leading trivia.
/// </summary>
public bool HasLeadingTrivia
{
get
{
return this.GetLeadingTrivia().Count > 0;
}
}
/// <summary>
/// Determines whether this node has any trailing trivia.
/// </summary>
public bool HasTrailingTrivia
{
get
{
return this.GetTrailingTrivia().Count > 0;
}
}
/// <summary>
/// Gets a node at given node index without forcing its creation.
/// If node was not created it would return null.
/// </summary>
internal abstract SyntaxNode? GetCachedSlot(int index);
internal int GetChildIndex(int slot)
{
int index = 0;
for (int i = 0; i < slot; i++)
{
var item = this.Green.GetSlot(i);
if (item != null)
{
if (item.IsList)
{
index += item.SlotCount;
}
else
{
index++;
}
}
}
return index;
}
/// <summary>
/// This function calculates the offset of a child at given position. It is very common that
/// some children to the left of the given index already know their positions so we first
/// check if that is the case. In a worst case the cost is O(n), but it is not generally an
/// issue because number of children in regular nodes is fixed and small. In a case where
/// the number of children could be large (lists) this function is overridden with more
/// efficient implementations.
/// </summary>
internal virtual int GetChildPosition(int index)
{
int offset = 0;
var green = this.Green;
while (index > 0)
{
index--;
var prevSibling = this.GetCachedSlot(index);
if (prevSibling != null)
{
return prevSibling.EndPosition + offset;
}
var greenChild = green.GetSlot(index);
if (greenChild != null)
{
offset += greenChild.FullWidth;
}
}
return this.Position + offset;
}
public Location GetLocation()
{
return this.SyntaxTree.GetLocation(this.Span);
}
internal Location Location
{
get
{
// SyntaxNodes always has a non-null SyntaxTree, however the tree might be rooted at a node which is not a CompilationUnit.
// These kind of nodes may be seen during binding in couple of scenarios:
// (a) Compiler synthesized syntax nodes (e.g. missing nodes, qualified names for command line using directives, etc.)
// (b) Speculatively binding syntax nodes through the semantic model.
//
// For scenario (a), we need to ensure that we return NoLocation for generating location agnostic compiler diagnostics.
// For scenario (b), at present, we do not expose the diagnostics for speculative binding, hence we can return NoLocation.
// In future, if we decide to support this, we will need some mechanism to distinguish between scenarios (a) and (b) here.
var tree = this.SyntaxTree;
RoslynDebug.Assert(tree != null);
return !tree.SupportsLocations ? NoLocation.Singleton : new SourceLocation(this);
}
}
/// <summary>
/// Gets a list of all the diagnostics in the sub tree that has this node as its root.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public IEnumerable<Diagnostic> GetDiagnostics()
{
return this.SyntaxTree.GetDiagnostics(this);
}
/// <summary>
/// Gets a <see cref="SyntaxReference"/> for this syntax node. CommonSyntaxReferences can be used to
/// regain access to a syntax node without keeping the entire tree and source text in
/// memory.
/// </summary>
public SyntaxReference GetReference()
{
return this.SyntaxTree.GetReference(this);
}
#region Node Lookup
/// <summary>
/// The node that contains this node in its <see cref="ChildNodes"/> collection.
/// </summary>
public SyntaxNode? Parent
{
get
{
return _parent;
}
}
public virtual SyntaxTrivia ParentTrivia
{
get
{
return default(SyntaxTrivia);
}
}
internal SyntaxNode? ParentOrStructuredTriviaParent
{
get
{
return GetParent(this, ascendOutOfTrivia: true);
}
}
/// <summary>
/// The list of child nodes and tokens of this node, where each element is a SyntaxNodeOrToken instance.
/// </summary>
public ChildSyntaxList ChildNodesAndTokens()
{
return new ChildSyntaxList(this);
}
public virtual SyntaxNodeOrToken ChildThatContainsPosition(int position)
{
//PERF: it is very important to keep this method fast.
if (!FullSpan.Contains(position))
{
throw new ArgumentOutOfRangeException(nameof(position));
}
SyntaxNodeOrToken childNodeOrToken = ChildSyntaxList.ChildThatContainsPosition(this, position);
Debug.Assert(childNodeOrToken.FullSpan.Contains(position), "ChildThatContainsPosition's return value does not contain the requested position.");
return childNodeOrToken;
}
/// <summary>
/// Gets node at given node index.
/// This WILL force node creation if node has not yet been created.
/// Can still return null for invalid slot numbers
/// </summary>
internal abstract SyntaxNode? GetNodeSlot(int slot);
internal SyntaxNode GetRequiredNodeSlot(int slot)
{
var syntaxNode = GetNodeSlot(slot);
RoslynDebug.Assert(syntaxNode is object);
return syntaxNode;
}
/// <summary>
/// Gets a list of the child nodes in prefix document order.
/// </summary>
public IEnumerable<SyntaxNode> ChildNodes()
{
foreach (var nodeOrToken in this.ChildNodesAndTokens())
{
if (nodeOrToken.AsNode(out var node))
{
yield return node;
}
}
}
/// <summary>
/// Gets a list of ancestor nodes
/// </summary>
public IEnumerable<SyntaxNode> Ancestors(bool ascendOutOfTrivia = true)
{
return this.Parent?
.AncestorsAndSelf(ascendOutOfTrivia) ??
SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
/// <summary>
/// Gets a list of ancestor nodes (including this node)
/// </summary>
public IEnumerable<SyntaxNode> AncestorsAndSelf(bool ascendOutOfTrivia = true)
{
for (SyntaxNode? node = this; node != null; node = GetParent(node, ascendOutOfTrivia))
{
yield return node;
}
}
private static SyntaxNode? GetParent(SyntaxNode node, bool ascendOutOfTrivia)
{
var parent = node.Parent;
if (parent == null && ascendOutOfTrivia)
{
var structuredTrivia = node as IStructuredTriviaSyntax;
if (structuredTrivia != null)
{
parent = structuredTrivia.ParentTrivia.Token.Parent;
}
}
return parent;
}
/// <summary>
/// Gets the first node of type TNode that matches the predicate.
/// </summary>
public TNode? FirstAncestorOrSelf<TNode>(Func<TNode, bool>? predicate = null, bool ascendOutOfTrivia = true)
where TNode : SyntaxNode
{
for (SyntaxNode? node = this; node != null; node = GetParent(node, ascendOutOfTrivia))
{
var tnode = node as TNode;
if (tnode != null && (predicate == null || predicate(tnode)))
{
return tnode;
}
}
return null;
}
/// <summary>
/// Gets the first node of type TNode that matches the predicate.
/// </summary>
[SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required for consistent API usage patterns.")]
public TNode? FirstAncestorOrSelf<TNode, TArg>(Func<TNode, TArg, bool> predicate, TArg argument, bool ascendOutOfTrivia = true)
where TNode : SyntaxNode
{
for (var node = this; node != null; node = GetParent(node, ascendOutOfTrivia))
{
if (node is TNode tnode && predicate(tnode, argument))
{
return tnode;
}
}
return null;
}
/// <summary>
/// Gets a list of descendant nodes in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodes(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of descendant nodes in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodes(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of descendant nodes (including this node) in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodesAndSelf(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Gets a list of descendant nodes (including this node) in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodesAndSelf(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Gets a list of descendant nodes and tokens in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokens(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of the descendant nodes and tokens in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokens(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of descendant nodes and tokens (including this node) in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensAndSelf(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Gets a list of the descendant nodes and tokens (including this node) in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensAndSelf(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Finds the node with the smallest <see cref="FullSpan"/> that contains <paramref name="span"/>.
/// <paramref name="getInnermostNodeForTie"/> is used to determine the behavior in case of a tie (i.e. a node having the same span as its parent).
/// If <paramref name="getInnermostNodeForTie"/> is true, then it returns lowest descending node encompassing the given <paramref name="span"/>.
/// Otherwise, it returns the outermost node encompassing the given <paramref name="span"/>.
/// </summary>
/// <devdoc>
/// TODO: This should probably be reimplemented with <see cref="ChildThatContainsPosition"/>
/// </devdoc>
/// <exception cref="ArgumentOutOfRangeException">This exception is thrown if <see cref="FullSpan"/> doesn't contain the given span.</exception>
public SyntaxNode FindNode(TextSpan span, bool findInsideTrivia = false, bool getInnermostNodeForTie = false)
{
if (!this.FullSpan.Contains(span))
{
throw new ArgumentOutOfRangeException(nameof(span));
}
var node = FindToken(span.Start, findInsideTrivia)
.Parent
!.FirstAncestorOrSelf<SyntaxNode, TextSpan>((a, span) => a.FullSpan.Contains(span), span);
RoslynDebug.Assert(node is object);
SyntaxNode? cuRoot = node.SyntaxTree?.GetRoot();
// Tie-breaking.
if (!getInnermostNodeForTie)
{
while (true)
{
var parent = node.Parent;
// NOTE: We care about FullSpan equality, but FullWidth is cheaper and equivalent.
if (parent == null || parent.FullWidth != node.FullWidth) break;
// prefer child over compilation unit
if (parent == cuRoot) break;
node = parent;
}
}
return node;
}
#endregion
#region Token Lookup
/// <summary>
/// Finds a descendant token of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the token relative to the beginning of the file.</param>
/// <param name="findInsideTrivia">
/// True to return tokens that are part of trivia. If false finds the token whose full span (including trivia)
/// includes the position.
/// </param>
public SyntaxToken FindToken(int position, bool findInsideTrivia = false)
{
return FindTokenCore(position, findInsideTrivia);
}
/// <summary>
/// Gets the first token of the tree rooted by this node. Skips zero-width tokens.
/// </summary>
/// <returns>The first token or <c>default(SyntaxToken)</c> if it doesn't exist.</returns>
public SyntaxToken GetFirstToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false)
{
return SyntaxNavigator.Instance.GetFirstToken(this, includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
}
/// <summary>
/// Gets the last token of the tree rooted by this node. Skips zero-width tokens.
/// </summary>
/// <returns>The last token or <c>default(SyntaxToken)</c> if it doesn't exist.</returns>
public SyntaxToken GetLastToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false)
{
return SyntaxNavigator.Instance.GetLastToken(this, includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
}
/// <summary>
/// Gets a list of the direct child tokens of this node.
/// </summary>
public IEnumerable<SyntaxToken> ChildTokens()
{
foreach (var nodeOrToken in this.ChildNodesAndTokens())
{
if (nodeOrToken.IsToken)
{
yield return nodeOrToken.AsToken();
}
}
}
/// <summary>
/// Gets a list of all the tokens in the span of this node.
/// </summary>
public IEnumerable<SyntaxToken> DescendantTokens(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return this.DescendantNodesAndTokens(descendIntoChildren, descendIntoTrivia).Where(sn => sn.IsToken).Select(sn => sn.AsToken());
}
/// <summary>
/// Gets a list of all the tokens in the full span of this node.
/// </summary>
public IEnumerable<SyntaxToken> DescendantTokens(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return this.DescendantNodesAndTokens(span, descendIntoChildren, descendIntoTrivia).Where(sn => sn.IsToken).Select(sn => sn.AsToken());
}
#endregion
#region Trivia Lookup
/// <summary>
/// The list of trivia that appears before this node in the source code and are attached to a token that is a
/// descendant of this node.
/// </summary>
public SyntaxTriviaList GetLeadingTrivia()
{
return GetFirstToken(includeZeroWidth: true).LeadingTrivia;
}
/// <summary>
/// The list of trivia that appears after this node in the source code and are attached to a token that is a
/// descendant of this node.
/// </summary>
public SyntaxTriviaList GetTrailingTrivia()
{
return GetLastToken(includeZeroWidth: true).TrailingTrivia;
}
/// <summary>
/// Finds a descendant trivia of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of the file.</param>
/// <param name="findInsideTrivia">
/// True to return tokens that are part of trivia. If false finds the token whose full span (including trivia)
/// includes the position.
/// </param>
public SyntaxTrivia FindTrivia(int position, bool findInsideTrivia = false)
{
return FindTrivia(position, findInsideTrivia ? SyntaxTrivia.Any : null);
}
/// <summary>
/// Finds a descendant trivia of this node at the specified position, where the position is
/// within the span of the node.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of
/// the file.</param>
/// <param name="stepInto">Specifies a function that determines per trivia node, whether to
/// descend into structured trivia of that node.</param>
/// <returns></returns>
public SyntaxTrivia FindTrivia(int position, Func<SyntaxTrivia, bool>? stepInto)
{
if (this.FullSpan.Contains(position))
{
return FindTriviaByOffset(this, position - this.Position, stepInto);
}
return default(SyntaxTrivia);