Repository navigation
Expand file tree
/
Copy pathFAQ.vb
More file actions
2435 lines (1920 loc) · 94.4 KB
/
Copy pathFAQ.vb
File metadata and controls
2435 lines (1920 loc) · 94.4 KB
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
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.IO
Imports System.Text
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.FindSymbols
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Xunit
Namespace APISampleUnitTestsVB
Public Class FAQ
<AttributeUsage(AttributeTargets.Method)>
Private Class FAQAttribute
Inherits Attribute
Private ReadOnly _Id As Integer
Public ReadOnly Property Id As Integer
Get
Return _Id
End Get
End Property
Public Sub New(id As Integer)
Me._Id = id
End Sub
End Class
Private _Mscorlib As MetadataReference
Public ReadOnly Property Mscorlib As MetadataReference
Get
If _Mscorlib Is Nothing Then
_Mscorlib = MetadataReference.CreateFromFile(GetType(Object).Assembly.Location)
End If
Return _Mscorlib
End Get
End Property
#Region " Section 1 : Getting Information Questions "
<FAQ(1)>
<Fact>
Public Sub GetTypeForTypeName()
Dim tree = SyntaxFactory.ParseSyntaxTree(
<text>
Module Program
Public Sub Main()
Dim i As Integer = 0
i += 1
End Sub
End Module
</text>.Value)
Dim vbRuntime = MetadataReference.CreateFromFile(GetType(CompilerServices.StandardModuleAttribute).Assembly.Location)
Dim comp = VisualBasicCompilation.Create("MyCompilation", syntaxTrees:={tree}, references:={Mscorlib, vbRuntime})
Dim model = comp.GetSemanticModel(tree)
' Get TypeSyntax corresponding to the keyword 'Integer' above.
Dim typeName =
Aggregate
node In tree.GetRoot().DescendantNodes.OfType(Of TypeSyntax)()
Where
node.ToString() = "Integer"
Into [Single]()
' Use GetTypeInfo() to get TypeSymbol corresponding to the keyword 'Integer' above.
Dim type = CType(model.GetTypeInfo(typeName).Type, ITypeSymbol)
Assert.Equal(SpecialType.System_Int32, type.SpecialType)
Assert.Equal("Integer", type.ToDisplayString())
' Alternately, use GetSymbolInfo() to get TypeSymbol corresponding to keyword 'Integer' above.
type = CType(model.GetSymbolInfo(typeName).Symbol, ITypeSymbol)
Assert.Equal(SpecialType.System_Int32, type.SpecialType)
Assert.Equal("Integer", type.ToDisplayString())
End Sub
<FAQ(2)>
<Fact>
Public Sub GetTypeForVariableDeclaration()
Dim tree = SyntaxFactory.ParseSyntaxTree(
<text>
Module Program
Public Sub Main()
Dim i = 0 : i += 1
End Sub
End Module
</text>.Value)
Dim vbOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithEmbedVbCoreRuntime(True)
Dim comp = VisualBasicCompilation.Create("MyCompilation", syntaxTrees:={tree}, references:={Mscorlib}, options:=vbOptions)
Dim model = comp.GetSemanticModel(tree)
' Get ModifiedIdentifierSyntax corresponding to the identifier 'i' in the statement 'Dim i = ...' above.
Dim identifier As ModifiedIdentifierSyntax = tree.GetRoot().
DescendantNodes.
OfType(Of VariableDeclaratorSyntax).
Single.
Names.
Single
' Get TypeSymbol corresponding to 'Dim i' above.
Dim type = CType(model.GetDeclaredSymbol(identifier), ILocalSymbol).Type
Assert.Equal(SpecialType.System_Int32, type.SpecialType)
Assert.Equal("Integer", type.ToDisplayString())
End Sub
<FAQ(3)>
<Fact>
Public Sub GetTypeForExpressions()
Dim source =
<text>
Imports System
Module Program
Public Sub M(s As Short())
Dim d = 1.0
Console.WriteLine(s(0) + d)
End Sub
Public Sub Main()
End Sub
End Module
</text>.Value
Dim vbOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithEmbedVbCoreRuntime(True)
Dim _projectId = ProjectId.CreateNewId()
Dim _documentId = DocumentId.CreateNewId(_projectId)
Dim sln = New AdhocWorkspace().CurrentSolution.
AddProject(_projectId, "MyProject", "MyProject", LanguageNames.VisualBasic).WithProjectCompilationOptions(_projectId, vbOptions).
AddMetadataReference(_projectId, Mscorlib).
AddDocument(_documentId, "MyFile.vb", source)
Dim document = sln.GetDocument(_documentId)
Dim model = CType(document.GetSemanticModelAsync().Result, SemanticModel)
' Get BinaryExpressionSyntax corresponding to the expression 's(0) + d' above.
Dim addExpression As BinaryExpressionSyntax = document.GetSyntaxRootAsync().Result.
DescendantNodes.
OfType(Of BinaryExpressionSyntax).
Single
' Get TypeSymbol corresponding to expression 's(0) + d' above.
Dim expressionTypeInfo As TypeInfo = model.GetTypeInfo(addExpression)
Dim expressionType = expressionTypeInfo.Type
Assert.Equal(SpecialType.System_Double, expressionType.SpecialType)
Assert.Equal("Double", expressionType.ToDisplayString())
Assert.Equal(SpecialType.System_Double, expressionTypeInfo.ConvertedType.SpecialType)
Assert.True(model.GetConversion(addExpression).IsIdentity)
' Get IdentifierNameSyntax corresponding to the variable 'd' in expression 's(0) + d' above.
Dim identifier = CType(addExpression.Right, IdentifierNameSyntax)
' Use GetTypeInfo() to get TypeSymbol corresponding to variable 'd' above.
Dim variableTypeInfo As TypeInfo = model.GetTypeInfo(identifier)
Dim variableType = variableTypeInfo.Type
Assert.Equal(SpecialType.System_Double, variableType.SpecialType)
Assert.Equal("Double", variableType.ToDisplayString())
Assert.Equal(SpecialType.System_Double, variableTypeInfo.ConvertedType.SpecialType)
Assert.True(model.GetConversion(identifier).IsIdentity)
' Alternately, use GetSymbolInfo() to get TypeSymbol corresponding to variable 'd' above.
variableType = (CType(model.GetSymbolInfo(identifier).Symbol, ILocalSymbol)).Type
Assert.Equal(SpecialType.System_Double, variableType.SpecialType)
Assert.Equal("Double", variableType.ToDisplayString())
' Get InvocationExpressionSyntax corresponding to 's(0)' in expression 's(0) + d' above.
Dim elementAccess = CType(addExpression.Left, InvocationExpressionSyntax)
' Use GetTypeInfo() to get TypeSymbol corresponding to 's(0)' above.
expressionTypeInfo = model.GetTypeInfo(elementAccess)
expressionType = expressionTypeInfo.Type
Assert.Equal(SpecialType.System_Int16, expressionType.SpecialType)
Assert.Equal("Short", expressionType.ToDisplayString())
Assert.Equal(SpecialType.System_Double, expressionTypeInfo.ConvertedType.SpecialType)
Dim conv = model.GetConversion(elementAccess)
Assert.True(conv.IsWidening AndAlso conv.IsNumeric)
' Get IdentifierNameSyntax corresponding to the parameter 's' in expression 's(0) + d' above.
identifier = CType(elementAccess.Expression, IdentifierNameSyntax)
' Use GetTypeInfo() to get TypeSymbol corresponding to parameter 's' above.
variableTypeInfo = model.GetTypeInfo(identifier)
variableType = variableTypeInfo.Type
Assert.Equal("Short()", variableType.ToDisplayString())
Assert.Equal("Short()", variableTypeInfo.ConvertedType.ToDisplayString())
Assert.True(model.GetConversion(identifier).IsIdentity)
' Alternately, use GetSymbolInfo() to get TypeSymbol corresponding to parameter 's' above.
variableType = (CType(model.GetSymbolInfo(identifier).Symbol, IParameterSymbol)).Type
Assert.Equal("Short()", variableType.ToDisplayString())
Assert.Equal(SpecialType.System_Int16, CType(variableType, IArrayTypeSymbol).ElementType.SpecialType)
End Sub
<FAQ(4)>
<Fact>
Public Sub GetInScopeSymbols()
Dim source =
<text>
Class C
End Class
Module Program
Private i As Integer = 0
Public Sub Main()
Dim j As Integer = 0 : j += i
' What symbols are in scope here?
End Sub
End Module
</text>.Value
Dim tree = SyntaxFactory.ParseSyntaxTree(source)
Dim vbOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithEmbedVbCoreRuntime(True)
Dim comp = VisualBasicCompilation.Create("MyCompilation", syntaxTrees:={tree}, references:={Mscorlib}, options:=vbOptions)
Dim model = comp.GetSemanticModel(tree)
' Get position of the comment above.
Dim position = source.IndexOf("' ")
' Get 'all' symbols that are in scope at the above position.
Dim symbols = model.LookupSymbols(position)
' Note: "Windows" only appears as a symbol at this location in Windows 8.1.
Dim results = String.Join(vbLf, From symbol In symbols
Select result = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)
Where result <> "Windows"
Order By result)
Assert.Equal(
<text>C
j As Integer
Microsoft
Program
Program.i As Integer
Sub Program.Main()
System</text>.Value, results)
' Filter results by looking at Kind of returned symbols (only get locals and fields).
results = String.Join(vbLf, From symbol In symbols
Where symbol.Kind = SymbolKind.Local OrElse
symbol.Kind = SymbolKind.Field
Select result = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)
Order By result)
Assert.Equal(
<text>j As Integer
Program.i As Integer</text>.Value, results)
' Filter results - get namespaces and types.
' Note: "Windows" only appears as a symbol at this location in Windows 8.1.
symbols = model.LookupNamespacesAndTypes(position)
results = String.Join(vbLf, From symbol In symbols
Select result = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)
Where result <> "Windows"
Order By result)
Assert.Equal(
<text>C
Microsoft
Program
System</text>.Value, results)
End Sub
<FAQ(5)>
<Fact>
Public Sub GetSymbolsForAccessibleMembersOfAType()
Dim source =
<text>
Imports System
Public Class C
Friend InstanceField As Integer = 0
Public Property InstanceProperty As Integer
Friend Sub InstanceMethod()
Console.WriteLine(InstanceField)
End Sub
Protected Sub InaccessibleInstanceMethod()
Console.WriteLine(InstanceProperty)
End Sub
End Class
Public Module ExtensionMethods
<System.Runtime.CompilerServices.Extension>
Public Sub ExtensionMethod(s As C)
End Sub
End Module
Module Program
Sub Main()
Dim c As C = New C()
c.ToString()
End Sub
End Module
</text>.Value
Dim tree = SyntaxFactory.ParseSyntaxTree(source)
Dim vbOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithEmbedVbCoreRuntime(True)
Dim comp = VisualBasicCompilation.Create("MyCompilation", syntaxTrees:={tree}, references:={Mscorlib}, options:=vbOptions)
Dim model = comp.GetSemanticModel(tree)
' Get position of 'c.ToString()' above.
Dim position = source.IndexOf("c.ToString()")
' Get IdentifierNameSyntax corresponding to identifier 'c' above.
Dim identifier = CType(tree.GetRoot().FindToken(position).Parent, IdentifierNameSyntax)
' Get TypeSymbol corresponding to variable 'c' above.
Dim type = model.GetTypeInfo(identifier).Type
' Get symbols for 'accessible' members on the above TypeSymbol.
Dim symbols = model.LookupSymbols(position, container:=type, includeReducedExtensionMethods:=True)
Dim results = String.Join(vbLf, From symbol In symbols
Select result = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)
Order By result)
Assert.Equal(
<text>C.InstanceField As Integer
Function Object.Equals(obj As Object) As Boolean
Function Object.Equals(objA As Object, objB As Object) As Boolean
Function Object.GetHashCode() As Integer
Function Object.GetType() As Type
Function Object.ReferenceEquals(objA As Object, objB As Object) As Boolean
Function Object.ToString() As String
Property C.InstanceProperty As Integer
Sub C.ExtensionMethod()
Sub C.InstanceMethod()</text>.Value, results)
End Sub
<FAQ(6)>
<Fact>
Public Sub FindAllInvocationsOfAMethod()
Dim tree = SyntaxFactory.ParseSyntaxTree(
<text>
Class C1
Public Sub M1()
M2()
End Sub
Public Sub M2()
End Sub
End Class
Class C2
Public Sub M1()
M2()
Call New C1().M2()
End Sub
Public Sub M2()
End Sub
End Class
Module Program
Sub Main()
End Sub
End Module
</text>.Value)
Dim vbOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithEmbedVbCoreRuntime(True)
Dim comp = VisualBasicCompilation.Create("MyCompilation", syntaxTrees:={tree}, references:={Mscorlib}, options:=vbOptions)
Dim model = comp.GetSemanticModel(tree)
' Get MethodBlockSyntax corresponding to method C1.M2() above.
Dim methodDeclaration As MethodBlockSyntax =
Aggregate c In tree.GetRoot().DescendantNodes.OfType(Of ClassBlockSyntax)()
Where c.ClassStatement.Identifier.ValueText = "C1"
From m In c.Members.OfType(Of MethodBlockSyntax)()
Where CType(m.SubOrFunctionStatement, MethodStatementSyntax).Identifier.ValueText = "M2"
Select m
Into [Single]()
' Get MethodSymbol corresponding to method C1.M2() above.
Dim method = CType(model.GetDeclaredSymbol(methodDeclaration), IMethodSymbol)
' Get all InvocationExpressionSyntax in the above code.
Dim allInvocations = tree.GetRoot().DescendantNodes.OfType(Of InvocationExpressionSyntax)()
' Use GetSymbolInfo() to find invocations of method C1.M2() above.
Dim matchingInvocations = From i In allInvocations Where model.GetSymbolInfo(i).Symbol.Equals(method)
Assert.Equal(2, matchingInvocations.Count)
End Sub
<FAQ(7)>
<Fact>
Public Sub FindAllReferencesToAMethodInASolution()
Dim source1 = <text>
Namespace NS
Public Class C
Public Sub MethodThatWeAreTryingToFind()
End Sub
Public Sub AnotherMethod()
MethodThatWeAreTryingToFind() ' First Reference.
End Sub
End Class
End Namespace</text>.Value
Dim source2 = <text>
Imports NS
Imports AliasedType = NS.C
Module Program
Sub Main()
Dim c1 = New C()
c1.MethodThatWeAreTryingToFind() ' Second Reference.
c1.AnotherMethod()
Dim c2 = New AliasedType()
c2.MethodThatWeAreTryingToFind() ' Third Reference.
End Sub
End Module</text>.Value
Dim _project1Id = ProjectId.CreateNewId(),
_project2Id = ProjectId.CreateNewId()
Dim _document1Id = DocumentId.CreateNewId(_project1Id),
_document2Id = DocumentId.CreateNewId(_project2Id)
Dim vbOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithEmbedVbCoreRuntime(True)
Dim sln = New AdhocWorkspace().CurrentSolution.
AddProject(_project1Id, "Project1", "Project1", LanguageNames.VisualBasic).
AddMetadataReference(_project1Id, Mscorlib).
AddDocument(_document1Id, "File1.vb", source1).
WithProjectCompilationOptions(_project1Id, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithEmbedVbCoreRuntime(True)).
AddProject(_project2Id, "Project2", "Project2", LanguageNames.VisualBasic).WithProjectCompilationOptions(_project2Id, vbOptions).
AddMetadataReference(_project2Id, Mscorlib).
AddProjectReference(_project2Id, New ProjectReference(_project1Id)).
AddDocument(_document2Id, "File2.vb", source2)
' If you wish to try against a real solution you could use code like
' Dim sln = Solution.Load("<Path>")
' OR Dim sln = Workspace.LoadSolution("<Path>").CurrentSolution
Dim project1 = sln.GetProject(_project1Id)
Dim document1 = project1.GetDocument(_document1Id)
' Get MethodBlockSyntax corresponding to the 'MethodThatWeAreTryingToFind'.
Dim methodBlock As MethodBlockSyntax = document1.GetSyntaxRootAsync().Result.DescendantNodes.
OfType(Of MethodBlockSyntax).
Single(Function(m) m.SubOrFunctionStatement.Identifier.ValueText = "MethodThatWeAreTryingToFind")
' Get MethodSymbol corresponding to the 'MethodThatWeAreTryingToFind'.
Dim method = document1.GetSemanticModelAsync().Result.GetDeclaredSymbol(methodBlock)
' Find all references to the 'MethodThatWeAreTryingToFind' in the solution.
Dim methodReferences = SymbolFinder.FindReferencesAsync(method, sln).Result
Assert.Equal(1, methodReferences.Count)
Dim methodReference = methodReferences.Single()
Assert.Equal(3, methodReference.Locations.Count)
Dim methodDefinition = CType(methodReference.Definition, IMethodSymbol)
Assert.Equal("MethodThatWeAreTryingToFind", methodDefinition.Name)
Assert.True(methodReference.Definition.Locations.Single.IsInSource)
Assert.Equal("File1.vb", methodReference.Definition.Locations.Single.SourceTree.FilePath)
Assert.True(methodReference.Locations.All(Function(referenceLocation) referenceLocation.Location.IsInSource))
Assert.Equal(1, methodReference.Locations.Count(Function(referenceLocation) referenceLocation.Document.Name = "File1.vb"))
Assert.Equal(2, methodReference.Locations.Count(Function(referenceLocation) referenceLocation.Document.Name = "File2.vb"))
End Sub
<FAQ(8)>
<Fact>
Public Sub FindAllInvocationsToMethodsFromAParticularNamespace()
Dim tree = SyntaxFactory.ParseSyntaxTree(
<text>
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
Dim a As Action = Sub() Return
Dim t = Task.Factory.StartNew(a)
t.Wait()
Console.WriteLine(a.ToString())
a = Sub()
t = New Task(a)
t.Start()
t.Wait()
End Sub
a()
End Sub
End Module
</text>.Value)
Dim vbOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithEmbedVbCoreRuntime(True)
Dim comp = VisualBasicCompilation.Create("MyCompilation", syntaxTrees:={tree}, references:={Mscorlib}, options:=vbOptions)
Dim model = comp.GetSemanticModel(tree)
' Instantiate MethodInvocationWalker (below) and tell it to find invocations to methods from the System.Threading.Tasks namespace.
Dim walker = New MethodInvocationWalker With {.SemanticModel = model, .NamespaceName = "System.Threading.Tasks"}
walker.Visit(tree.GetRoot())
Assert.Equal(
<text>
Line 8: Task.Factory.StartNew(a)
Line 9: t.Wait()
Line 13: New Task(a)
Line 14: t.Start()
Line 15: t.Wait()</text>.Value, walker.Results.ToString())
End Sub
' Below SyntaxWalker checks all nodes of type ObjectCreationExpressionSyntax or InvocationExpressionSyntax
' present under the SyntaxNode being visited to detect invocations to methods from the supplied namespace.
Public Class MethodInvocationWalker
Inherits VisualBasicSyntaxWalker
Public Property SemanticModel As SemanticModel
Public Property NamespaceName As String
Public Property Results As New StringBuilder()
Private Function CheckWhetherMethodIsFromNamespace(node As ExpressionSyntax) As Boolean
Dim isMatch = False
If SemanticModel IsNot Nothing Then
Dim symbolInfo = SemanticModel.GetSymbolInfo(node)
Dim ns As String = symbolInfo.Symbol.ContainingNamespace.ToDisplayString()
If ns = NamespaceName Then
Results.Append(vbLf)
Results.Append("Line ")
Results.Append(SemanticModel.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line)
Results.Append(": ")
Results.Append(node.ToString())
isMatch = True
End If
End If
Return isMatch
End Function
Public Overrides Sub VisitObjectCreationExpression(node As ObjectCreationExpressionSyntax)
CheckWhetherMethodIsFromNamespace(node)
MyBase.VisitObjectCreationExpression(node)
End Sub
Public Overrides Sub VisitInvocationExpression(node As InvocationExpressionSyntax)
CheckWhetherMethodIsFromNamespace(node)
MyBase.VisitInvocationExpression(node)
End Sub
End Class
<FAQ(9)>
<Fact>
Public Sub GetAllFieldAndMethodSymbolsInACompilation()
Dim tree = SyntaxFactory.ParseSyntaxTree(
<text>
Imports System
Namespace NS1
Public Class C
Dim InstanceField As Integer = 0
Friend Sub InstanceMethod()
Console.WriteLine(InstanceField)
End Sub
End Class
End Namespace
Namespace NS2
Module ExtensionMethods
<System.Runtime.CompilerServices.Extension>
Public Sub ExtensionMethod(s As NS1.C)
End Sub
End Module
End Namespace
Module Program
Sub Main()
Dim c As NS1.C = New NS1.C()
c.ToString()
End Sub
End Module
</text>.Value)
Dim vbRuntime = MetadataReference.CreateFromFile(GetType(CompilerServices.StandardModuleAttribute).Assembly.Location)
Dim comp = VisualBasicCompilation.Create("MyCompilation", syntaxTrees:={tree}, references:={Mscorlib, vbRuntime})
Dim results = New StringBuilder()
' Traverse the symbol tree to find all namespaces, types, methods and fields.
For Each ns In comp.Assembly.GlobalNamespace.GetNamespaceMembers()
results.Append(vbLf)
results.Append(ns.Kind.ToString())
results.Append(": ")
results.Append(ns.Name)
For Each typeMember In ns.GetTypeMembers()
results.Append(vbLf)
results.Append(" ")
results.Append(typeMember.TypeKind.ToString())
results.Append(": ")
results.Append(typeMember.Name)
For Each member In typeMember.GetMembers()
results.Append(vbLf)
results.Append(" ")
If member.Kind = SymbolKind.Field OrElse member.Kind = SymbolKind.Method Then
results.Append(member.Kind.ToString())
results.Append(": ")
results.Append(member.Name)
End If
Next
Next
Next
Assert.Equal(
<text>
Namespace: NS1
Class: C
Method: .ctor
Field: InstanceField
Method: InstanceMethod
Namespace: NS2
Module: ExtensionMethods
Method: ExtensionMethod</text>.Value, results.ToString())
End Sub
<FAQ(10)>
<Fact>
Public Sub TraverseAllExpressionsInASyntaxTreeUsingAWalker()
Dim tree = SyntaxFactory.ParseSyntaxTree(
<text>
Imports System
Module Program
Sub Main()
Dim i = 0.0
i += 1 + 2L
End Sub
End Module
</text>.Value)
Dim vbOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithEmbedVbCoreRuntime(True)
Dim comp = VisualBasicCompilation.Create("MyCompilation", syntaxTrees:={tree}, references:={Mscorlib}, options:=vbOptions)
Dim model = comp.GetSemanticModel(tree)
Dim walker = New ExpressionWalker() With {.SemanticModel = model}
walker.Visit(tree.GetRoot())
Assert.Equal(
<text>
LiteralExpressionSyntax 0.0 has type Double
IdentifierNameSyntax i has type Double
BinaryExpressionSyntax 1 + 2L has type Long
LiteralExpressionSyntax 1 has type Integer
LiteralExpressionSyntax 2L has type Long</text>.Value, walker.Results.ToString())
End Sub
' Below SyntaxWalker traverses all expressions under the SyntaxNode being visited and lists the types of these expressions.
Public Class ExpressionWalker
Inherits SyntaxWalker
Public Property SemanticModel As SemanticModel
Public Property Results As New StringBuilder()
Public Overrides Sub Visit(node As SyntaxNode)
If TypeOf node Is ExpressionSyntax Then
Dim type = SemanticModel.GetTypeInfo(CType(node, ExpressionSyntax)).Type
If type IsNot Nothing Then
Results.Append(vbLf)
Results.Append(node.GetType().Name)
Results.Append(" ")
Results.Append(node.ToString())
Results.Append(" has type ")
Results.Append(type.ToDisplayString())
End If
End If
MyBase.Visit(node)
End Sub
End Class
<FAQ(11)>
<Fact>
Public Sub CompareSyntax()
Dim source =
<text>
Imports System
Module Program
Sub Main()
Dim i = 0.0
i += 1 + 2L
End Sub
End Module
</text>.Value
Dim tree1 = SyntaxFactory.ParseSyntaxTree(source)
Dim tree2 = SyntaxFactory.ParseSyntaxTree(source)
Dim node1 As SyntaxNode = tree1.GetRoot()
Dim node2 As SyntaxNode = tree2.GetRoot()
' Compare trees and nodes that are identical.
Assert.True(tree1.IsEquivalentTo(tree2))
Assert.True(node1.IsEquivalentTo(node2))
' tree3 is identical to tree1 except for a single comment.
Dim tree3 = SyntaxFactory.ParseSyntaxTree(
<text>
Imports System
Module Program
' Additional comment.
Sub Main()
Dim i = 0.0
i += 1 + 2L
End Sub
End Module
</text>.Value)
Dim node3 As SyntaxNode = tree3.GetRoot()
' Compare trees and nodes that are identical except for trivia.
Assert.True(tree1.IsEquivalentTo(tree3)) ' Trivia differences are ignored.
Assert.False(node1.IsEquivalentTo(node3)) ' Trivia differences are considered.
' tree4 is identical to tree1 except for method body contents.
Dim tree4 = SyntaxFactory.ParseSyntaxTree(
<text>
Imports System
Module Program
Sub Main()
End Sub
End Module
</text>.Value)
Dim node4 As SyntaxNode = tree4.GetRoot()
' Compare trees and nodes that are identical at the top-level.
Assert.True(tree1.IsEquivalentTo(tree4, topLevel:=True)) ' Only top-level nodes are considered.
Assert.False(node1.IsEquivalentTo(node4)) ' Non-top-level nodes are considered.
' Tokens and Trivia can also be compared.
Dim token1 As SyntaxToken = node1.DescendantTokens.First
Dim token2 As SyntaxToken = node2.DescendantTokens.First
Assert.True(token1.IsEquivalentTo(token2))
Dim trivia1 As SyntaxTrivia = node1.DescendantTrivia().First(Function(t) t.Kind() = SyntaxKind.WhitespaceTrivia)
Dim trivia2 As SyntaxTrivia = node2.DescendantTrivia().Last(Function(t) t.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.False(trivia1.IsEquivalentTo(trivia2))
End Sub
<FAQ(29)>
<Fact>
Public Sub TraverseAllCommentsInASyntaxTreeUsingAWalker()
Dim tree = SyntaxFactory.ParseSyntaxTree(
<text>
Imports System
''' <summary>First Comment</summary>
Module Program
' Second Comment
Sub Main()
' Third Comment
End Sub
End Module
</text>.Value)
Dim walker As New CommentWalker()
walker.Visit(tree.GetRoot())
Assert.Equal(
<text>
''' <summary>First Comment</summary> (Parent Token: ModuleKeyword) (Structured)
' Second Comment (Parent Token: SubKeyword)
' Third Comment (Parent Token: EndKeyword)</text>.Value, walker.Results.ToString())
End Sub
' Below SyntaxWalker traverses all comments present under the SyntaxNode being visited.
Public Class CommentWalker
Inherits VisualBasicSyntaxWalker
Public Property Results As New StringBuilder()
Public Sub New()
MyBase.New(SyntaxWalkerDepth.StructuredTrivia)
End Sub
Public Overrides Sub VisitTrivia(trivia As SyntaxTrivia)
If trivia.Kind() = SyntaxKind.CommentTrivia OrElse trivia.Kind() = SyntaxKind.DocumentationCommentTrivia Then
Results.Append(vbLf)
Results.Append(trivia.ToFullString().Trim())
Results.Append(" (Parent Token: ")
Results.Append(trivia.Token.Kind.ToString())
Results.Append(")")
If trivia.Kind() = SyntaxKind.DocumentationCommentTrivia Then
' Trivia for xml documentation comments have additional 'structure'
' available under a child DocumentationCommentSyntax.
Assert.True(trivia.HasStructure)
Dim documentationComment = CType(trivia.GetStructure(), DocumentationCommentTriviaSyntax)
Assert.True(documentationComment.ParentTrivia = trivia)
Results.Append(" (Structured)")
End If
End If
MyBase.VisitTrivia(trivia)
End Sub
End Class
<FAQ(12)>
<Fact>
Public Sub CompareSymbols()
Dim tree = SyntaxFactory.ParseSyntaxTree(
<text>
Imports System
Class C
End Class
Module Program
Public Sub Main()
Dim c = New C()
Console.WriteLine(c.ToString())
End Sub
End Module
</text>.Value)
Dim vbOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithEmbedVbCoreRuntime(True)
Dim comp = VisualBasicCompilation.Create("MyCompilation", syntaxTrees:={tree}, references:={Mscorlib}, options:=vbOptions)
Dim model = comp.GetSemanticModel(tree)
' Get ModifiedIdentifierSyntax corresponding to the identifier 'c' in the statement 'Dim c = ...' above.
Dim identifier As ModifiedIdentifierSyntax = tree.GetRoot().
DescendantNodes.
OfType(Of VariableDeclaratorSyntax).
Single.
Names.
Single
' Get TypeSymbol corresponding to 'Dim c' above.
Dim type As ITypeSymbol = CType(model.GetDeclaredSymbol(identifier), ILocalSymbol).Type
Dim expectedType As ITypeSymbol = comp.GetTypeByMetadataName("C")
Assert.True(type.Equals(expectedType))
End Sub
<FAQ(13)>
<Fact>
Public Sub TestWhetherANodeIsPartOfATreeOrASemanticModel()
Dim source = <text>
Imports System
Class C
End Class
Module Program
Public Sub Main()
Dim c = New C()
Console.WriteLine(c.ToString())
End Sub
End Module
</text>.Value
Dim tree = SyntaxFactory.ParseSyntaxTree(source)
Dim other = SyntaxFactory.ParseSyntaxTree(source)
Dim vbOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithEmbedVbCoreRuntime(True)
Dim comp = VisualBasicCompilation.Create("MyCompilation", syntaxTrees:={tree}, references:={Mscorlib}, options:=vbOptions)
Dim model = comp.GetSemanticModel(tree)
Dim nodeFromTree As SyntaxNode = tree.GetRoot()
Dim tokenNotFromTree As SyntaxToken = SyntaxFactory.Token(SyntaxKind.ClassKeyword)
Dim nodeNotFromTree As SyntaxNode = other.GetRoot()
Assert.True(nodeFromTree.SyntaxTree Is tree)
Assert.True(nodeFromTree.SyntaxTree Is model.SyntaxTree)
Assert.False(tokenNotFromTree.SyntaxTree Is tree)
Assert.False(nodeNotFromTree.SyntaxTree Is model.SyntaxTree)
Assert.True(nodeNotFromTree.SyntaxTree Is other)
End Sub
<FAQ(14)>
<Fact>
Public Sub ValueVersusValueTextVersusGetTextForTokens()
Dim source = <text>
Imports System
Module Program
Public Sub Main()
Dim [long] = 1L
Console.WriteLine([long])
End Sub
End Module
</text>.Value
Dim tree = SyntaxFactory.ParseSyntaxTree(source)
' Get token corresponding to identifier '[long]' above.
Dim token1 As SyntaxToken = tree.GetRoot().FindToken(source.IndexOf("[long]"))
' Get token corresponding to literal '1L' above.
Dim token2 As SyntaxToken = tree.GetRoot().FindToken(source.IndexOf("1L"))
Assert.Equal("String", token1.Value.GetType().Name)
Assert.Equal("long", token1.Value)
Assert.Equal("long", token1.ValueText)
Assert.Equal("[long]", token1.ToString())
Assert.Equal("Int64", token2.Value.GetType().Name)
Assert.Equal(1L, token2.Value)
Assert.Equal("1", token2.ValueText)
Assert.Equal("1L", token2.ToString())
End Sub
<FAQ(16)>
<Fact>
Public Sub GetLineAndColumnInfo()
Dim tree = SyntaxFactory.ParseSyntaxTree(
<text>
Module Program
Public Sub Main()
End Sub
End Module
</text>.Value, path:="MyCodeFile.vb")
' Get MethodBlockSyntax corresponding to the method block for 'Sub Main()' above.
Dim node As MethodBlockSyntax = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockSyntax).Single
' Use GetLocation() and GetLineSpan() to get file, line and column info for above BlockSyntax.
Dim location As Location = node.GetLocation()
Dim lineSpan As FileLinePositionSpan = location.GetLineSpan()
Assert.True(location.IsInSource)
Assert.Equal("MyCodeFile.vb", lineSpan.Path)
Assert.Equal(3, lineSpan.StartLinePosition.Line)
Assert.Equal(4, lineSpan.StartLinePosition.Character)
' Alternate way to get file, line and column info from any span.
location = tree.GetLocation(node.Span)
lineSpan = location.GetLineSpan()
Assert.Equal("MyCodeFile.vb", lineSpan.Path)
Assert.Equal(3, lineSpan.StartLinePosition.Line)
Assert.Equal(4, lineSpan.StartLinePosition.Character)
' Yet another way to get file, line and column info from any span.
lineSpan = tree.GetLineSpan(node.Span)
Assert.Equal("MyCodeFile.vb", lineSpan.Path)
Assert.Equal(4, lineSpan.EndLinePosition.Line)
Assert.Equal(11, lineSpan.EndLinePosition.Character)
' SyntaxTokens also have GetLocation().
' Use GetLocation() to get the position of the 'Public' token under the above MethodBlockSyntax.