forked from dotnet/roslyn
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRetargetingSymbolTranslator.cs
More file actions
1382 lines (1140 loc) · 61.7 KB
/
RetargetingSymbolTranslator.cs
File metadata and controls
1382 lines (1140 loc) · 61.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
internal enum RetargetOptions : byte
{
RetargetPrimitiveTypesByName = 0,
RetargetPrimitiveTypesByTypeCode = 1,
}
internal partial class RetargetingModuleSymbol
{
/// <summary>
/// Retargeting map from underlying module to this one.
/// </summary>
private readonly ConcurrentDictionary<Symbol, Symbol> _symbolMap =
new ConcurrentDictionary<Symbol, Symbol>(concurrencyLevel: 2, capacity: 4);
private readonly Func<Symbol, RetargetingMethodSymbol> _createRetargetingMethod;
private readonly Func<Symbol, RetargetingNamespaceSymbol> _createRetargetingNamespace;
private readonly Func<Symbol, RetargetingTypeParameterSymbol> _createRetargetingTypeParameter;
private readonly Func<Symbol, RetargetingNamedTypeSymbol> _createRetargetingNamedType;
private readonly Func<Symbol, FieldSymbol> _createRetargetingField;
private readonly Func<Symbol, RetargetingPropertySymbol> _createRetargetingProperty;
private readonly Func<Symbol, RetargetingEventSymbol> _createRetargetingEvent;
private RetargetingMethodSymbol CreateRetargetingMethod(Symbol symbol)
{
Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule));
return new RetargetingMethodSymbol(this, (MethodSymbol)symbol);
}
private RetargetingNamespaceSymbol CreateRetargetingNamespace(Symbol symbol)
{
Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule));
return new RetargetingNamespaceSymbol(this, (NamespaceSymbol)symbol);
}
private RetargetingNamedTypeSymbol CreateRetargetingNamedType(Symbol symbol)
{
Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule));
return new RetargetingNamedTypeSymbol(this, (NamedTypeSymbol)symbol);
}
private FieldSymbol CreateRetargetingField(Symbol symbol)
{
Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule));
if (symbol is TupleErrorFieldSymbol tupleErrorField)
{
var correspondingTupleField = tupleErrorField.CorrespondingTupleField;
Debug.Assert(correspondingTupleField is TupleErrorFieldSymbol);
var retargetedCorrespondingDefaultFieldOpt = (correspondingTupleField == (object)tupleErrorField)
? null
: (TupleErrorFieldSymbol)RetargetingTranslator.Retarget(correspondingTupleField);
return new TupleErrorFieldSymbol(
RetargetingTranslator.Retarget(tupleErrorField.ContainingType, RetargetOptions.RetargetPrimitiveTypesByName),
tupleErrorField.Name,
tupleErrorField.TupleElementIndex,
tupleErrorField.Locations.IsEmpty ? null : tupleErrorField.Locations[0],
this.RetargetingTranslator.Retarget(tupleErrorField.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode),
tupleErrorField.GetUseSiteInfo().DiagnosticInfo,
tupleErrorField.IsImplicitlyDeclared,
retargetedCorrespondingDefaultFieldOpt);
}
return new RetargetingFieldSymbol(this, (FieldSymbol)symbol);
}
private RetargetingPropertySymbol CreateRetargetingProperty(Symbol symbol)
{
Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule));
return new RetargetingPropertySymbol(this, (PropertySymbol)symbol);
}
private RetargetingEventSymbol CreateRetargetingEvent(Symbol symbol)
{
Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule));
return new RetargetingEventSymbol(this, (EventSymbol)symbol);
}
private RetargetingTypeParameterSymbol CreateRetargetingTypeParameter(Symbol symbol)
{
Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule));
return new RetargetingTypeParameterSymbol(this, (TypeParameterSymbol)symbol);
}
internal class RetargetingSymbolTranslator
: CSharpSymbolVisitor<RetargetOptions, Symbol>
{
private readonly RetargetingModuleSymbol _retargetingModule;
public RetargetingSymbolTranslator(RetargetingModuleSymbol retargetingModule)
{
Debug.Assert((object)retargetingModule != null);
_retargetingModule = retargetingModule;
}
/// <summary>
/// Retargeting map from underlying module to the retargeting module.
/// </summary>
private ConcurrentDictionary<Symbol, Symbol> SymbolMap
{
get
{
return _retargetingModule._symbolMap;
}
}
/// <summary>
/// RetargetingAssemblySymbol owning retargetingModule.
/// </summary>
private RetargetingAssemblySymbol RetargetingAssembly
{
get
{
return _retargetingModule._retargetingAssembly;
}
}
/// <summary>
/// The underlying ModuleSymbol for retargetingModule.
/// </summary>
private SourceModuleSymbol UnderlyingModule
{
get
{
return _retargetingModule._underlyingModule;
}
}
/// <summary>
/// The map that captures information about what assembly should be retargeted
/// to what assembly. Key is the AssemblySymbol referenced by the underlying module,
/// value is the corresponding AssemblySymbol referenced by the retargeting module, and
/// corresponding retargeting map for symbols.
/// </summary>
private Dictionary<AssemblySymbol, DestinationData> RetargetingAssemblyMap
{
get
{
return _retargetingModule._retargetingAssemblyMap;
}
}
public Symbol Retarget(Symbol symbol)
{
Debug.Assert(symbol.Kind != SymbolKind.NamedType || ((NamedTypeSymbol)symbol).PrimitiveTypeCode == Cci.PrimitiveTypeCode.NotPrimitive);
return symbol.Accept(this, RetargetOptions.RetargetPrimitiveTypesByName);
}
public MarshalPseudoCustomAttributeData Retarget(MarshalPseudoCustomAttributeData marshallingInfo)
{
// Retarget by type code - primitive types are encoded in short form in an attribute signature:
return marshallingInfo?.WithTranslatedTypes<TypeSymbol, RetargetingSymbolTranslator>(
(type, translator) => translator.Retarget(type, RetargetOptions.RetargetPrimitiveTypesByTypeCode), this);
}
public TypeSymbol Retarget(TypeSymbol symbol, RetargetOptions options)
{
return (TypeSymbol)symbol.Accept(this, options);
}
public TypeWithAnnotations Retarget(TypeWithAnnotations underlyingType, RetargetOptions options, NamedTypeSymbol asDynamicIfNoPiaContainingType = null)
{
var newTypeSymbol = Retarget(underlyingType.Type, options);
if ((object)asDynamicIfNoPiaContainingType != null)
{
newTypeSymbol = newTypeSymbol.AsDynamicIfNoPia(asDynamicIfNoPiaContainingType);
}
bool modifiersHaveChanged;
var newModifiers = RetargetModifiers(underlyingType.CustomModifiers, out modifiersHaveChanged);
if (modifiersHaveChanged || !TypeSymbol.Equals(underlyingType.Type, newTypeSymbol, TypeCompareKind.ConsiderEverything2))
{
return underlyingType.WithTypeAndModifiers(newTypeSymbol, newModifiers);
}
return underlyingType;
}
public NamespaceSymbol Retarget(NamespaceSymbol ns)
{
return (NamespaceSymbol)this.SymbolMap.GetOrAdd(ns, _retargetingModule._createRetargetingNamespace);
}
private NamedTypeSymbol RetargetNamedTypeDefinition(NamedTypeSymbol type, RetargetOptions options)
{
Debug.Assert(type.IsDefinition);
if (type.IsNativeIntegerType)
{
var result = RetargetNamedTypeDefinition(type.NativeIntegerUnderlyingType, options);
return result.SpecialType == SpecialType.None ? result : result.AsNativeInteger();
}
// Before we do anything else, check if we need to do special retargeting
// for primitive type references encoded with enum values in metadata signatures.
if (options == RetargetOptions.RetargetPrimitiveTypesByTypeCode)
{
Cci.PrimitiveTypeCode typeCode = type.PrimitiveTypeCode;
if (typeCode != Cci.PrimitiveTypeCode.NotPrimitive)
{
return RetargetingAssembly.GetPrimitiveType(typeCode);
}
}
if (type.Kind == SymbolKind.ErrorType)
{
return Retarget((ErrorTypeSymbol)type);
}
AssemblySymbol retargetFrom = type.ContainingAssembly;
// Deal with "to be local" NoPia types leaking through source module.
// These are the types that are coming from assemblies linked (/l-ed)
// by the compilation that created the source module.
bool isLocalType;
if (ReferenceEquals(retargetFrom, this.RetargetingAssembly.UnderlyingAssembly))
{
Debug.Assert(!retargetFrom.IsLinked);
isLocalType = type.IsExplicitDefinitionOfNoPiaLocalType;
}
else
{
isLocalType = retargetFrom.IsLinked;
}
if (isLocalType)
{
return RetargetNoPiaLocalType(type);
}
// Perform general retargeting.
if (ReferenceEquals(retargetFrom, this.RetargetingAssembly.UnderlyingAssembly))
{
return RetargetNamedTypeDefinitionFromUnderlyingAssembly(type);
}
// Does this type come from one of the retargeted assemblies?
DestinationData destination;
if (!this.RetargetingAssemblyMap.TryGetValue(retargetFrom, out destination))
{
// No need to retarget
return type;
}
// Retarget from one assembly to another
type = PerformTypeRetargeting(ref destination, type);
this.RetargetingAssemblyMap[retargetFrom] = destination;
return type;
}
private NamedTypeSymbol RetargetNamedTypeDefinitionFromUnderlyingAssembly(NamedTypeSymbol type)
{
// The type is defined in the underlying assembly.
var module = type.ContainingModule;
if (ReferenceEquals(module, this.UnderlyingModule))
{
Debug.Assert(module.Ordinal == 0);
Debug.Assert(!type.IsExplicitDefinitionOfNoPiaLocalType);
var container = type.ContainingType;
while ((object)container != null)
{
if (container.IsExplicitDefinitionOfNoPiaLocalType)
{
// Types nested into local types are not supported.
return (NamedTypeSymbol)this.SymbolMap.GetOrAdd(type, new UnsupportedMetadataTypeSymbol());
}
container = container.ContainingType;
}
return (NamedTypeSymbol)this.SymbolMap.GetOrAdd(type, _retargetingModule._createRetargetingNamedType);
}
else
{
// The type is defined in one of the added modules
Debug.Assert(module.Ordinal > 0);
PEModuleSymbol addedModule = (PEModuleSymbol)this.RetargetingAssembly.Modules[module.Ordinal];
Debug.Assert(ReferenceEquals(((PEModuleSymbol)module).Module, addedModule.Module));
return RetargetNamedTypeDefinition((PENamedTypeSymbol)type, addedModule);
}
}
private NamedTypeSymbol RetargetNoPiaLocalType(NamedTypeSymbol type)
{
NamedTypeSymbol cached;
var map = this.RetargetingAssembly.NoPiaUnificationMap;
if (map.TryGetValue(type, out cached))
{
return cached;
}
NamedTypeSymbol result;
if (type.ContainingSymbol.Kind != SymbolKind.NamedType &&
type.Arity == 0)
{
// Get type's identity
bool isInterface = type.IsInterface;
bool hasGuid = false;
string interfaceGuid = null;
string scope = null;
if (isInterface)
{
// Get type's Guid
hasGuid = type.GetGuidString(out interfaceGuid);
}
MetadataTypeName name = MetadataTypeName.FromFullName(type.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), forcedArity: type.Arity);
string identifier = null;
if ((object)type.ContainingModule == (object)_retargetingModule.UnderlyingModule)
{
// This is a local type explicitly declared in source. Get information from TypeIdentifier attribute.
foreach (var attrData in type.GetAttributes())
{
int signatureIndex = attrData.GetTargetAttributeSignatureIndex(type, AttributeDescription.TypeIdentifierAttribute);
if (signatureIndex != -1)
{
Debug.Assert(signatureIndex == 0 || signatureIndex == 1);
if (signatureIndex == 1 && attrData.CommonConstructorArguments.Length == 2)
{
scope = attrData.CommonConstructorArguments[0].ValueInternal as string;
identifier = attrData.CommonConstructorArguments[1].ValueInternal as string;
}
break;
}
}
}
else
{
Debug.Assert((object)type.ContainingAssembly != (object)RetargetingAssembly.UnderlyingAssembly);
// Note, this logic should match the one in EmbeddedType.Cci.IReference.GetAttributes.
// Here we are trying to predict what attributes we will emit on embedded type, which corresponds the
// type we are retargeting. That function actually emits the attributes.
if (!(hasGuid && isInterface))
{
type.ContainingAssembly.GetGuidString(out scope);
identifier = name.FullName;
}
}
result = MetadataDecoder.SubstituteNoPiaLocalType(
ref name,
isInterface,
type.BaseTypeNoUseSiteDiagnostics,
interfaceGuid,
scope,
identifier,
RetargetingAssembly);
Debug.Assert((object)result != null);
}
else
{
// TODO: report better error?
result = new UnsupportedMetadataTypeSymbol();
}
cached = map.GetOrAdd(type, result);
return cached;
}
private static NamedTypeSymbol RetargetNamedTypeDefinition(PENamedTypeSymbol type, PEModuleSymbol addedModule)
{
Debug.Assert(!type.ContainingModule.Equals(addedModule) &&
ReferenceEquals(((PEModuleSymbol)type.ContainingModule).Module, addedModule.Module));
TypeSymbol cached;
if (addedModule.TypeHandleToTypeMap.TryGetValue(type.Handle, out cached))
{
return (NamedTypeSymbol)cached;
}
NamedTypeSymbol result;
NamedTypeSymbol containingType = type.ContainingType;
MetadataTypeName mdName;
if ((object)containingType != null)
{
// Nested type. We need to retarget
// the enclosing type and then go back and get the type we are interested in.
NamedTypeSymbol scope = RetargetNamedTypeDefinition((PENamedTypeSymbol)containingType, addedModule);
mdName = MetadataTypeName.FromTypeName(type.MetadataName, forcedArity: type.Arity);
result = scope.LookupMetadataType(ref mdName);
Debug.Assert((object)result != null && result.Arity == type.Arity);
}
else
{
string namespaceName = type.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat);
mdName = MetadataTypeName.FromNamespaceAndTypeName(namespaceName, type.MetadataName, forcedArity: type.Arity);
result = addedModule.LookupTopLevelMetadataType(ref mdName);
Debug.Assert(result.Arity == type.Arity);
}
return result;
}
private static NamedTypeSymbol PerformTypeRetargeting(
ref DestinationData destination,
NamedTypeSymbol type)
{
NamedTypeSymbol result;
if (!destination.SymbolMap.TryGetValue(type, out result))
{
// Lookup by name as a TypeRef.
NamedTypeSymbol containingType = type.ContainingType;
NamedTypeSymbol result1;
MetadataTypeName mdName;
if ((object)containingType != null)
{
// This happens if type is a nested class. We need to retarget
// the enclosing class and then go back and get the type we are interested in.
NamedTypeSymbol scope = PerformTypeRetargeting(ref destination, containingType);
mdName = MetadataTypeName.FromTypeName(type.MetadataName, forcedArity: type.Arity);
result1 = scope.LookupMetadataType(ref mdName);
Debug.Assert((object)result1 != null && result1.Arity == type.Arity);
}
else
{
string namespaceName = type.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat);
mdName = MetadataTypeName.FromNamespaceAndTypeName(namespaceName, type.MetadataName, forcedArity: type.Arity);
result1 = destination.To.LookupTopLevelMetadataType(ref mdName, digThroughForwardedTypes: true);
Debug.Assert(result1.Arity == type.Arity);
}
result = destination.SymbolMap.GetOrAdd(type, result1);
Debug.Assert(TypeSymbol.Equals(result1, result, TypeCompareKind.ConsiderEverything2));
}
return result;
}
public NamedTypeSymbol Retarget(NamedTypeSymbol type, RetargetOptions options)
{
NamedTypeSymbol originalDefinition = type.OriginalDefinition;
NamedTypeSymbol newDefinition = RetargetNamedTypeDefinition(originalDefinition, options);
if (ReferenceEquals(type, originalDefinition))
{
return newDefinition;
}
if (newDefinition.Kind == SymbolKind.ErrorType && !newDefinition.IsGenericType)
{
return newDefinition;
}
Debug.Assert(originalDefinition.Arity == 0 || !ReferenceEquals(type.ConstructedFrom, type));
if (type.IsUnboundGenericType)
{
if (ReferenceEquals(newDefinition, originalDefinition))
{
return type;
}
return newDefinition.AsUnboundGenericType();
}
Debug.Assert((object)type.ContainingType == null || !type.ContainingType.IsUnboundGenericType());
// This must be a generic instantiation (i.e. constructed type).
NamedTypeSymbol genericType = type;
var oldArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance();
int startOfNonInterfaceArguments = int.MaxValue;
// Collect generic arguments for the type and its containers.
while ((object)genericType != null)
{
if (startOfNonInterfaceArguments == int.MaxValue &&
!genericType.IsInterface)
{
startOfNonInterfaceArguments = oldArguments.Count;
}
oldArguments.AddRange(genericType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics);
genericType = genericType.ContainingType;
}
bool anythingRetargeted = !originalDefinition.Equals(newDefinition);
// retarget the arguments
var newArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(oldArguments.Count);
foreach (var arg in oldArguments)
{
var newArg = Retarget(arg, RetargetOptions.RetargetPrimitiveTypesByTypeCode); // generic instantiation is a signature
if (!anythingRetargeted && !newArg.IsSameAs(arg))
{
anythingRetargeted = true;
}
newArguments.Add(newArg);
}
// See if it is or its enclosing type is a non-interface closed over NoPia local types.
bool noPiaIllegalGenericInstantiation = IsNoPiaIllegalGenericInstantiation(oldArguments, newArguments, startOfNonInterfaceArguments);
oldArguments.Free();
NamedTypeSymbol constructedType;
if (!anythingRetargeted)
{
// Nothing was retargeted, return original type symbol.
constructedType = type;
}
else
{
// Create symbol for new constructed type and return it.
// need to collect type parameters in the same order as we have arguments,
// but this should be done for the new definition.
genericType = newDefinition;
ArrayBuilder<TypeParameterSymbol> newParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(newArguments.Count);
// Collect generic arguments for the type and its containers.
while ((object)genericType != null)
{
if (genericType.Arity > 0)
{
newParameters.AddRange(genericType.TypeParameters);
}
genericType = genericType.ContainingType;
}
Debug.Assert(newParameters.Count == newArguments.Count);
TypeMap substitution = new TypeMap(newParameters.ToImmutableAndFree(), newArguments.ToImmutable());
constructedType = substitution.SubstituteNamedType(newDefinition).WithTupleDataFrom(type);
}
newArguments.Free();
if (noPiaIllegalGenericInstantiation)
{
return new NoPiaIllegalGenericInstantiationSymbol(_retargetingModule, constructedType);
}
return constructedType;
}
private bool IsNoPiaIllegalGenericInstantiation(ArrayBuilder<TypeWithAnnotations> oldArguments, ArrayBuilder<TypeWithAnnotations> newArguments, int startOfNonInterfaceArguments)
{
// TODO: Do we need to check constraints on type parameters as well?
if (this.UnderlyingModule.ContainsExplicitDefinitionOfNoPiaLocalTypes)
{
for (int i = startOfNonInterfaceArguments; i < oldArguments.Count; i++)
{
if (IsOrClosedOverAnExplicitLocalType(oldArguments[i].Type))
{
return true;
}
}
}
ImmutableArray<AssemblySymbol> assembliesToEmbedTypesFrom = this.UnderlyingModule.GetAssembliesToEmbedTypesFrom();
if (assembliesToEmbedTypesFrom.Length > 0)
{
for (int i = startOfNonInterfaceArguments; i < oldArguments.Count; i++)
{
if (MetadataDecoder.IsOrClosedOverATypeFromAssemblies(oldArguments[i].Type, assembliesToEmbedTypesFrom))
{
return true;
}
}
}
ImmutableArray<AssemblySymbol> linkedAssemblies = RetargetingAssembly.GetLinkedReferencedAssemblies();
if (!linkedAssemblies.IsDefaultOrEmpty)
{
for (int i = startOfNonInterfaceArguments; i < newArguments.Count; i++)
{
if (MetadataDecoder.IsOrClosedOverATypeFromAssemblies(newArguments[i].Type, linkedAssemblies))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Perform a check whether the type or at least one of its generic arguments
/// is an explicitly defined local type. The check is performed recursively.
/// </summary>
private bool IsOrClosedOverAnExplicitLocalType(TypeSymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.TypeParameter:
return false;
case SymbolKind.ArrayType:
return IsOrClosedOverAnExplicitLocalType(((ArrayTypeSymbol)symbol).ElementType);
case SymbolKind.PointerType:
return IsOrClosedOverAnExplicitLocalType(((PointerTypeSymbol)symbol).PointedAtType);
case SymbolKind.DynamicType:
return false;
case SymbolKind.ErrorType:
case SymbolKind.NamedType:
var namedType = (NamedTypeSymbol)symbol;
if ((object)symbol.OriginalDefinition.ContainingModule == (object)_retargetingModule.UnderlyingModule &&
namedType.IsExplicitDefinitionOfNoPiaLocalType)
{
return true;
}
do
{
foreach (var argument in namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics)
{
if (IsOrClosedOverAnExplicitLocalType(argument.Type))
{
return true;
}
}
namedType = namedType.ContainingType;
}
while ((object)namedType != null);
return false;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
public virtual TypeParameterSymbol Retarget(TypeParameterSymbol typeParameter)
{
return (TypeParameterSymbol)this.SymbolMap.GetOrAdd(typeParameter, _retargetingModule._createRetargetingTypeParameter);
}
public ArrayTypeSymbol Retarget(ArrayTypeSymbol type)
{
TypeWithAnnotations oldElement = type.ElementTypeWithAnnotations;
TypeWithAnnotations newElement = Retarget(oldElement, RetargetOptions.RetargetPrimitiveTypesByTypeCode);
if (oldElement.IsSameAs(newElement))
{
return type;
}
if (type.IsSZArray)
{
return ArrayTypeSymbol.CreateSZArray(this.RetargetingAssembly, newElement);
}
return ArrayTypeSymbol.CreateMDArray(this.RetargetingAssembly, newElement, type.Rank, type.Sizes, type.LowerBounds);
}
internal ImmutableArray<CustomModifier> RetargetModifiers(ImmutableArray<CustomModifier> oldModifiers, out bool modifiersHaveChanged)
{
ArrayBuilder<CustomModifier> newModifiers = null;
for (int i = 0; i < oldModifiers.Length; i++)
{
var oldModifier = oldModifiers[i];
NamedTypeSymbol oldModifierSymbol = ((CSharpCustomModifier)oldModifier).ModifierSymbol;
NamedTypeSymbol newModifierSymbol = Retarget(oldModifierSymbol, RetargetOptions.RetargetPrimitiveTypesByName); // should be retargeted by name
if (!newModifierSymbol.Equals(oldModifierSymbol))
{
if (newModifiers == null)
{
newModifiers = ArrayBuilder<CustomModifier>.GetInstance(oldModifiers.Length);
newModifiers.AddRange(oldModifiers, i);
}
newModifiers.Add(oldModifier.IsOptional ?
CSharpCustomModifier.CreateOptional(newModifierSymbol) :
CSharpCustomModifier.CreateRequired(newModifierSymbol));
}
else if (newModifiers != null)
{
newModifiers.Add(oldModifier);
}
}
Debug.Assert(newModifiers == null || newModifiers.Count == oldModifiers.Length);
modifiersHaveChanged = (newModifiers != null);
return modifiersHaveChanged ? newModifiers.ToImmutableAndFree() : oldModifiers;
}
public PointerTypeSymbol Retarget(PointerTypeSymbol type)
{
TypeWithAnnotations oldPointed = type.PointedAtTypeWithAnnotations;
TypeWithAnnotations newPointed = Retarget(oldPointed, RetargetOptions.RetargetPrimitiveTypesByTypeCode);
if (oldPointed.IsSameAs(newPointed))
{
return type;
}
return new PointerTypeSymbol(newPointed);
}
public FunctionPointerTypeSymbol Retarget(FunctionPointerTypeSymbol type)
{
var signature = type.Signature;
var newReturn = Retarget(signature.ReturnTypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode);
var newRefModifiers = RetargetModifiers(signature.RefCustomModifiers, out bool symbolModified);
symbolModified = symbolModified || !signature.ReturnTypeWithAnnotations.IsSameAs(newReturn);
var newParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty;
ImmutableArray<ImmutableArray<CustomModifier>> newParamModifiers = default;
var paramCount = signature.ParameterCount;
if (paramCount > 0)
{
var newParameterTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(paramCount);
var newParameterCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(paramCount);
bool parametersModified = false;
foreach (var parameter in signature.Parameters)
{
var newParameterType = Retarget(parameter.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode);
var newModifiers = RetargetModifiers(parameter.RefCustomModifiers, out bool customModifiersChanged);
newParameterTypesBuilder.Add(newParameterType);
newParameterCustomModifiersBuilder.Add(newModifiers);
parametersModified = parametersModified || !parameter.TypeWithAnnotations.IsSameAs(newParameterType) || customModifiersChanged;
}
if (parametersModified)
{
newParameterTypes = newParameterTypesBuilder.ToImmutableAndFree();
newParamModifiers = newParameterCustomModifiersBuilder.ToImmutableAndFree();
symbolModified = true;
}
else
{
newParameterTypesBuilder.Free();
newParameterCustomModifiersBuilder.Free();
newParameterTypes = signature.ParameterTypesWithAnnotations;
}
}
if (symbolModified)
{
return type.SubstituteTypeSymbol(newReturn, newParameterTypes, newRefModifiers, newParamModifiers);
}
else
{
return type;
}
}
public static ErrorTypeSymbol Retarget(ErrorTypeSymbol type)
{
// TODO: if it is a missing symbol error but no longer missing in the target assembly, then we can resolve it here.
var useSiteDiagnostic = type.GetUseSiteInfo().DiagnosticInfo;
if (useSiteDiagnostic?.Severity == DiagnosticSeverity.Error)
{
return type;
}
// A retargeted error symbol must trigger an error on use so that a dependent compilation won't
// improperly succeed. We therefore ensure we have a use-site diagnostic.
return
(type as ExtendedErrorTypeSymbol)?.AsUnreported() ?? // preserve diagnostic information if possible
new ExtendedErrorTypeSymbol(type, type.ResultKind,
type.ErrorInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_ErrorInReferencedAssembly, type.ContainingAssembly?.Identity.GetDisplayName() ?? string.Empty), true);
}
public ImmutableArray<Symbol> Retarget(ImmutableArray<Symbol> arr)
{
var symbols = ArrayBuilder<Symbol>.GetInstance(arr.Length);
foreach (var s in arr)
{
symbols.Add(Retarget(s));
}
return symbols.ToImmutableAndFree();
}
public ImmutableArray<NamedTypeSymbol> Retarget(ImmutableArray<NamedTypeSymbol> sequence)
{
var result = ArrayBuilder<NamedTypeSymbol>.GetInstance(sequence.Length);
foreach (var nts in sequence)
{
// If there is an error type in the base type list, it will end up in the interface list (rather
// than as the base class), so it might end up passing through here. If it is specified using
// a primitive type keyword, then it will have a primitive type code, even if corlib is missing.
Debug.Assert(nts.TypeKind == TypeKind.Error || nts.PrimitiveTypeCode == Cci.PrimitiveTypeCode.NotPrimitive);
result.Add(Retarget(nts, RetargetOptions.RetargetPrimitiveTypesByName));
}
return result.ToImmutableAndFree();
}
public ImmutableArray<TypeSymbol> Retarget(ImmutableArray<TypeSymbol> sequence)
{
var result = ArrayBuilder<TypeSymbol>.GetInstance(sequence.Length);
foreach (var ts in sequence)
{
// In incorrect code, a type parameter constraint list can contain primitive types.
Debug.Assert(ts.TypeKind == TypeKind.Error || ts.PrimitiveTypeCode == Cci.PrimitiveTypeCode.NotPrimitive);
result.Add(Retarget(ts, RetargetOptions.RetargetPrimitiveTypesByName));
}
return result.ToImmutableAndFree();
}
public ImmutableArray<TypeWithAnnotations> Retarget(ImmutableArray<TypeWithAnnotations> sequence)
{
var result = ArrayBuilder<TypeWithAnnotations>.GetInstance(sequence.Length);
foreach (var ts in sequence)
{
result.Add(Retarget(ts, RetargetOptions.RetargetPrimitiveTypesByName));
}
return result.ToImmutableAndFree();
}
public ImmutableArray<TypeParameterSymbol> Retarget(ImmutableArray<TypeParameterSymbol> list)
{
var parameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(list.Length);
foreach (var tps in list)
{
parameters.Add(Retarget(tps));
}
return parameters.ToImmutableAndFree();
}
public MethodSymbol Retarget(MethodSymbol method)
{
Debug.Assert(ReferenceEquals(method.ContainingModule, this.UnderlyingModule));
Debug.Assert(ReferenceEquals(method, method.OriginalDefinition));
return (MethodSymbol)this.SymbolMap.GetOrAdd(method, _retargetingModule._createRetargetingMethod);
}
public MethodSymbol Retarget(MethodSymbol method, IEqualityComparer<MethodSymbol> retargetedMethodComparer)
{
if (ReferenceEquals(method.ContainingModule, this.UnderlyingModule) && ReferenceEquals(method, method.OriginalDefinition))
{
return Retarget(method);
}
var containingType = method.ContainingType;
var retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName);
// NB: may return null if the method cannot be found in the retargeted type (e.g. removed in a subsequent version)
return ReferenceEquals(retargetedType, containingType) ?
method :
FindMethodInRetargetedType(method, retargetedType, retargetedMethodComparer);
}
public FieldSymbol Retarget(FieldSymbol field)
{
return (FieldSymbol)this.SymbolMap.GetOrAdd(field, _retargetingModule._createRetargetingField);
}
public PropertySymbol Retarget(PropertySymbol property)
{
Debug.Assert(ReferenceEquals(property.ContainingModule, this.UnderlyingModule));
Debug.Assert(ReferenceEquals(property, property.OriginalDefinition));
return (PropertySymbol)this.SymbolMap.GetOrAdd(property, _retargetingModule._createRetargetingProperty);
}
public PropertySymbol Retarget(PropertySymbol property, IEqualityComparer<PropertySymbol> retargetedPropertyComparer)
{
if (ReferenceEquals(property.ContainingModule, this.UnderlyingModule) && ReferenceEquals(property, property.OriginalDefinition))
{
return Retarget(property);
}
var containingType = property.ContainingType;
var retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName);
// NB: may return null if the property cannot be found in the retargeted type (e.g. removed in a subsequent version)
return ReferenceEquals(retargetedType, containingType) ?
property :
FindPropertyInRetargetedType(property, retargetedType, retargetedPropertyComparer);
}
public EventSymbol Retarget(EventSymbol @event)
{
if (ReferenceEquals(@event.ContainingModule, this.UnderlyingModule) && ReferenceEquals(@event, @event.OriginalDefinition))
{
return (EventSymbol)this.SymbolMap.GetOrAdd(@event, _retargetingModule._createRetargetingEvent);
}
var containingType = @event.ContainingType;
var retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName);
// NB: may return null if the event cannot be found in the retargeted type (e.g. removed in a subsequent version)
return ReferenceEquals(retargetedType, containingType) ?
@event :
FindEventInRetargetedType(@event, retargetedType);
}
private MethodSymbol FindMethodInRetargetedType(MethodSymbol method, NamedTypeSymbol retargetedType, IEqualityComparer<MethodSymbol> retargetedMethodComparer)
{
return RetargetedTypeMethodFinder.Find(this, method, retargetedType, retargetedMethodComparer);
}
private class RetargetedTypeMethodFinder : RetargetingSymbolTranslator
{
private RetargetedTypeMethodFinder(RetargetingModuleSymbol retargetingModule) :
base(retargetingModule)
{
}
public static MethodSymbol Find(RetargetingSymbolTranslator translator, MethodSymbol method, NamedTypeSymbol retargetedType, IEqualityComparer<MethodSymbol> retargetedMethodComparer)
{
if (!method.IsGenericMethod)
{
return FindWorker(translator, method, retargetedType, retargetedMethodComparer);
}
// A generic method needs special handling because its signature is very likely
// to refer to method's type parameters.
var finder = new RetargetedTypeMethodFinder(translator._retargetingModule);
return FindWorker(finder, method, retargetedType, retargetedMethodComparer);
}
private static MethodSymbol FindWorker
(
RetargetingSymbolTranslator translator,
MethodSymbol method,
NamedTypeSymbol retargetedType,
IEqualityComparer<MethodSymbol> retargetedMethodComparer
)
{
bool modifiersHaveChanged_Ignored; //ignored
var targetParamsBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(method.Parameters.Length);
foreach (var param in method.Parameters)
{
targetParamsBuilder.Add(
new SignatureOnlyParameterSymbol(
translator.Retarget(param.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode),
translator.RetargetModifiers(param.RefCustomModifiers, out modifiersHaveChanged_Ignored),
param.IsParams,
param.RefKind));