-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Compilation.cs
3438 lines (2972 loc) · 143 KB
/
Compilation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <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 abstract partial class Compilation
{
/// <summary>
/// Returns true if this is a case sensitive compilation, false otherwise. Case sensitivity
/// affects compilation features such as name lookup as well as choosing what names to emit
/// when there are multiple different choices (for example between a virtual method and an
/// override).
/// </summary>
public abstract bool IsCaseSensitive { get; }
/// <summary>
/// Used for test purposes only to emulate missing members.
/// </summary>
private SmallDictionary<int, bool>? _lazyMakeWellKnownTypeMissingMap;
/// <summary>
/// Used for test purposes only to emulate missing members.
/// </summary>
private SmallDictionary<int, bool>? _lazyMakeMemberMissingMap;
// Protected for access in CSharpCompilation.WithAdditionalFeatures
protected readonly IReadOnlyDictionary<string, string> _features;
public ScriptCompilationInfo? ScriptCompilationInfo => CommonScriptCompilationInfo;
internal abstract ScriptCompilationInfo? CommonScriptCompilationInfo { get; }
internal Compilation(
string? name,
ImmutableArray<MetadataReference> references,
IReadOnlyDictionary<string, string> features,
bool isSubmission,
SemanticModelProvider? semanticModelProvider,
AsyncQueue<CompilationEvent>? eventQueue)
{
RoslynDebug.Assert(!references.IsDefault);
RoslynDebug.Assert(features != null);
this.AssemblyName = name;
this.ExternalReferences = references;
this.SemanticModelProvider = semanticModelProvider;
this.EventQueue = eventQueue;
_lazySubmissionSlotIndex = isSubmission ? SubmissionSlotIndexToBeAllocated : SubmissionSlotIndexNotApplicable;
_features = features;
}
protected static IReadOnlyDictionary<string, string> SyntaxTreeCommonFeatures(IEnumerable<SyntaxTree> trees)
{
IReadOnlyDictionary<string, string>? set = null;
foreach (var tree in trees)
{
var treeFeatures = tree.Options.Features;
if (set == null)
{
set = treeFeatures;
}
else
{
if ((object)set != treeFeatures && !set.SetEquals(treeFeatures))
{
throw new ArgumentException(CodeAnalysisResources.InconsistentSyntaxTreeFeature, nameof(trees));
}
}
}
if (set == null)
{
// Edge case where there are no syntax trees
set = ImmutableDictionary<string, string>.Empty;
}
return set;
}
internal abstract AnalyzerDriver CreateAnalyzerDriver(ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerManager analyzerManager, SeverityFilter severityFilter);
/// <summary>
/// Gets the source language ("C#" or "Visual Basic").
/// </summary>
public abstract string Language { get; }
internal abstract void SerializePdbEmbeddedCompilationOptions(BlobBuilder builder);
internal static void ValidateScriptCompilationParameters(Compilation? previousScriptCompilation, Type? returnType, ref Type? globalsType)
{
if (globalsType != null && !IsValidHostObjectType(globalsType))
{
throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeValuePointerbyRefOrOpen, nameof(globalsType));
}
if (returnType != null && !IsValidSubmissionReturnType(returnType))
{
throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeVoidByRefOrOpen, nameof(returnType));
}
if (previousScriptCompilation != null)
{
if (globalsType == null)
{
globalsType = previousScriptCompilation.HostObjectType;
}
else if (globalsType != previousScriptCompilation.HostObjectType)
{
throw new ArgumentException(CodeAnalysisResources.TypeMustBeSameAsHostObjectTypeOfPreviousSubmission, nameof(globalsType));
}
// Force the previous submission to be analyzed. This is required for anonymous types unification.
if (previousScriptCompilation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error))
{
throw new InvalidOperationException(CodeAnalysisResources.PreviousSubmissionHasErrors);
}
}
}
/// <summary>
/// Checks options passed to submission compilation constructor.
/// Throws an exception if the options are not applicable to submissions.
/// </summary>
internal static void CheckSubmissionOptions(CompilationOptions? options)
{
if (options == null)
{
return;
}
if (options.OutputKind.IsValid() && options.OutputKind != OutputKind.DynamicallyLinkedLibrary)
{
throw new ArgumentException(CodeAnalysisResources.InvalidOutputKindForSubmission, nameof(options));
}
if (options.CryptoKeyContainer != null ||
options.CryptoKeyFile != null ||
options.DelaySign != null ||
!options.CryptoPublicKey.IsEmpty ||
(options.DelaySign == true && options.PublicSign))
{
throw new ArgumentException(CodeAnalysisResources.InvalidCompilationOptions, nameof(options));
}
}
/// <summary>
/// Creates a new compilation equivalent to this one with different symbol instances.
/// </summary>
public Compilation Clone()
{
return CommonClone();
}
protected abstract Compilation CommonClone();
/// <summary>
/// Returns a new compilation with a given event queue.
/// </summary>
internal abstract Compilation WithEventQueue(AsyncQueue<CompilationEvent>? eventQueue);
/// <summary>
/// Returns a new compilation with a given semantic model provider.
/// </summary>
internal abstract Compilation WithSemanticModelProvider(SemanticModelProvider semanticModelProvider);
/// <summary>
/// Gets a new <see cref="SemanticModel"/> for the specified syntax tree.
/// </summary>
/// <param name="syntaxTree">The specified syntax tree.</param>
/// <param name="ignoreAccessibility">
/// True if the SemanticModel should ignore accessibility rules when answering semantic questions.
/// </param>
public SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility = false)
=> CommonGetSemanticModel(syntaxTree, ignoreAccessibility);
/// <summary>
/// Gets a <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>.
/// If <see cref="SemanticModelProvider"/> is non-null, it attempts to use <see cref="SemanticModelProvider.GetSemanticModel(SyntaxTree, Compilation, bool)"/>
/// to get a semantic model. Otherwise, it creates a new semantic model using <see cref="CreateSemanticModel(SyntaxTree, bool)"/>.
/// </summary>
/// <param name="syntaxTree"></param>
/// <param name="ignoreAccessibility"></param>
/// <returns></returns>
protected abstract SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility);
/// <summary>
/// Creates a new <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>.
/// Unlike the <see cref="GetSemanticModel(SyntaxTree, bool)"/> and <see cref="CommonGetSemanticModel(SyntaxTree, bool)"/>,
/// it does not attempt to use the <see cref="SemanticModelProvider"/> to get a semantic model, but instead always creates a new semantic model.
/// </summary>
/// <param name="syntaxTree"></param>
/// <param name="ignoreAccessibility"></param>
/// <returns></returns>
internal abstract SemanticModel CreateSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility);
/// <summary>
/// Returns a new INamedTypeSymbol representing an error type with the given name and arity
/// in the given optional container.
/// </summary>
public INamedTypeSymbol CreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (arity < 0)
{
throw new ArgumentException($"{nameof(arity)} must be >= 0", nameof(arity));
}
return CommonCreateErrorTypeSymbol(container, name, arity);
}
protected abstract INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity);
/// <summary>
/// Returns a new INamespaceSymbol representing an error (missing) namespace with the given name.
/// </summary>
public INamespaceSymbol CreateErrorNamespaceSymbol(INamespaceSymbol container, string name)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return CommonCreateErrorNamespaceSymbol(container, name);
}
protected abstract INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name);
#region Name
internal const string UnspecifiedModuleAssemblyName = "?";
/// <summary>
/// Simple assembly name, or null if not specified.
/// </summary>
/// <remarks>
/// The name is used for determining internals-visible-to relationship with referenced assemblies.
///
/// If the compilation represents an assembly the value of <see cref="AssemblyName"/> is its simple name.
///
/// Unless <see cref="CompilationOptions.ModuleName"/> specifies otherwise the module name
/// written to metadata is <see cref="AssemblyName"/> with an extension based upon <see cref="CompilationOptions.OutputKind"/>.
/// </remarks>
public string? AssemblyName { get; }
internal void CheckAssemblyName(DiagnosticBag diagnostics)
{
// We could only allow name == null if OutputKind is Module.
// However, it does no harm that we allow name == null for assemblies as well, so we don't enforce it.
if (this.AssemblyName != null)
{
MetadataHelpers.CheckAssemblyOrModuleName(this.AssemblyName, MessageProvider, MessageProvider.ERR_BadAssemblyName, diagnostics);
}
}
internal string MakeSourceAssemblySimpleName()
{
return AssemblyName ?? UnspecifiedModuleAssemblyName;
}
internal string MakeSourceModuleName()
{
return Options.ModuleName ??
(AssemblyName != null ? AssemblyName + Options.OutputKind.GetDefaultExtension() : UnspecifiedModuleAssemblyName);
}
/// <summary>
/// Creates a compilation with the specified assembly name.
/// </summary>
/// <param name="assemblyName">The new assembly name.</param>
/// <returns>A new compilation.</returns>
public Compilation WithAssemblyName(string? assemblyName)
{
return CommonWithAssemblyName(assemblyName);
}
protected abstract Compilation CommonWithAssemblyName(string? outputName);
#endregion
#region Options
/// <summary>
/// Gets the options the compilation was created with.
/// </summary>
public CompilationOptions Options { get { return CommonOptions; } }
protected abstract CompilationOptions CommonOptions { get; }
/// <summary>
/// Creates a new compilation with the specified compilation options.
/// </summary>
/// <param name="options">The new options.</param>
/// <returns>A new compilation.</returns>
public Compilation WithOptions(CompilationOptions options)
{
return CommonWithOptions(options);
}
protected abstract Compilation CommonWithOptions(CompilationOptions options);
#endregion
#region Submissions
// An index in the submission slot array. Allocated lazily in compilation phase based upon the slot index of the previous submission.
// Special values:
// -1 ... neither this nor previous submissions in the chain allocated a slot (the submissions don't contain code)
// -2 ... the slot of this submission hasn't been determined yet
// -3 ... this is not a submission compilation
private int _lazySubmissionSlotIndex;
private const int SubmissionSlotIndexNotApplicable = -3;
private const int SubmissionSlotIndexToBeAllocated = -2;
/// <summary>
/// True if the compilation represents an interactive submission.
/// </summary>
internal bool IsSubmission
{
get
{
return _lazySubmissionSlotIndex != SubmissionSlotIndexNotApplicable;
}
}
/// <summary>
/// The previous submission, if any, or null.
/// </summary>
private Compilation? PreviousSubmission
{
get
{
return ScriptCompilationInfo?.PreviousScriptCompilation;
}
}
/// <summary>
/// Gets or allocates a runtime submission slot index for this compilation.
/// </summary>
/// <returns>Non-negative integer if this is a submission and it or a previous submission contains code, negative integer otherwise.</returns>
internal int GetSubmissionSlotIndex()
{
if (_lazySubmissionSlotIndex == SubmissionSlotIndexToBeAllocated)
{
// TODO (tomat): remove recursion
int lastSlotIndex = ScriptCompilationInfo!.PreviousScriptCompilation?.GetSubmissionSlotIndex() ?? 0;
_lazySubmissionSlotIndex = HasCodeToEmit() ? lastSlotIndex + 1 : lastSlotIndex;
}
return _lazySubmissionSlotIndex;
}
// The type of interactive submission result requested by the host, or null if this compilation doesn't represent a submission.
//
// The type is resolved to a symbol when the Script's instance ctor symbol is constructed. The symbol needs to be resolved against
// the references of this compilation.
//
// Consider (tomat): As an alternative to Reflection Type we could hold onto any piece of information that lets us
// resolve the type symbol when needed.
/// <summary>
/// The type object that represents the type of submission result the host requested.
/// </summary>
internal Type? SubmissionReturnType => ScriptCompilationInfo?.ReturnTypeOpt;
internal static bool IsValidSubmissionReturnType(Type type)
{
return !(type == typeof(void) || type.IsByRef || type.GetTypeInfo().ContainsGenericParameters);
}
/// <summary>
/// The type of the globals object or null if not specified for this compilation.
/// </summary>
internal Type? HostObjectType => ScriptCompilationInfo?.GlobalsType;
internal static bool IsValidHostObjectType(Type type)
{
var info = type.GetTypeInfo();
return !(info.IsValueType || info.IsPointer || info.IsByRef || info.ContainsGenericParameters);
}
internal abstract bool HasSubmissionResult();
public Compilation WithScriptCompilationInfo(ScriptCompilationInfo? info) => CommonWithScriptCompilationInfo(info);
protected abstract Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo? info);
#endregion
#region Syntax Trees
/// <summary>
/// Gets the syntax trees (parsed from source code) that this compilation was created with.
/// </summary>
public IEnumerable<SyntaxTree> SyntaxTrees { get { return CommonSyntaxTrees; } }
protected abstract IEnumerable<SyntaxTree> CommonSyntaxTrees { get; }
/// <summary>
/// Creates a new compilation with additional syntax trees.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation AddSyntaxTrees(params SyntaxTree[] trees)
{
return CommonAddSyntaxTrees(trees);
}
/// <summary>
/// Creates a new compilation with additional syntax trees.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees)
{
return CommonAddSyntaxTrees(trees);
}
protected abstract Compilation CommonAddSyntaxTrees(IEnumerable<SyntaxTree> trees);
/// <summary>
/// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
/// added later.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveSyntaxTrees(params SyntaxTree[] trees)
{
return CommonRemoveSyntaxTrees(trees);
}
/// <summary>
/// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
/// added later.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
{
return CommonRemoveSyntaxTrees(trees);
}
protected abstract Compilation CommonRemoveSyntaxTrees(IEnumerable<SyntaxTree> trees);
/// <summary>
/// Creates a new compilation without any syntax trees. Preserves metadata info for use with
/// trees added later.
/// </summary>
public Compilation RemoveAllSyntaxTrees()
{
return CommonRemoveAllSyntaxTrees();
}
protected abstract Compilation CommonRemoveAllSyntaxTrees();
/// <summary>
/// Creates a new compilation with an old syntax tree replaced with a new syntax tree.
/// Reuses metadata from old compilation object.
/// </summary>
/// <param name="newTree">The new tree.</param>
/// <param name="oldTree">The old tree.</param>
/// <returns>A new compilation.</returns>
public Compilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree)
{
return CommonReplaceSyntaxTree(oldTree, newTree);
}
protected abstract Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree);
/// <summary>
/// Returns true if this compilation contains the specified tree. False otherwise.
/// </summary>
/// <param name="syntaxTree">A syntax tree.</param>
public bool ContainsSyntaxTree(SyntaxTree syntaxTree)
{
return CommonContainsSyntaxTree(syntaxTree);
}
protected abstract bool CommonContainsSyntaxTree(SyntaxTree? syntaxTree);
/// <summary>
/// Optional semantic model provider for this compilation.
/// </summary>
internal SemanticModelProvider? SemanticModelProvider { get; }
/// <summary>
/// The event queue that this compilation was created with.
/// </summary>
internal AsyncQueue<CompilationEvent>? EventQueue { get; }
#endregion
#region References
internal static ImmutableArray<MetadataReference> ValidateReferences<T>(IEnumerable<MetadataReference>? references)
where T : CompilationReference
{
var result = references.AsImmutableOrEmpty();
for (int i = 0; i < result.Length; i++)
{
var reference = result[i];
if (reference == null)
{
throw new ArgumentNullException($"{nameof(references)}[{i}]");
}
var peReference = reference as PortableExecutableReference;
if (peReference == null && !(reference is T))
{
Debug.Assert(reference is UnresolvedMetadataReference || reference is CompilationReference);
throw new ArgumentException(string.Format(CodeAnalysisResources.ReferenceOfTypeIsInvalid1, reference.GetType()),
$"{nameof(references)}[{i}]");
}
}
return result;
}
internal CommonReferenceManager GetBoundReferenceManager()
{
return CommonGetBoundReferenceManager();
}
internal abstract CommonReferenceManager CommonGetBoundReferenceManager();
/// <summary>
/// Metadata references passed to the compilation constructor.
/// </summary>
public ImmutableArray<MetadataReference> ExternalReferences { get; }
/// <summary>
/// Unique metadata references specified via #r directive in the source code of this compilation.
/// </summary>
public abstract ImmutableArray<MetadataReference> DirectiveReferences { get; }
/// <summary>
/// All reference directives used in this compilation.
/// </summary>
internal abstract IEnumerable<ReferenceDirective> ReferenceDirectives { get; }
/// <summary>
/// Maps values of #r references to resolved metadata references.
/// </summary>
internal abstract IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap { get; }
/// <summary>
/// All metadata references -- references passed to the compilation
/// constructor as well as references specified via #r directives.
/// </summary>
public IEnumerable<MetadataReference> References
{
get
{
foreach (var reference in ExternalReferences)
{
yield return reference;
}
foreach (var reference in DirectiveReferences)
{
yield return reference;
}
}
}
/// <summary>
/// Creates a metadata reference for this compilation.
/// </summary>
/// <param name="aliases">
/// Optional aliases that can be used to refer to the compilation root namespace via extern alias directive.
/// </param>
/// <param name="embedInteropTypes">
/// Embed the COM types from the reference so that the compiled
/// application no longer requires a primary interop assembly (PIA).
/// </param>
public abstract CompilationReference ToMetadataReference(ImmutableArray<string> aliases = default(ImmutableArray<string>), bool embedInteropTypes = false);
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
/// <param name="newReferences">
/// The new references.
/// </param>
/// <returns>A new compilation.</returns>
public Compilation WithReferences(IEnumerable<MetadataReference> newReferences)
{
return this.CommonWithReferences(newReferences);
}
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
/// <param name="newReferences">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation WithReferences(params MetadataReference[] newReferences)
{
return this.WithReferences((IEnumerable<MetadataReference>)newReferences);
}
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
protected abstract Compilation CommonWithReferences(IEnumerable<MetadataReference> newReferences);
/// <summary>
/// Creates a new compilation with additional metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation AddReferences(params MetadataReference[] references)
{
return AddReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new compilation with additional metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation AddReferences(IEnumerable<MetadataReference> references)
{
if (references == null)
{
throw new ArgumentNullException(nameof(references));
}
if (references.IsEmpty())
{
return this;
}
return CommonWithReferences(this.ExternalReferences.Union(references));
}
/// <summary>
/// Creates a new compilation without the specified metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveReferences(params MetadataReference[] references)
{
return RemoveReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new compilation without the specified metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveReferences(IEnumerable<MetadataReference> references)
{
if (references == null)
{
throw new ArgumentNullException(nameof(references));
}
if (references.IsEmpty())
{
return this;
}
var refSet = new HashSet<MetadataReference>(this.ExternalReferences);
//EDMAURER if AddingReferences accepts duplicates, then a consumer supplying a list with
//duplicates to add will not know exactly which to remove. Let them supply a list with
//duplicates here.
foreach (var r in references.Distinct())
{
if (!refSet.Remove(r))
{
throw new ArgumentException(string.Format(CodeAnalysisResources.MetadataRefNotFoundToRemove1, r),
nameof(references));
}
}
return CommonWithReferences(refSet);
}
/// <summary>
/// Creates a new compilation without any metadata references.
/// </summary>
public Compilation RemoveAllReferences()
{
return CommonWithReferences(SpecializedCollections.EmptyEnumerable<MetadataReference>());
}
/// <summary>
/// Creates a new compilation with an old metadata reference replaced with a new metadata
/// reference.
/// </summary>
/// <param name="newReference">The new reference.</param>
/// <param name="oldReference">The old reference.</param>
/// <returns>A new compilation.</returns>
public Compilation ReplaceReference(MetadataReference oldReference, MetadataReference? newReference)
{
if (oldReference == null)
{
throw new ArgumentNullException(nameof(oldReference));
}
if (newReference == null)
{
return this.RemoveReferences(oldReference);
}
return this.RemoveReferences(oldReference).AddReferences(newReference);
}
/// <summary>
/// Gets the <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/> for a metadata reference used to create this
/// compilation.
/// </summary>
/// <param name="reference">The target reference.</param>
/// <returns>
/// Assembly or module symbol corresponding to the given reference or null if there is none.
/// </returns>
public ISymbol? GetAssemblyOrModuleSymbol(MetadataReference reference)
{
return CommonGetAssemblyOrModuleSymbol(reference);
}
protected abstract ISymbol? CommonGetAssemblyOrModuleSymbol(MetadataReference reference);
/// <summary>
/// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol.
/// </summary>
/// <param name="assemblySymbol">The target symbol.</param>
public MetadataReference? GetMetadataReference(IAssemblySymbol assemblySymbol)
{
return CommonGetMetadataReference(assemblySymbol);
}
private protected abstract MetadataReference? CommonGetMetadataReference(IAssemblySymbol assemblySymbol);
/// <summary>
/// Assembly identities of all assemblies directly referenced by this compilation.
/// </summary>
/// <remarks>
/// Includes identities of references passed in the compilation constructor
/// as well as those specified via directives in source code.
/// </remarks>
public abstract IEnumerable<AssemblyIdentity> ReferencedAssemblyNames { get; }
#endregion
#region Symbols
/// <summary>
/// The <see cref="IAssemblySymbol"/> that represents the assembly being created.
/// </summary>
public IAssemblySymbol Assembly { get { return CommonAssembly; } }
protected abstract IAssemblySymbol CommonAssembly { get; }
/// <summary>
/// Gets the <see cref="IModuleSymbol"/> for the module being created by compiling all of
/// the source code.
/// </summary>
public IModuleSymbol SourceModule { get { return CommonSourceModule; } }
protected abstract IModuleSymbol CommonSourceModule { get; }
/// <summary>
/// The root namespace that contains all namespaces and types defined in source code or in
/// referenced metadata, merged into a single namespace hierarchy.
/// </summary>
public INamespaceSymbol GlobalNamespace { get { return CommonGlobalNamespace; } }
protected abstract INamespaceSymbol CommonGlobalNamespace { get; }
/// <summary>
/// Gets the corresponding compilation namespace for the specified module or assembly namespace.
/// </summary>
public INamespaceSymbol? GetCompilationNamespace(INamespaceSymbol namespaceSymbol)
{
return CommonGetCompilationNamespace(namespaceSymbol);
}
protected abstract INamespaceSymbol? CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol);
internal abstract CommonAnonymousTypeManager CommonAnonymousTypeManager { get; }
/// <summary>
/// Returns the Main method that will serves as the entry point of the assembly, if it is
/// executable (and not a script).
/// </summary>
public IMethodSymbol? GetEntryPoint(CancellationToken cancellationToken)
{
return CommonGetEntryPoint(cancellationToken);
}
protected abstract IMethodSymbol? CommonGetEntryPoint(CancellationToken cancellationToken);
/// <summary>
/// Get the symbol for the predefined type from the Cor Library referenced by this
/// compilation.
/// </summary>
public INamedTypeSymbol GetSpecialType(SpecialType specialType)
{
return (INamedTypeSymbol)CommonGetSpecialType(specialType).GetITypeSymbol();
}
/// <summary>
/// Get the symbol for the predefined type member from the COR Library referenced by this compilation.
/// </summary>
internal abstract ISymbolInternal CommonGetSpecialTypeMember(SpecialMember specialMember);
/// <summary>
/// Returns true if the type is System.Type.
/// </summary>
internal abstract bool IsSystemTypeReference(ITypeSymbolInternal type);
private protected abstract INamedTypeSymbolInternal CommonGetSpecialType(SpecialType specialType);
/// <summary>
/// Lookup member declaration in well known type used by this Compilation.
/// </summary>
internal abstract ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member);
/// <summary>
/// Lookup well-known type used by this Compilation.
/// </summary>
internal abstract ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType);
/// <summary>
/// Returns true if the specified type is equal to or derives from System.Attribute well-known type.
/// </summary>
internal abstract bool IsAttributeType(ITypeSymbol type);
/// <summary>
/// The INamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of
/// Error if there was no COR Library in this Compilation.
/// </summary>
public INamedTypeSymbol ObjectType { get { return CommonObjectType; } }
protected abstract INamedTypeSymbol CommonObjectType { get; }
/// <summary>
/// The TypeSymbol for the type 'dynamic' in this Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
public ITypeSymbol DynamicType { get { return CommonDynamicType; } }
protected abstract ITypeSymbol CommonDynamicType { get; }
/// <summary>
/// A symbol representing the script globals type.
/// </summary>
internal ITypeSymbol? ScriptGlobalsType => CommonScriptGlobalsType;
protected abstract ITypeSymbol? CommonScriptGlobalsType { get; }
/// <summary>
/// A symbol representing the implicit Script class. This is null if the class is not
/// defined in the compilation.
/// </summary>
public INamedTypeSymbol? ScriptClass { get { return CommonScriptClass; } }
protected abstract INamedTypeSymbol? CommonScriptClass { get; }
/// <summary>
/// Resolves a symbol that represents script container (Script class). Uses the
/// full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol.
/// </summary>
/// <returns>The Script class symbol or null if it is not defined.</returns>
protected INamedTypeSymbol? CommonBindScriptClass()
{
string scriptClassName = this.Options.ScriptClassName ?? "";
string[] parts = scriptClassName.Split('.');
INamespaceSymbol container = this.SourceModule.GlobalNamespace;
for (int i = 0; i < parts.Length - 1; i++)
{
INamespaceSymbol? next = container.GetNestedNamespace(parts[i]);
if (next == null)
{
AssertNoScriptTrees();
return null;
}
container = next;
}
foreach (INamedTypeSymbol candidate in container.GetTypeMembers(parts[parts.Length - 1]))
{
if (candidate.IsScriptClass)
{
return candidate;
}
}
AssertNoScriptTrees();
return null;
}
[Conditional("DEBUG")]
private void AssertNoScriptTrees()
{
foreach (var tree in this.SyntaxTrees)
{
Debug.Assert(tree.Options.Kind != SourceCodeKind.Script);
}
}
/// <summary>
/// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the
/// COR Library in this Compilation.
/// </summary>
public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1, NullableAnnotation elementNullableAnnotation = NullableAnnotation.None)
{
return CommonCreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation);
}
/// <summary>
/// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the
/// COR Library in this Compilation.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank)
{
return CreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation: default);
}
protected abstract IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation elementNullableAnnotation);
/// <summary>
/// Returns a new IPointerTypeSymbol representing a pointer type tied to a type in this
/// Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
public IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType)
{
return CommonCreatePointerTypeSymbol(pointedAtType);
}
protected abstract IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType);
/// <summary>
/// Returns a new IFunctionPointerTypeSymbol representing a function pointer type tied to types in this
/// Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
/// <exception cref="ArgumentException">
/// If:
/// * <see cref="RefKind.Out"/> is passed as the returnRefKind.
/// * parameterTypes and parameterRefKinds do not have the same length.
/// </exception>
/// <exception cref="ArgumentNullException">
/// If returnType is <see langword="null"/>, or if parameterTypes or parameterRefKinds are default,
/// or if any of the types in parameterTypes are null.</exception>
public IFunctionPointerTypeSymbol CreateFunctionPointerTypeSymbol(
ITypeSymbol returnType,
RefKind returnRefKind,
ImmutableArray<ITypeSymbol> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
SignatureCallingConvention callingConvention = SignatureCallingConvention.Default,
ImmutableArray<INamedTypeSymbol> callingConventionTypes = default)
{
return CommonCreateFunctionPointerTypeSymbol(returnType, returnRefKind, parameterTypes, parameterRefKinds, callingConvention, callingConventionTypes);
}