/
VisualBasicCompilation.vb
3028 lines (2515 loc) · 142 KB
/
VisualBasicCompilation.vb
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.Collections.Concurrent
Imports System.Collections.Immutable
Imports System.IO
Imports System.Reflection.Metadata
Imports System.Runtime.InteropServices
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.InternalUtilities
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The Compilation object is an immutable representation of a single invocation of the
''' compiler. Although immutable, a Compilation is also on-demand, in that a compilation can be
''' created quickly, but will that compiler parts or all of the code in order to respond to
''' method or properties. Also, a compilation can produce a new compilation with a small change
''' from the current compilation. This is, in many cases, more efficient than creating a new
''' compilation from scratch, as the new compilation can share information from the old
''' compilation.
''' </summary>
Public NotInheritable Class VisualBasicCompilation
Inherits Compilation
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'
' Changes to the public interface of this class should remain synchronized with the C#
' version. Do not make any changes to the public interface without making the corresponding
' change to the C# version.
'
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
''' <summary>
''' most of time all compilation would use same MyTemplate. no reason to create (reparse) one for each compilation
''' as long as its parse option is same
''' </summary>
Private Shared ReadOnly s_myTemplateCache As ConcurrentLruCache(Of VisualBasicParseOptions, SyntaxTree) =
New ConcurrentLruCache(Of VisualBasicParseOptions, SyntaxTree)(capacity:=5)
''' <summary>
''' The SourceAssemblySymbol for this compilation. Do not access directly, use Assembly
''' property instead. This field is lazily initialized by ReferenceManager,
''' ReferenceManager.CacheLockObject must be locked while ReferenceManager "calculates" the
''' value and assigns it, several threads must not perform duplicate "calculation"
''' simultaneously.
''' </summary>
Private _lazyAssemblySymbol As SourceAssemblySymbol
''' <summary>
''' Holds onto data related to reference binding.
''' The manager is shared among multiple compilations that we expect to have the same result of reference binding.
''' In most cases this can be determined without performing the binding. If the compilation however contains a circular
''' metadata reference (a metadata reference that refers back to the compilation) we need to avoid sharing of the binding results.
''' We do so by creating a new reference manager for such compilation.
''' </summary>
Private _referenceManager As ReferenceManager
''' <summary>
''' The options passed to the constructor of the Compilation
''' </summary>
Private ReadOnly _options As VisualBasicCompilationOptions
''' <summary>
''' The global namespace symbol. Lazily populated on first access.
''' </summary>
Private _lazyGlobalNamespace As NamespaceSymbol
''' <summary>
''' The syntax trees explicitly given to the compilation at creation, in ordinal order.
''' </summary>
Private ReadOnly _syntaxTrees As ImmutableArray(Of SyntaxTree)
Private ReadOnly _syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer)
''' <summary>
''' The syntax trees of this compilation plus all 'hidden' trees
''' added to the compilation by compiler, e.g. Vb Core Runtime.
''' </summary>
Private _lazyAllSyntaxTrees As ImmutableArray(Of SyntaxTree)
''' <summary>
''' A map between syntax trees and the root declarations in the declaration table.
''' Incrementally updated between compilation versions when source changes are made.
''' </summary>
Private ReadOnly _rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry)
''' <summary>
''' Imports appearing in <see cref="SyntaxTree"/>s in this compilation.
''' </summary>
''' <remarks>
''' Unlike in C#, we don't need to use a set because the <see cref="SourceFile"/> objects
''' that record the imports are persisted.
''' </remarks>
Private _lazyImportInfos As ConcurrentQueue(Of ImportInfo)
''' <summary>
''' Cache the CLS diagnostics for the whole compilation so they aren't computed repeatedly.
''' </summary>
''' <remarks>
''' NOTE: Presently, we do not cache the per-tree diagnostics.
''' </remarks>
Private _lazyClsComplianceDiagnostics As ImmutableArray(Of Diagnostic)
''' <summary>
''' A SyntaxTree and the associated RootSingleNamespaceDeclaration for an embedded
''' syntax tree in the Compilation. Unlike the entries in m_rootNamespaces, the
''' SyntaxTree here is lazy since the tree cannot be evaluated until the references
''' have been resolved (as part of binding the source module), and at that point, the
''' SyntaxTree may be Nothing if the embedded tree is not needed for the Compilation.
''' </summary>
Private Structure EmbeddedTreeAndDeclaration
Public ReadOnly Tree As Lazy(Of SyntaxTree)
Public ReadOnly DeclarationEntry As DeclarationTableEntry
Public Sub New(treeOpt As Func(Of SyntaxTree), rootNamespaceOpt As Func(Of RootSingleNamespaceDeclaration))
Me.Tree = New Lazy(Of SyntaxTree)(treeOpt)
Me.DeclarationEntry = New DeclarationTableEntry(New Lazy(Of RootSingleNamespaceDeclaration)(rootNamespaceOpt), isEmbedded:=True)
End Sub
End Structure
Private ReadOnly _embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration)
''' <summary>
''' The declaration table that holds onto declarations from source. Incrementally updated
''' between compilation versions when source changes are made.
''' </summary>
''' <remarks></remarks>
Private ReadOnly _declarationTable As DeclarationTable
''' <summary>
''' Manages anonymous types declared in this compilation. Unifies types that are structurally equivalent.
''' </summary>
Private ReadOnly _anonymousTypeManager As AnonymousTypeManager
''' <summary>
''' Manages automatically embedded content.
''' </summary>
Private _lazyEmbeddedSymbolManager As EmbeddedSymbolManager
''' <summary>
''' MyTemplate automatically embedded from resource in the compiler.
''' It doesn't feel like it should be managed by EmbeddedSymbolManager
''' because MyTemplate is treated as user code, i.e. can be extended via
''' partial declarations, doesn't require "on-demand" metadata generation, etc.
'''
''' SyntaxTree.Dummy means uninitialized.
''' </summary>
Private _lazyMyTemplate As SyntaxTree = VisualBasicSyntaxTree.Dummy
Private ReadOnly _scriptClass As Lazy(Of ImplicitNamedTypeSymbol)
''' <summary>
''' Contains the main method of this assembly, if there is one.
''' </summary>
Private _lazyEntryPoint As EntryPoint
''' <summary>
''' The set of trees for which a <see cref="CompilationUnitCompletedEvent"/> has been added to the queue.
''' </summary>
Private _lazyCompilationUnitCompletedTrees As HashSet(Of SyntaxTree)
''' <summary>
''' The common language version among the trees of the compilation.
''' </summary>
Private ReadOnly _languageVersion As LanguageVersion
Public Overrides ReadOnly Property Language As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
Public Overrides ReadOnly Property IsCaseSensitive As Boolean
Get
Return False
End Get
End Property
Friend ReadOnly Property Declarations As DeclarationTable
Get
Return _declarationTable
End Get
End Property
Friend ReadOnly Property MergedRootDeclaration As MergedNamespaceDeclaration
Get
Return Declarations.GetMergedRoot(Me)
End Get
End Property
Public Shadows ReadOnly Property Options As VisualBasicCompilationOptions
Get
Return _options
End Get
End Property
''' <summary>
''' The language version that was used to parse the syntax trees of this compilation.
''' </summary>
Public ReadOnly Property LanguageVersion As LanguageVersion
Get
Return _languageVersion
End Get
End Property
Friend ReadOnly Property AnonymousTypeManager As AnonymousTypeManager
Get
Return Me._anonymousTypeManager
End Get
End Property
Friend Overrides ReadOnly Property CommonAnonymousTypeManager As CommonAnonymousTypeManager
Get
Return Me._anonymousTypeManager
End Get
End Property
''' <summary>
''' SyntaxTree of MyTemplate for the compilation. Settable for testing purposes only.
''' </summary>
Friend Property MyTemplate As SyntaxTree
Get
If _lazyMyTemplate Is VisualBasicSyntaxTree.Dummy Then
Dim compilationOptions = Me.Options
If compilationOptions.EmbedVbCoreRuntime OrElse compilationOptions.SuppressEmbeddedDeclarations Then
_lazyMyTemplate = Nothing
Else
' first see whether we can use one from global cache
Dim parseOptions = If(compilationOptions.ParseOptions, VisualBasicParseOptions.Default)
Dim tree As SyntaxTree = Nothing
If s_myTemplateCache.TryGetValue(parseOptions, tree) Then
Debug.Assert(tree IsNot Nothing)
Debug.Assert(tree IsNot VisualBasicSyntaxTree.Dummy)
Debug.Assert(tree.IsMyTemplate)
Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy)
Else
' we need to make one.
Dim text As String = EmbeddedResources.VbMyTemplateText
' The My template regularly makes use of more recent language features. Care is
' taken to ensure these are compatible with 2.0 runtimes so there is no danger
' with allowing the newer syntax here.
Dim options = parseOptions.WithLanguageVersion(LanguageVersion.Default)
tree = VisualBasicSyntaxTree.ParseText(text, options:=options, isMyTemplate:=True)
If tree.GetDiagnostics().Any() Then
Throw ExceptionUtilities.Unreachable
End If
If Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy) Is VisualBasicSyntaxTree.Dummy Then
' set global cache
s_myTemplateCache(parseOptions) = tree
End If
End If
End If
Debug.Assert(_lazyMyTemplate Is Nothing OrElse _lazyMyTemplate.IsMyTemplate)
End If
Return _lazyMyTemplate
End Get
Set(value As SyntaxTree)
Debug.Assert(_lazyMyTemplate Is VisualBasicSyntaxTree.Dummy)
Debug.Assert(value IsNot VisualBasicSyntaxTree.Dummy)
Debug.Assert(value Is Nothing OrElse value.IsMyTemplate)
If value?.GetDiagnostics().Any() Then
Throw ExceptionUtilities.Unreachable
End If
_lazyMyTemplate = value
End Set
End Property
Friend ReadOnly Property EmbeddedSymbolManager As EmbeddedSymbolManager
Get
If _lazyEmbeddedSymbolManager Is Nothing Then
Dim embedded = If(Options.EmbedVbCoreRuntime, EmbeddedSymbolKind.VbCore, EmbeddedSymbolKind.None) Or
If(IncludeInternalXmlHelper(), EmbeddedSymbolKind.XmlHelper, EmbeddedSymbolKind.None)
If embedded <> EmbeddedSymbolKind.None Then
embedded = embedded Or EmbeddedSymbolKind.EmbeddedAttribute
End If
Interlocked.CompareExchange(_lazyEmbeddedSymbolManager, New EmbeddedSymbolManager(embedded), Nothing)
End If
Return _lazyEmbeddedSymbolManager
End Get
End Property
#Region "Constructors and Factories"
''' <summary>
''' Create a new compilation from scratch.
''' </summary>
''' <param name="assemblyName">Simple assembly name.</param>
''' <param name="syntaxTrees">The syntax trees with the source code for the new compilation.</param>
''' <param name="references">The references for the new compilation.</param>
''' <param name="options">The compiler options to use.</param>
''' <returns>A new compilation.</returns>
Public Shared Function Create(
assemblyName As String,
Optional syntaxTrees As IEnumerable(Of SyntaxTree) = Nothing,
Optional references As IEnumerable(Of MetadataReference) = Nothing,
Optional options As VisualBasicCompilationOptions = Nothing
) As VisualBasicCompilation
Return Create(assemblyName,
options,
If(syntaxTrees IsNot Nothing, syntaxTrees.Cast(Of SyntaxTree), Nothing),
references,
previousSubmission:=Nothing,
returnType:=Nothing,
hostObjectType:=Nothing,
isSubmission:=False)
End Function
''' <summary>
''' Creates a new compilation that can be used in scripting.
''' </summary>
Friend Shared Function CreateScriptCompilation(
assemblyName As String,
Optional syntaxTree As SyntaxTree = Nothing,
Optional references As IEnumerable(Of MetadataReference) = Nothing,
Optional options As VisualBasicCompilationOptions = Nothing,
Optional previousScriptCompilation As VisualBasicCompilation = Nothing,
Optional returnType As Type = Nothing,
Optional globalsType As Type = Nothing) As VisualBasicCompilation
CheckSubmissionOptions(options)
ValidateScriptCompilationParameters(previousScriptCompilation, returnType, globalsType)
Return Create(
assemblyName,
If(options, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).WithReferencesSupersedeLowerVersions(True),
If((syntaxTree IsNot Nothing), {syntaxTree}, SpecializedCollections.EmptyEnumerable(Of SyntaxTree)()),
references,
previousScriptCompilation,
returnType,
globalsType,
isSubmission:=True)
End Function
Private Shared Function Create(
assemblyName As String,
options As VisualBasicCompilationOptions,
syntaxTrees As IEnumerable(Of SyntaxTree),
references As IEnumerable(Of MetadataReference),
previousSubmission As VisualBasicCompilation,
returnType As Type,
hostObjectType As Type,
isSubmission As Boolean
) As VisualBasicCompilation
Debug.Assert(Not isSubmission OrElse options.ReferencesSupersedeLowerVersions)
If options Is Nothing Then
options = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication)
End If
Dim validatedReferences = ValidateReferences(Of VisualBasicCompilationReference)(references)
Dim c As VisualBasicCompilation = Nothing
Dim embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c))
Dim declMap = ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)()
Dim declTable = AddEmbeddedTrees(DeclarationTable.Empty, embeddedTrees)
c = New VisualBasicCompilation(
assemblyName,
options,
validatedReferences,
ImmutableArray(Of SyntaxTree).Empty,
ImmutableDictionary.Create(Of SyntaxTree, Integer)(),
declMap,
embeddedTrees,
declTable,
previousSubmission,
returnType,
hostObjectType,
isSubmission,
referenceManager:=Nothing,
reuseReferenceManager:=False)
If syntaxTrees IsNot Nothing Then
c = c.AddSyntaxTrees(syntaxTrees)
End If
Debug.Assert(c._lazyAssemblySymbol Is Nothing)
Return c
End Function
Private Sub New(
assemblyName As String,
options As VisualBasicCompilationOptions,
references As ImmutableArray(Of MetadataReference),
syntaxTrees As ImmutableArray(Of SyntaxTree),
syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer),
rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry),
embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration),
declarationTable As DeclarationTable,
previousSubmission As VisualBasicCompilation,
submissionReturnType As Type,
hostObjectType As Type,
isSubmission As Boolean,
referenceManager As ReferenceManager,
reuseReferenceManager As Boolean,
Optional eventQueue As AsyncQueue(Of CompilationEvent) = Nothing
)
MyBase.New(assemblyName, references, SyntaxTreeCommonFeatures(syntaxTrees), isSubmission, eventQueue)
Debug.Assert(rootNamespaces IsNot Nothing)
Debug.Assert(declarationTable IsNot Nothing)
Debug.Assert(syntaxTrees.All(Function(tree) syntaxTrees(syntaxTreeOrdinalMap(tree)) Is tree))
Debug.Assert(syntaxTrees.SetEquals(rootNamespaces.Keys.AsImmutable(), EqualityComparer(Of SyntaxTree).Default))
Debug.Assert(embeddedTrees.All(Function(treeAndDeclaration) declarationTable.Contains(treeAndDeclaration.DeclarationEntry)))
_options = options
_syntaxTrees = syntaxTrees
_syntaxTreeOrdinalMap = syntaxTreeOrdinalMap
_rootNamespaces = rootNamespaces
_embeddedTrees = embeddedTrees
_declarationTable = declarationTable
_anonymousTypeManager = New AnonymousTypeManager(Me)
_languageVersion = CommonLanguageVersion(syntaxTrees)
_scriptClass = New Lazy(Of ImplicitNamedTypeSymbol)(AddressOf BindScriptClass)
If isSubmission Then
Debug.Assert(previousSubmission Is Nothing OrElse previousSubmission.HostObjectType Is hostObjectType)
Me.ScriptCompilationInfo = New VisualBasicScriptCompilationInfo(previousSubmission, submissionReturnType, hostObjectType)
Else
Debug.Assert(previousSubmission Is Nothing AndAlso submissionReturnType Is Nothing AndAlso hostObjectType Is Nothing)
End If
If reuseReferenceManager Then
referenceManager.AssertCanReuseForCompilation(Me)
_referenceManager = referenceManager
Else
_referenceManager = New ReferenceManager(MakeSourceAssemblySimpleName(),
options.AssemblyIdentityComparer,
If(referenceManager IsNot Nothing, referenceManager.ObservedMetadata, Nothing))
End If
Debug.Assert(_lazyAssemblySymbol Is Nothing)
If Me.EventQueue IsNot Nothing Then
Me.EventQueue.TryEnqueue(New CompilationStartedEvent(Me))
End If
End Sub
Friend Overrides Sub ValidateDebugEntryPoint(debugEntryPoint As IMethodSymbol, diagnostics As DiagnosticBag)
Debug.Assert(debugEntryPoint IsNot Nothing)
' Debug entry point has to be a method definition from this compilation.
Dim methodSymbol = TryCast(debugEntryPoint, MethodSymbol)
If methodSymbol?.DeclaringCompilation IsNot Me OrElse Not methodSymbol.IsDefinition Then
diagnostics.Add(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition, Location.None)
End If
End Sub
Private Function CommonLanguageVersion(syntaxTrees As ImmutableArray(Of SyntaxTree)) As LanguageVersion
' We don't check m_Options.ParseOptions.LanguageVersion for consistency, because
' it isn't consistent in practice. In fact sometimes m_Options.ParseOptions is Nothing.
Dim result As LanguageVersion? = Nothing
For Each tree In syntaxTrees
Dim version = CType(tree.Options, VisualBasicParseOptions).LanguageVersion
If result Is Nothing Then
result = version
ElseIf result <> version Then
Throw New ArgumentException(CodeAnalysisResources.InconsistentLanguageVersions, NameOf(syntaxTrees))
End If
Next
Return If(result, LanguageVersion.Default.MapSpecifiedToEffectiveVersion)
End Function
''' <summary>
''' Create a duplicate of this compilation with different symbol instances
''' </summary>
Public Shadows Function Clone() As VisualBasicCompilation
Return New VisualBasicCompilation(
Me.AssemblyName,
_options,
Me.ExternalReferences,
_syntaxTrees,
_syntaxTreeOrdinalMap,
_rootNamespaces,
_embeddedTrees,
_declarationTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
_referenceManager,
reuseReferenceManager:=True,
eventQueue:=Nothing) ' no event queue when cloning
End Function
Private Function UpdateSyntaxTrees(
syntaxTrees As ImmutableArray(Of SyntaxTree),
syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer),
rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry),
declarationTable As DeclarationTable,
referenceDirectivesChanged As Boolean) As VisualBasicCompilation
Return New VisualBasicCompilation(
Me.AssemblyName,
_options,
Me.ExternalReferences,
syntaxTrees,
syntaxTreeOrdinalMap,
rootNamespaces,
_embeddedTrees,
declarationTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
_referenceManager,
reuseReferenceManager:=Not referenceDirectivesChanged)
End Function
''' <summary>
''' Creates a new compilation with the specified name.
''' </summary>
Public Shadows Function WithAssemblyName(assemblyName As String) As VisualBasicCompilation
' Can't reuse references since the source assembly name changed and the referenced symbols might
' have internals-visible-to relationship with this compilation or they might had a circular reference
' to this compilation.
Return New VisualBasicCompilation(
assemblyName,
Me.Options,
Me.ExternalReferences,
_syntaxTrees,
_syntaxTreeOrdinalMap,
_rootNamespaces,
_embeddedTrees,
_declarationTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
_referenceManager,
reuseReferenceManager:=String.Equals(assemblyName, Me.AssemblyName, StringComparison.Ordinal))
End Function
Public Shadows Function WithReferences(ParamArray newReferences As MetadataReference()) As VisualBasicCompilation
Return WithReferences(DirectCast(newReferences, IEnumerable(Of MetadataReference)))
End Function
''' <summary>
''' Creates a new compilation with the specified references.
''' </summary>
''' <remarks>
''' The new <see cref="VisualBasicCompilation"/> will query the given <see cref="MetadataReference"/> for the underlying
''' metadata as soon as the are needed.
'''
''' The New compilation uses whatever metadata is currently being provided by the <see cref="MetadataReference"/>.
''' E.g. if the current compilation references a metadata file that has changed since the creation of the compilation
''' the New compilation is going to use the updated version, while the current compilation will be using the previous (it doesn't change).
''' </remarks>
Public Shadows Function WithReferences(newReferences As IEnumerable(Of MetadataReference)) As VisualBasicCompilation
Dim declTable = RemoveEmbeddedTrees(_declarationTable, _embeddedTrees)
Dim c As VisualBasicCompilation = Nothing
Dim embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c))
declTable = AddEmbeddedTrees(declTable, embeddedTrees)
' References might have changed, don't reuse reference manager.
' Don't even reuse observed metadata - let the manager query for the metadata again.
c = New VisualBasicCompilation(
Me.AssemblyName,
Me.Options,
ValidateReferences(Of VisualBasicCompilationReference)(newReferences),
_syntaxTrees,
_syntaxTreeOrdinalMap,
_rootNamespaces,
embeddedTrees,
declTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
referenceManager:=Nothing,
reuseReferenceManager:=False)
Return c
End Function
Public Shadows Function WithOptions(newOptions As VisualBasicCompilationOptions) As VisualBasicCompilation
If newOptions Is Nothing Then
Throw New ArgumentNullException(NameOf(newOptions))
End If
Dim c As VisualBasicCompilation = Nothing
Dim embeddedTrees = _embeddedTrees
Dim declTable = _declarationTable
Dim declMap = Me._rootNamespaces
If Not String.Equals(Me.Options.RootNamespace, newOptions.RootNamespace, StringComparison.Ordinal) Then
' If the root namespace was updated we have to update declaration table
' entries for all the syntax trees of the compilation
'
' NOTE: we use case-sensitive comparison so that the new compilation
' gets a root namespace with correct casing
declMap = ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)()
declTable = DeclarationTable.Empty
embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c))
declTable = AddEmbeddedTrees(declTable, embeddedTrees)
Dim discardedReferenceDirectivesChanged As Boolean = False
For Each tree In _syntaxTrees
AddSyntaxTreeToDeclarationMapAndTable(tree, newOptions, Me.IsSubmission, declMap, declTable, discardedReferenceDirectivesChanged) ' declMap and declTable passed ByRef
Next
ElseIf Me.Options.EmbedVbCoreRuntime <> newOptions.EmbedVbCoreRuntime OrElse Me.Options.ParseOptions <> newOptions.ParseOptions Then
declTable = RemoveEmbeddedTrees(declTable, _embeddedTrees)
embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c))
declTable = AddEmbeddedTrees(declTable, embeddedTrees)
End If
c = New VisualBasicCompilation(
Me.AssemblyName,
newOptions,
Me.ExternalReferences,
_syntaxTrees,
_syntaxTreeOrdinalMap,
declMap,
embeddedTrees,
declTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
_referenceManager,
reuseReferenceManager:=_options.CanReuseCompilationReferenceManager(newOptions))
Return c
End Function
''' <summary>
''' Returns a new compilation with the given compilation set as the previous submission.
''' </summary>
Friend Shadows Function WithScriptCompilationInfo(info As VisualBasicScriptCompilationInfo) As VisualBasicCompilation
If info Is ScriptCompilationInfo Then
Return Me
End If
' Reference binding doesn't depend on previous submission so we can reuse it.
Return New VisualBasicCompilation(
Me.AssemblyName,
Me.Options,
Me.ExternalReferences,
_syntaxTrees,
_syntaxTreeOrdinalMap,
_rootNamespaces,
_embeddedTrees,
_declarationTable,
info?.PreviousScriptCompilation,
info?.ReturnTypeOpt,
info?.GlobalsType,
info IsNot Nothing,
_referenceManager,
reuseReferenceManager:=True)
End Function
''' <summary>
''' Returns a new compilation with a given event queue.
''' </summary>
Friend Overrides Function WithEventQueue(eventQueue As AsyncQueue(Of CompilationEvent)) As Compilation
Return New VisualBasicCompilation(
Me.AssemblyName,
Me.Options,
Me.ExternalReferences,
_syntaxTrees,
_syntaxTreeOrdinalMap,
_rootNamespaces,
_embeddedTrees,
_declarationTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
_referenceManager,
reuseReferenceManager:=True,
eventQueue:=eventQueue)
End Function
#End Region
#Region "Submission"
Friend Shadows ReadOnly Property ScriptCompilationInfo As VisualBasicScriptCompilationInfo
Friend Overrides ReadOnly Property CommonScriptCompilationInfo As ScriptCompilationInfo
Get
Return ScriptCompilationInfo
End Get
End Property
Friend Shadows ReadOnly Property PreviousSubmission As VisualBasicCompilation
Get
Return ScriptCompilationInfo?.PreviousScriptCompilation
End Get
End Property
Friend Overrides Function HasSubmissionResult() As Boolean
Debug.Assert(IsSubmission)
' submission can be empty or comprise of a script file
Dim tree = SyntaxTrees.SingleOrDefault()
If tree Is Nothing Then
Return False
End If
Dim root = tree.GetCompilationUnitRoot()
If root.HasErrors Then
Return False
End If
' TODO: look for return statements
' https://github.com/dotnet/roslyn/issues/5773
Dim lastStatement = root.Members.LastOrDefault()
If lastStatement Is Nothing Then
Return False
End If
Dim model = GetSemanticModel(tree)
Select Case lastStatement.Kind
Case SyntaxKind.PrintStatement
Dim expression = DirectCast(lastStatement, PrintStatementSyntax).Expression
Dim info = model.GetTypeInfo(expression)
' always true, even for info.Type = Void
Return True
Case SyntaxKind.ExpressionStatement
Dim expression = DirectCast(lastStatement, ExpressionStatementSyntax).Expression
Dim info = model.GetTypeInfo(expression)
Return info.Type.SpecialType <> SpecialType.System_Void
Case SyntaxKind.CallStatement
Dim expression = DirectCast(lastStatement, CallStatementSyntax).Invocation
Dim info = model.GetTypeInfo(expression)
Return info.Type.SpecialType <> SpecialType.System_Void
Case Else
Return False
End Select
End Function
Friend Function GetSubmissionInitializer() As SynthesizedInteractiveInitializerMethod
Return If(IsSubmission AndAlso ScriptClass IsNot Nothing,
ScriptClass.GetScriptInitializer(),
Nothing)
End Function
#End Region
#Region "Syntax Trees"
''' <summary>
''' Get a read-only list of the syntax trees that this compilation was created with.
''' </summary>
Public Shadows ReadOnly Property SyntaxTrees As ImmutableArray(Of SyntaxTree)
Get
Return _syntaxTrees
End Get
End Property
''' <summary>
''' Get a read-only list of the syntax trees that this compilation was created with PLUS
''' the trees that were automatically added to it, i.e. Vb Core Runtime tree.
''' </summary>
Friend Shadows ReadOnly Property AllSyntaxTrees As ImmutableArray(Of SyntaxTree)
Get
If _lazyAllSyntaxTrees.IsDefault Then
Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance()
builder.AddRange(_syntaxTrees)
For Each embeddedTree In _embeddedTrees
Dim tree = embeddedTree.Tree.Value
If tree IsNot Nothing Then
builder.Add(tree)
End If
Next
ImmutableInterlocked.InterlockedInitialize(_lazyAllSyntaxTrees, builder.ToImmutableAndFree())
End If
Return _lazyAllSyntaxTrees
End Get
End Property
''' <summary>
''' Is the passed in syntax tree in this compilation?
''' </summary>
Public Shadows Function ContainsSyntaxTree(syntaxTree As SyntaxTree) As Boolean
If syntaxTree Is Nothing Then
Throw New ArgumentNullException(NameOf(syntaxTree))
End If
Dim vbtree = syntaxTree
Return vbtree IsNot Nothing AndAlso _rootNamespaces.ContainsKey(vbtree)
End Function
Public Shadows Function AddSyntaxTrees(ParamArray trees As SyntaxTree()) As VisualBasicCompilation
Return AddSyntaxTrees(DirectCast(trees, IEnumerable(Of SyntaxTree)))
End Function
Public Shadows Function AddSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As VisualBasicCompilation
If trees Is Nothing Then
Throw New ArgumentNullException(NameOf(trees))
End If
If Not trees.Any() Then
Return Me
End If
' We're using a try-finally for this builder because there's a test that
' specifically checks for one or more of the argument exceptions below
' and we don't want to see console spew (even though we don't generally
' care about pool "leaks" in exceptional cases). Alternatively, we
' could create a new ArrayBuilder.
Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance()
Try
builder.AddRange(_syntaxTrees)
Dim referenceDirectivesChanged = False
Dim oldTreeCount = _syntaxTrees.Length
Dim ordinalMap = _syntaxTreeOrdinalMap
Dim declMap = _rootNamespaces
Dim declTable = _declarationTable
Dim i = 0
For Each tree As SyntaxTree In trees
If tree Is Nothing Then
Throw New ArgumentNullException(String.Format(VBResources.Trees0, i))
End If
If Not tree.HasCompilationUnitRoot Then
Throw New ArgumentException(String.Format(VBResources.TreesMustHaveRootNode, i))
End If
If tree.IsEmbeddedOrMyTemplateTree() Then
Throw New ArgumentException(VBResources.CannotAddCompilerSpecialTree)
End If
If declMap.ContainsKey(tree) Then
Throw New ArgumentException(VBResources.SyntaxTreeAlreadyPresent, String.Format(VBResources.Trees0, i))
End If
AddSyntaxTreeToDeclarationMapAndTable(tree, _options, Me.IsSubmission, declMap, declTable, referenceDirectivesChanged) ' declMap and declTable passed ByRef
builder.Add(tree)
ordinalMap = ordinalMap.Add(tree, oldTreeCount + i)
i += 1
Next
If IsSubmission AndAlso declMap.Count > 1 Then
Throw New ArgumentException(VBResources.SubmissionCanHaveAtMostOneSyntaxTree, NameOf(trees))
End If
Return UpdateSyntaxTrees(builder.ToImmutable(), ordinalMap, declMap, declTable, referenceDirectivesChanged)
Finally
builder.Free()
End Try
End Function
Private Shared Sub AddSyntaxTreeToDeclarationMapAndTable(
tree As SyntaxTree,
compilationOptions As VisualBasicCompilationOptions,
isSubmission As Boolean,
ByRef declMap As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry),
ByRef declTable As DeclarationTable,
ByRef referenceDirectivesChanged As Boolean
)
Dim entry = New DeclarationTableEntry(New Lazy(Of RootSingleNamespaceDeclaration)(Function() ForTree(tree, compilationOptions, isSubmission)), isEmbedded:=False)
declMap = declMap.Add(tree, entry) ' Callers are responsible for checking for existing entries.
declTable = declTable.AddRootDeclaration(entry)
referenceDirectivesChanged = referenceDirectivesChanged OrElse tree.HasReferenceDirectives
End Sub
Private Shared Function ForTree(tree As SyntaxTree, options As VisualBasicCompilationOptions, isSubmission As Boolean) As RootSingleNamespaceDeclaration
Return DeclarationTreeBuilder.ForTree(tree, options.GetRootNamespaceParts(), If(options.ScriptClassName, ""), isSubmission)
End Function
Public Shadows Function RemoveSyntaxTrees(ParamArray trees As SyntaxTree()) As VisualBasicCompilation
Return RemoveSyntaxTrees(DirectCast(trees, IEnumerable(Of SyntaxTree)))
End Function
Public Shadows Function RemoveSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As VisualBasicCompilation
If trees Is Nothing Then
Throw New ArgumentNullException(NameOf(trees))
End If
If Not trees.Any() Then
Return Me
End If
Dim referenceDirectivesChanged = False
Dim removeSet As New HashSet(Of SyntaxTree)()
Dim declMap = _rootNamespaces
Dim declTable = _declarationTable
For Each tree As SyntaxTree In trees
If tree.IsEmbeddedOrMyTemplateTree() Then
Throw New ArgumentException(VBResources.CannotRemoveCompilerSpecialTree)
End If
RemoveSyntaxTreeFromDeclarationMapAndTable(tree, declMap, declTable, referenceDirectivesChanged)
removeSet.Add(tree)
Next
Debug.Assert(removeSet.Count > 0)
' We're going to have to revise the ordinals of all
' trees after the first one removed, so just build
' a new map.
' CONSIDER: an alternative approach would be to set the map to empty and
' re-calculate it the next time we need it. This might save us time in the
' case where remove calls are made sequentially (rare?).
Dim ordinalMap = ImmutableDictionary.Create(Of SyntaxTree, Integer)()
Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance()
Dim i = 0
For Each tree In _syntaxTrees
If Not removeSet.Contains(tree) Then
builder.Add(tree)
ordinalMap = ordinalMap.Add(tree, i)
i += 1
End If
Next
Return UpdateSyntaxTrees(builder.ToImmutableAndFree(), ordinalMap, declMap, declTable, referenceDirectivesChanged)
End Function
Private Shared Sub RemoveSyntaxTreeFromDeclarationMapAndTable(
tree As SyntaxTree,
ByRef declMap As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry),
ByRef declTable As DeclarationTable,
ByRef referenceDirectivesChanged As Boolean
)
Dim root As DeclarationTableEntry = Nothing
If Not declMap.TryGetValue(tree, root) Then
Throw New ArgumentException(String.Format(VBResources.SyntaxTreeNotFoundToRemove, tree))
End If
declTable = declTable.RemoveRootDeclaration(root)
declMap = declMap.Remove(tree)
referenceDirectivesChanged = referenceDirectivesChanged OrElse tree.HasReferenceDirectives
End Sub
Public Shadows Function RemoveAllSyntaxTrees() As VisualBasicCompilation
Return UpdateSyntaxTrees(ImmutableArray(Of SyntaxTree).Empty,
ImmutableDictionary.Create(Of SyntaxTree, Integer)(),
ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)(),
AddEmbeddedTrees(DeclarationTable.Empty, _embeddedTrees),
referenceDirectivesChanged:=_declarationTable.ReferenceDirectives.Any())
End Function
Public Shadows Function ReplaceSyntaxTree(oldTree As SyntaxTree, newTree As SyntaxTree) As VisualBasicCompilation
If oldTree Is Nothing Then
Throw New ArgumentNullException(NameOf(oldTree))
End If
If newTree Is Nothing Then
Return Me.RemoveSyntaxTrees(oldTree)
ElseIf newTree Is oldTree Then
Return Me
End If
If Not newTree.HasCompilationUnitRoot Then
Throw New ArgumentException(VBResources.TreeMustHaveARootNodeWithCompilationUnit, NameOf(newTree))
End If
Dim vbOldTree = oldTree
Dim vbNewTree = newTree
If vbOldTree.IsEmbeddedOrMyTemplateTree() Then
Throw New ArgumentException(VBResources.CannotRemoveCompilerSpecialTree)
End If
If vbNewTree.IsEmbeddedOrMyTemplateTree() Then
Throw New ArgumentException(VBResources.CannotAddCompilerSpecialTree)