-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathCSharpCompilation.cs
3724 lines (3179 loc) · 153 KB
/
CSharpCompilation.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.
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CSharp.Binder;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The compilation object is an immutable representation of a single invocation of the
/// compiler. Although immutable, a compilation is also on-demand, and will realize and cache
/// data as necessary. A compilation can produce a new compilation from existing compilation
/// with the application of small deltas. In many cases, it is more efficient than creating a
/// new compilation from scratch, as the new compilation can reuse information from the old
/// compilation.
/// </summary>
public sealed partial class CSharpCompilation : Compilation
{
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// Changes to the public interface of this class should remain synchronized with the VB
// version. Do not make any changes to the public interface without making the corresponding
// change to the VB version.
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions();
private readonly CSharpCompilationOptions _options;
private readonly Lazy<Imports> _globalImports;
private readonly Lazy<Imports> _previousSubmissionImports;
private readonly Lazy<AliasSymbol> _globalNamespaceAlias; // alias symbol used to resolve "global::".
private readonly Lazy<ImplicitNamedTypeSymbol?> _scriptClass;
// All imports (using directives and extern aliases) in syntax trees in this compilation.
// NOTE: We need to de-dup since the Imports objects that populate the list may be GC'd
// and re-created.
private ConcurrentSet<ImportInfo>? _lazyImportInfos;
// Cache the CLS diagnostics for the whole compilation so they aren't computed repeatedly.
// NOTE: Presently, we do not cache the per-tree diagnostics.
private ImmutableArray<Diagnostic> _lazyClsComplianceDiagnostics;
private Conversions? _conversions;
internal Conversions Conversions
{
get
{
if (_conversions == null)
{
Interlocked.CompareExchange(ref _conversions, new BuckStopsHereBinder(this).Conversions, null);
}
return _conversions;
}
}
/// <summary>
/// Manages anonymous types declared in this compilation. Unifies types that are structurally equivalent.
/// </summary>
private readonly AnonymousTypeManager _anonymousTypeManager;
private NamespaceSymbol? _lazyGlobalNamespace;
internal readonly BuiltInOperators builtInOperators;
/// <summary>
/// The <see cref="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 SourceAssemblySymbol? _lazyAssemblySymbol;
/// <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 _referenceManager;
private readonly SyntaxAndDeclarationManager _syntaxAndDeclarations;
/// <summary>
/// Contains the main method of this assembly, if there is one.
/// </summary>
private EntryPoint? _lazyEntryPoint;
/// <summary>
/// Emit nullable attributes for only those members that are visible outside the assembly
/// (public, protected, and if any [InternalsVisibleTo] attributes, internal members).
/// If false, attributes are emitted for all members regardless of visibility.
/// </summary>
private ThreeState _lazyEmitNullablePublicOnly;
/// <summary>
/// The set of trees for which a <see cref="CompilationUnitCompletedEvent"/> has been added to the queue.
/// </summary>
private HashSet<SyntaxTree>? _lazyCompilationUnitCompletedTrees;
/// <summary>
/// Run the nullable walker during the flow analysis passes. True if the project-level nullable
/// context option is set, or if any file enables nullable or just the nullable warnings.
/// </summary>
private ThreeState _lazyShouldRunNullableWalker;
public override string Language
{
get
{
return LanguageNames.CSharp;
}
}
public override bool IsCaseSensitive
{
get
{
return true;
}
}
/// <summary>
/// The options the compilation was created with.
/// </summary>
public new CSharpCompilationOptions Options
{
get
{
return _options;
}
}
internal AnonymousTypeManager AnonymousTypeManager
{
get
{
return _anonymousTypeManager;
}
}
internal override CommonAnonymousTypeManager CommonAnonymousTypeManager
{
get
{
return AnonymousTypeManager;
}
}
/// <summary>
/// True when the compiler is run in "strict" mode, in which it enforces the language specification
/// in some cases even at the expense of full compatibility. Such differences typically arise when
/// earlier versions of the compiler failed to enforce the full language specification.
/// </summary>
internal bool FeatureStrictEnabled => Feature("strict") != null;
/// <summary>
/// True if we should enable nullable semantic analysis in this compilation.
/// </summary>
internal bool NullableSemanticAnalysisEnabled
{
get
{
var nullableAnalysisFlag = Feature("run-nullable-analysis");
if (nullableAnalysisFlag == "false")
{
return false;
}
return ShouldRunNullableWalker || nullableAnalysisFlag == "true";
}
}
/// <summary>
/// True when the "peverify-compat" feature flag is set or the language version is below C# 7.2.
/// With this flag we will avoid certain patterns known not be compatible with PEVerify.
/// The code may be less efficient and may deviate from spec in corner cases.
/// The flag is only to be used if PEVerify pass is extremely important.
/// </summary>
internal bool IsPeVerifyCompatEnabled => LanguageVersion < LanguageVersion.CSharp7_2 || Feature("peverify-compat") != null;
internal bool ShouldRunNullableWalker
{
get
{
if (!_lazyShouldRunNullableWalker.HasValue())
{
if (Options.NullableContextOptions != NullableContextOptions.Disable)
{
_lazyShouldRunNullableWalker = ThreeState.True;
return true;
}
foreach (var syntaxTree in SyntaxTrees)
{
if (((CSharpSyntaxTree)syntaxTree).HasNullableEnables())
{
_lazyShouldRunNullableWalker = ThreeState.True;
return true;
}
}
_lazyShouldRunNullableWalker = ThreeState.False;
}
return _lazyShouldRunNullableWalker.Value();
}
}
/// <summary>
/// The language version that was used to parse the syntax trees of this compilation.
/// </summary>
public LanguageVersion LanguageVersion
{
get;
}
protected override INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol container, string name, int arity)
{
return new ExtendedErrorTypeSymbol(
container.EnsureCSharpSymbolOrNull(nameof(container)),
name, arity, errorInfo: null).GetPublicSymbol();
}
protected override INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name)
{
return new MissingNamespaceSymbol(
container.EnsureCSharpSymbolOrNull(nameof(container)),
name).GetPublicSymbol();
}
#region Constructors and Factories
private static readonly CSharpCompilationOptions s_defaultOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication);
private static readonly CSharpCompilationOptions s_defaultSubmissionOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithReferencesSupersedeLowerVersions(true);
/// <summary>
/// Creates a new compilation from scratch. Methods such as AddSyntaxTrees or AddReferences
/// on the returned object will allow to continue building up the Compilation incrementally.
/// </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 static CSharpCompilation Create(
string assemblyName,
IEnumerable<SyntaxTree>? syntaxTrees = null,
IEnumerable<MetadataReference>? references = null,
CSharpCompilationOptions? options = null)
{
return Create(
assemblyName,
options ?? s_defaultOptions,
syntaxTrees,
references,
previousSubmission: null,
returnType: null,
hostObjectType: null,
isSubmission: false);
}
/// <summary>
/// Creates a new compilation that can be used in scripting.
/// </summary>
public static CSharpCompilation CreateScriptCompilation(
string assemblyName,
SyntaxTree? syntaxTree = null,
IEnumerable<MetadataReference>? references = null,
CSharpCompilationOptions? options = null,
CSharpCompilation? previousScriptCompilation = null,
Type? returnType = null,
Type? globalsType = null)
{
CheckSubmissionOptions(options);
ValidateScriptCompilationParameters(previousScriptCompilation, returnType, ref globalsType);
return Create(
assemblyName,
options?.WithReferencesSupersedeLowerVersions(true) ?? s_defaultSubmissionOptions,
(syntaxTree != null) ? new[] { syntaxTree } : SpecializedCollections.EmptyEnumerable<SyntaxTree>(),
references,
previousScriptCompilation,
returnType,
globalsType,
isSubmission: true);
}
private static CSharpCompilation Create(
string? assemblyName,
CSharpCompilationOptions options,
IEnumerable<SyntaxTree>? syntaxTrees,
IEnumerable<MetadataReference>? references,
CSharpCompilation? previousSubmission,
Type? returnType,
Type? hostObjectType,
bool isSubmission)
{
RoslynDebug.Assert(options != null);
Debug.Assert(!isSubmission || options.ReferencesSupersedeLowerVersions);
var validatedReferences = ValidateReferences<CSharpCompilationReference>(references);
// We can't reuse the whole Reference Manager entirely (reuseReferenceManager = false)
// because the set of references of this submission differs from the previous one.
// The submission inherits references of the previous submission, adds the previous submission reference
// and may add more references passed explicitly or via #r.
//
// TODO: Consider reusing some results of the assembly binding to improve perf
// since most of the binding work is similar.
var compilation = new CSharpCompilation(
assemblyName,
options,
validatedReferences,
previousSubmission,
returnType,
hostObjectType,
isSubmission,
referenceManager: null,
reuseReferenceManager: false,
syntaxAndDeclarations: new SyntaxAndDeclarationManager(
ImmutableArray<SyntaxTree>.Empty,
options.ScriptClassName,
options.SourceReferenceResolver,
CSharp.MessageProvider.Instance,
isSubmission,
state: null));
if (syntaxTrees != null)
{
compilation = compilation.AddSyntaxTrees(syntaxTrees);
}
Debug.Assert(compilation._lazyAssemblySymbol is null);
return compilation;
}
private CSharpCompilation(
string? assemblyName,
CSharpCompilationOptions options,
ImmutableArray<MetadataReference> references,
CSharpCompilation? previousSubmission,
Type? submissionReturnType,
Type? hostObjectType,
bool isSubmission,
ReferenceManager? referenceManager,
bool reuseReferenceManager,
SyntaxAndDeclarationManager syntaxAndDeclarations,
AsyncQueue<CompilationEvent>? eventQueue = null)
: this(assemblyName, options, references, previousSubmission, submissionReturnType, hostObjectType, isSubmission, referenceManager, reuseReferenceManager, syntaxAndDeclarations, SyntaxTreeCommonFeatures(syntaxAndDeclarations.ExternalSyntaxTrees), eventQueue)
{
}
private CSharpCompilation(
string? assemblyName,
CSharpCompilationOptions options,
ImmutableArray<MetadataReference> references,
CSharpCompilation? previousSubmission,
Type? submissionReturnType,
Type? hostObjectType,
bool isSubmission,
ReferenceManager? referenceManager,
bool reuseReferenceManager,
SyntaxAndDeclarationManager syntaxAndDeclarations,
IReadOnlyDictionary<string, string> features,
AsyncQueue<CompilationEvent>? eventQueue = null)
: base(assemblyName, references, features, isSubmission, eventQueue)
{
WellKnownMemberSignatureComparer = new WellKnownMembersSignatureComparer(this);
_options = options;
this.builtInOperators = new BuiltInOperators(this);
_scriptClass = new Lazy<ImplicitNamedTypeSymbol?>(BindScriptClass);
_globalImports = new Lazy<Imports>(BindGlobalImports);
_previousSubmissionImports = new Lazy<Imports>(ExpandPreviousSubmissionImports);
_globalNamespaceAlias = new Lazy<AliasSymbol>(CreateGlobalNamespaceAlias);
_anonymousTypeManager = new AnonymousTypeManager(this);
this.LanguageVersion = CommonLanguageVersion(syntaxAndDeclarations.ExternalSyntaxTrees);
if (isSubmission)
{
Debug.Assert(previousSubmission == null || previousSubmission.HostObjectType == hostObjectType);
this.ScriptCompilationInfo = new CSharpScriptCompilationInfo(previousSubmission, submissionReturnType, hostObjectType);
}
else
{
Debug.Assert(previousSubmission == null && submissionReturnType == null && hostObjectType == null);
}
if (reuseReferenceManager)
{
if (referenceManager is null)
{
throw new ArgumentNullException(nameof(referenceManager));
}
referenceManager.AssertCanReuseForCompilation(this);
_referenceManager = referenceManager;
}
else
{
_referenceManager = new ReferenceManager(
MakeSourceAssemblySimpleName(),
this.Options.AssemblyIdentityComparer,
observedMetadata: referenceManager?.ObservedMetadata);
}
_syntaxAndDeclarations = syntaxAndDeclarations;
Debug.Assert(_lazyAssemblySymbol is null);
if (EventQueue != null) EventQueue.TryEnqueue(new CompilationStartedEvent(this));
}
internal override void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics)
{
Debug.Assert(debugEntryPoint != null);
// Debug entry point has to be a method definition from this compilation.
var methodSymbol = (debugEntryPoint as Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol;
if (methodSymbol?.DeclaringCompilation != this || !methodSymbol.IsDefinition)
{
diagnostics.Add(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition, Location.None);
}
}
private static LanguageVersion CommonLanguageVersion(ImmutableArray<SyntaxTree> syntaxTrees)
{
LanguageVersion? result = null;
foreach (var tree in syntaxTrees)
{
var version = ((CSharpParseOptions)tree.Options).LanguageVersion;
if (result == null)
{
result = version;
}
else if (result != version)
{
throw new ArgumentException(CodeAnalysisResources.InconsistentLanguageVersions, nameof(syntaxTrees));
}
}
return result ?? LanguageVersion.Default.MapSpecifiedToEffectiveVersion();
}
/// <summary>
/// Create a duplicate of this compilation with different symbol instances.
/// </summary>
public new CSharpCompilation Clone()
{
return new CSharpCompilation(
this.AssemblyName,
_options,
this.ExternalReferences,
this.PreviousSubmission,
this.SubmissionReturnType,
this.HostObjectType,
this.IsSubmission,
_referenceManager,
reuseReferenceManager: true,
syntaxAndDeclarations: _syntaxAndDeclarations);
}
private CSharpCompilation Update(
ReferenceManager referenceManager,
bool reuseReferenceManager,
SyntaxAndDeclarationManager syntaxAndDeclarations)
{
return new CSharpCompilation(
this.AssemblyName,
_options,
this.ExternalReferences,
this.PreviousSubmission,
this.SubmissionReturnType,
this.HostObjectType,
this.IsSubmission,
referenceManager,
reuseReferenceManager,
syntaxAndDeclarations);
}
/// <summary>
/// Creates a new compilation with the specified name.
/// </summary>
public new CSharpCompilation WithAssemblyName(string? assemblyName)
{
// 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 CSharpCompilation(
assemblyName,
_options,
this.ExternalReferences,
this.PreviousSubmission,
this.SubmissionReturnType,
this.HostObjectType,
this.IsSubmission,
_referenceManager,
reuseReferenceManager: assemblyName == this.AssemblyName,
syntaxAndDeclarations: _syntaxAndDeclarations);
}
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
/// <remarks>
/// The new <see cref="CSharpCompilation"/> 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 new CSharpCompilation WithReferences(IEnumerable<MetadataReference>? references)
{
// References might have changed, don't reuse reference manager.
// Don't even reuse observed metadata - let the manager query for the metadata again.
return new CSharpCompilation(
this.AssemblyName,
_options,
ValidateReferences<CSharpCompilationReference>(references),
this.PreviousSubmission,
this.SubmissionReturnType,
this.HostObjectType,
this.IsSubmission,
referenceManager: null,
reuseReferenceManager: false,
syntaxAndDeclarations: _syntaxAndDeclarations);
}
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
public new CSharpCompilation WithReferences(params MetadataReference[] references)
{
return this.WithReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new compilation with the specified compilation options.
/// </summary>
public CSharpCompilation WithOptions(CSharpCompilationOptions options)
{
var oldOptions = this.Options;
bool reuseReferenceManager = oldOptions.CanReuseCompilationReferenceManager(options);
bool reuseSyntaxAndDeclarationManager = oldOptions.ScriptClassName == options.ScriptClassName &&
oldOptions.SourceReferenceResolver == options.SourceReferenceResolver;
return new CSharpCompilation(
this.AssemblyName,
options,
this.ExternalReferences,
this.PreviousSubmission,
this.SubmissionReturnType,
this.HostObjectType,
this.IsSubmission,
_referenceManager,
reuseReferenceManager,
reuseSyntaxAndDeclarationManager ?
_syntaxAndDeclarations :
new SyntaxAndDeclarationManager(
_syntaxAndDeclarations.ExternalSyntaxTrees,
options.ScriptClassName,
options.SourceReferenceResolver,
_syntaxAndDeclarations.MessageProvider,
_syntaxAndDeclarations.IsSubmission,
state: null));
}
/// <summary>
/// Returns a new compilation with the given compilation set as the previous submission.
/// </summary>
public CSharpCompilation WithScriptCompilationInfo(CSharpScriptCompilationInfo? info)
{
if (info == ScriptCompilationInfo)
{
return this;
}
// Reference binding doesn't depend on previous submission so we can reuse it.
return new CSharpCompilation(
this.AssemblyName,
_options,
this.ExternalReferences,
info?.PreviousScriptCompilation,
info?.ReturnTypeOpt,
info?.GlobalsType,
info != null,
_referenceManager,
reuseReferenceManager: true,
syntaxAndDeclarations: _syntaxAndDeclarations);
}
/// <summary>
/// Returns a new compilation with a given event queue.
/// </summary>
internal override Compilation WithEventQueue(AsyncQueue<CompilationEvent>? eventQueue)
{
return new CSharpCompilation(
this.AssemblyName,
_options,
this.ExternalReferences,
this.PreviousSubmission,
this.SubmissionReturnType,
this.HostObjectType,
this.IsSubmission,
_referenceManager,
reuseReferenceManager: true,
syntaxAndDeclarations: _syntaxAndDeclarations,
eventQueue: eventQueue);
}
#endregion
#region Submission
public new CSharpScriptCompilationInfo? ScriptCompilationInfo { get; }
internal override ScriptCompilationInfo? CommonScriptCompilationInfo => ScriptCompilationInfo;
internal CSharpCompilation? PreviousSubmission => ScriptCompilationInfo?.PreviousScriptCompilation;
internal override bool HasSubmissionResult()
{
Debug.Assert(IsSubmission);
// A submission may be empty or comprised of a single script file.
var tree = _syntaxAndDeclarations.ExternalSyntaxTrees.SingleOrDefault();
if (tree == null)
{
return false;
}
var root = tree.GetCompilationUnitRoot();
if (root.HasErrors)
{
return false;
}
// Are there any top-level return statements?
if (root.DescendantNodes(n => n is GlobalStatementSyntax || n is StatementSyntax || n is CompilationUnitSyntax).Any(n => n.IsKind(SyntaxKind.ReturnStatement)))
{
return true;
}
// Is there a trailing expression?
var lastGlobalStatement = (GlobalStatementSyntax)root.Members.LastOrDefault(m => m.IsKind(SyntaxKind.GlobalStatement));
if (lastGlobalStatement != null)
{
var statement = lastGlobalStatement.Statement;
if (statement.IsKind(SyntaxKind.ExpressionStatement))
{
var expressionStatement = (ExpressionStatementSyntax)statement;
if (expressionStatement.SemicolonToken.IsMissing)
{
var model = GetSemanticModel(tree);
var expression = expressionStatement.Expression;
var info = model.GetTypeInfo(expression);
return info.ConvertedType?.SpecialType != SpecialType.System_Void;
}
}
}
return false;
}
#endregion
#region Syntax Trees (maintain an ordered list)
/// <summary>
/// The syntax trees (parsed from source code) that this compilation was created with.
/// </summary>
public new ImmutableArray<SyntaxTree> SyntaxTrees
{
get { return _syntaxAndDeclarations.GetLazyState().SyntaxTrees; }
}
/// <summary>
/// Returns true if this compilation contains the specified tree. False otherwise.
/// </summary>
public new bool ContainsSyntaxTree(SyntaxTree? syntaxTree)
{
return syntaxTree != null && _syntaxAndDeclarations.GetLazyState().RootNamespaces.ContainsKey(syntaxTree);
}
/// <summary>
/// Creates a new compilation with additional syntax trees.
/// </summary>
public new CSharpCompilation AddSyntaxTrees(params SyntaxTree[] trees)
{
return AddSyntaxTrees((IEnumerable<SyntaxTree>)trees);
}
/// <summary>
/// Creates a new compilation with additional syntax trees.
/// </summary>
public new CSharpCompilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees)
{
if (trees == null)
{
throw new ArgumentNullException(nameof(trees));
}
if (trees.IsEmpty())
{
return this;
}
// This HashSet is needed so that we don't allow adding the same tree twice
// with a single call to AddSyntaxTrees. Rather than using a separate HashSet,
// ReplaceSyntaxTrees can just check against ExternalSyntaxTrees, because we
// only allow replacing a single tree at a time.
var externalSyntaxTrees = PooledHashSet<SyntaxTree>.GetInstance();
var syntaxAndDeclarations = _syntaxAndDeclarations;
externalSyntaxTrees.AddAll(syntaxAndDeclarations.ExternalSyntaxTrees);
bool reuseReferenceManager = true;
int i = 0;
foreach (var tree in trees.Cast<CSharpSyntaxTree>())
{
if (tree == null)
{
throw new ArgumentNullException($"{nameof(trees)}[{i}]");
}
if (!tree.HasCompilationUnitRoot)
{
throw new ArgumentException(CSharpResources.TreeMustHaveARootNodeWith, $"{nameof(trees)}[{i}]");
}
if (externalSyntaxTrees.Contains(tree))
{
throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, $"{nameof(trees)}[{i}]");
}
if (this.IsSubmission && tree.Options.Kind == SourceCodeKind.Regular)
{
throw new ArgumentException(CSharpResources.SubmissionCanOnlyInclude, $"{nameof(trees)}[{i}]");
}
externalSyntaxTrees.Add(tree);
reuseReferenceManager &= !tree.HasReferenceOrLoadDirectives;
i++;
}
externalSyntaxTrees.Free();
if (this.IsSubmission && i > 1)
{
throw new ArgumentException(CSharpResources.SubmissionCanHaveAtMostOne, nameof(trees));
}
syntaxAndDeclarations = syntaxAndDeclarations.AddSyntaxTrees(trees);
return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations);
}
/// <summary>
/// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
/// added later.
/// </summary>
public new CSharpCompilation RemoveSyntaxTrees(params SyntaxTree[] trees)
{
return RemoveSyntaxTrees((IEnumerable<SyntaxTree>)trees);
}
/// <summary>
/// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
/// added later.
/// </summary>
public new CSharpCompilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
{
if (trees == null)
{
throw new ArgumentNullException(nameof(trees));
}
if (trees.IsEmpty())
{
return this;
}
var removeSet = PooledHashSet<SyntaxTree>.GetInstance();
// This HashSet is needed so that we don't allow adding the same tree twice
// with a single call to AddSyntaxTrees. Rather than using a separate HashSet,
// ReplaceSyntaxTrees can just check against ExternalSyntaxTrees, because we
// only allow replacing a single tree at a time.
var externalSyntaxTrees = PooledHashSet<SyntaxTree>.GetInstance();
var syntaxAndDeclarations = _syntaxAndDeclarations;
externalSyntaxTrees.AddAll(syntaxAndDeclarations.ExternalSyntaxTrees);
bool reuseReferenceManager = true;
int i = 0;
foreach (var tree in trees.Cast<CSharpSyntaxTree>())
{
if (!externalSyntaxTrees.Contains(tree))
{
// Check to make sure this is not a #load'ed tree.
var loadedSyntaxTreeMap = syntaxAndDeclarations.GetLazyState().LoadedSyntaxTreeMap;
if (SyntaxAndDeclarationManager.IsLoadedSyntaxTree(tree, loadedSyntaxTreeMap))
{
throw new ArgumentException(CSharpResources.SyntaxTreeFromLoadNoRemoveReplace, $"{nameof(trees)}[{i}]");
}
throw new ArgumentException(CSharpResources.SyntaxTreeNotFoundToRemove, $"{nameof(trees)}[{i}]");
}
removeSet.Add(tree);
reuseReferenceManager &= !tree.HasReferenceOrLoadDirectives;
i++;
}
externalSyntaxTrees.Free();
syntaxAndDeclarations = syntaxAndDeclarations.RemoveSyntaxTrees(removeSet);
removeSet.Free();
return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations);
}
/// <summary>
/// Creates a new compilation without any syntax trees. Preserves metadata info
/// from this compilation for use with trees added later.
/// </summary>
public new CSharpCompilation RemoveAllSyntaxTrees()
{
var syntaxAndDeclarations = _syntaxAndDeclarations;
return Update(
_referenceManager,
reuseReferenceManager: !syntaxAndDeclarations.MayHaveReferenceDirectives(),
syntaxAndDeclarations: syntaxAndDeclarations.WithExternalSyntaxTrees(ImmutableArray<SyntaxTree>.Empty));
}
/// <summary>
/// Creates a new compilation without the old tree but with the new tree.
/// </summary>
public new CSharpCompilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree? newTree)
{
// this is just to force a cast exception
oldTree = (CSharpSyntaxTree)oldTree;
newTree = (CSharpSyntaxTree?)newTree;
if (oldTree == null)
{
throw new ArgumentNullException(nameof(oldTree));
}
if (newTree == null)
{
return this.RemoveSyntaxTrees(oldTree);
}
else if (newTree == oldTree)
{
return this;
}
if (!newTree.HasCompilationUnitRoot)
{
throw new ArgumentException(CSharpResources.TreeMustHaveARootNodeWith, nameof(newTree));
}
var syntaxAndDeclarations = _syntaxAndDeclarations;
var externalSyntaxTrees = syntaxAndDeclarations.ExternalSyntaxTrees;
if (!externalSyntaxTrees.Contains(oldTree))
{
// Check to see if this is a #load'ed tree.
var loadedSyntaxTreeMap = syntaxAndDeclarations.GetLazyState().LoadedSyntaxTreeMap;
if (SyntaxAndDeclarationManager.IsLoadedSyntaxTree(oldTree, loadedSyntaxTreeMap))
{
throw new ArgumentException(CSharpResources.SyntaxTreeFromLoadNoRemoveReplace, nameof(oldTree));
}
throw new ArgumentException(CSharpResources.SyntaxTreeNotFoundToRemove, nameof(oldTree));
}
if (externalSyntaxTrees.Contains(newTree))
{
throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, nameof(newTree));
}
// TODO(tomat): Consider comparing #r's of the old and the new tree. If they are exactly the same we could still reuse.
// This could be a perf win when editing a script file in the IDE. The services create a new compilation every keystroke
// that replaces the tree with a new one.
var reuseReferenceManager = !oldTree.HasReferenceOrLoadDirectives() && !newTree.HasReferenceOrLoadDirectives();
syntaxAndDeclarations = syntaxAndDeclarations.ReplaceSyntaxTree(oldTree, newTree);
return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations);
}
internal override int GetSyntaxTreeOrdinal(SyntaxTree tree)
{
Debug.Assert(this.ContainsSyntaxTree(tree));
return _syntaxAndDeclarations.GetLazyState().OrdinalMap[tree];
}
#endregion
#region References
internal override CommonReferenceManager CommonGetBoundReferenceManager()
{
return GetBoundReferenceManager();
}
internal new ReferenceManager GetBoundReferenceManager()
{
if (_lazyAssemblySymbol is null)
{
_referenceManager.CreateSourceAssemblyForCompilation(this);
Debug.Assert(_lazyAssemblySymbol is object);
}
// referenceManager can only be accessed after we initialized the lazyAssemblySymbol.
// In fact, initialization of the assembly symbol might change the reference manager.
return _referenceManager;
}
// for testing only:
internal bool ReferenceManagerEquals(CSharpCompilation other)
{
return ReferenceEquals(_referenceManager, other._referenceManager);
}
public override ImmutableArray<MetadataReference> DirectiveReferences
{
get
{
return GetBoundReferenceManager().DirectiveReferences;
}
}
internal override IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap
=> GetBoundReferenceManager().ReferenceDirectiveMap;
// for testing purposes
internal IEnumerable<string> ExternAliases
{
get
{
return GetBoundReferenceManager().ExternAliases;
}
}
/// <summary>
/// Gets the <see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> for a metadata reference used to create this compilation.
/// </summary>
/// <returns><see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> corresponding to the given reference or null if there is none.</returns>
/// <remarks>
/// Uses object identity when comparing two references.
/// </remarks>
internal new Symbol? GetAssemblyOrModuleSymbol(MetadataReference reference)
{
if (reference == null)
{
throw new ArgumentNullException(nameof(reference));
}
if (reference.Properties.Kind == MetadataImageKind.Assembly)
{
return GetBoundReferenceManager().GetReferencedAssemblySymbol(reference);
}
else
{
Debug.Assert(reference.Properties.Kind == MetadataImageKind.Module);
int index = GetBoundReferenceManager().GetReferencedModuleIndex(reference);
return index < 0 ? null : this.Assembly.Modules[index];
}
}
public override IEnumerable<AssemblyIdentity> ReferencedAssemblyNames
{
get