-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathConversionsBase.cs
3827 lines (3246 loc) · 172 KB
/
ConversionsBase.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 disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract partial class ConversionsBase
{
private const int MaximumRecursionDepth = 50;
protected readonly AssemblySymbol corLibrary;
protected readonly int currentRecursionDepth;
internal readonly bool IncludeNullability;
/// <summary>
/// An optional clone of this instance with distinct IncludeNullability.
/// Used to avoid unnecessary allocations when calling WithNullability() repeatedly.
/// </summary>
private ConversionsBase _lazyOtherNullability;
protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt)
{
Debug.Assert((object)corLibrary != null);
Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability);
Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth);
this.corLibrary = corLibrary;
this.currentRecursionDepth = currentRecursionDepth;
IncludeNullability = includeNullability;
_lazyOtherNullability = otherNullabilityOpt;
}
/// <summary>
/// Returns this instance if includeNullability is correct, and returns a
/// cached clone of this instance with distinct IncludeNullability otherwise.
/// </summary>
internal ConversionsBase WithNullability(bool includeNullability)
{
if (IncludeNullability == includeNullability)
{
return this;
}
if (_lazyOtherNullability == null)
{
Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null);
}
Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability);
Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this);
return _lazyOtherNullability;
}
protected abstract ConversionsBase WithNullabilityCore(bool includeNullability);
public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo);
public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo);
public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo);
protected abstract ConversionsBase CreateInstance(int currentRecursionDepth);
protected abstract Conversion GetInterpolatedStringConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo);
protected abstract bool IsAttributeArgumentBinding { get; }
protected abstract bool IsParameterDefaultValueBinding { get; }
internal AssemblySymbol CorLibrary { get { return corLibrary; } }
#nullable enable
/// <summary>
/// Derived types should provide non-null value for proper classification of conversions from expression.
/// </summary>
protected abstract CSharpCompilation? Compilation { get; }
/// <summary>
/// Determines if the source expression is convertible to the destination type via
/// any built-in or user-defined implicit conversion.
/// </summary>
public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(sourceExpression != null);
Debug.Assert(Compilation != null);
Debug.Assert((object)destination != null);
var sourceType = sourceExpression.Type;
//PERF: identity conversion is by far the most common implicit conversion, check for that first
if (sourceType is { } && HasIdentityConversionInternal(sourceType, destination))
{
return Conversion.Identity;
}
Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteInfo);
if (conversion.Exists)
{
return conversion;
}
if (sourceType is { })
{
// Try using the short-circuit "fast-conversion" path.
Conversion fastConversion = FastClassifyConversion(sourceType, destination);
if (fastConversion.Exists)
{
if (fastConversion.IsImplicit)
{
return fastConversion;
}
}
else
{
conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteInfo);
if (conversion.Exists)
{
return conversion;
}
}
}
else if (sourceExpression.GetFunctionType() is { } sourceFunctionType)
{
if (HasImplicitFunctionTypeConversion(sourceFunctionType, destination, ref useSiteInfo))
{
return Conversion.FunctionType;
}
}
conversion = GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo);
if (conversion.Exists)
{
return conversion;
}
// The switch expression conversion is "lowest priority", so that if there is a conversion from the expression's
// type it will be preferred over the switch expression conversion. Technically, we would want the language
// specification to say that the switch expression conversion only "exists" if there is no implicit conversion
// from the type, and we accomplish that by making it lowest priority. The same is true for the conditional
// expression conversion.
conversion = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo);
if (conversion.Exists)
{
return conversion;
}
return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo);
}
/// <summary>
/// Determines if the source type is convertible to the destination type via
/// any built-in or user-defined implicit conversion.
/// </summary>
public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert((object)source != null);
Debug.Assert((object)destination != null);
//PERF: identity conversions are very common, check for that first.
if (HasIdentityConversionInternal(source, destination))
{
return Conversion.Identity;
}
// Try using the short-circuit "fast-conversion" path.
Conversion fastConversion = FastClassifyConversion(source, destination);
if (fastConversion.Exists)
{
return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion;
}
else
{
Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo);
if (conversion.Exists)
{
return conversion;
}
}
return GetImplicitUserDefinedConversion(source, destination, ref useSiteInfo);
}
/// <summary>
/// Helper method that calls <see cref="ClassifyImplicitConversionFromType"/> or
/// <see cref="HasImplicitFunctionTypeToFunctionTypeConversion"/> depending on whether the
/// types are <see cref="FunctionTypeSymbol"/> instances.
/// Used by method type inference and best common type only.
/// </summary>
public Conversion ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var sourceFunctionType = source as FunctionTypeSymbol;
var destinationFunctionType = destination as FunctionTypeSymbol;
if (sourceFunctionType is null && destinationFunctionType is null)
{
return ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo);
}
if (sourceFunctionType is { } && destinationFunctionType is { })
{
return HasImplicitFunctionTypeToFunctionTypeConversion(sourceFunctionType, destinationFunctionType, ref useSiteInfo) ?
Conversion.FunctionType :
Conversion.NoConversion;
}
Debug.Assert(false);
return Conversion.NoConversion;
}
#nullable disable
/// <summary>
/// Determines if the source expression of given type is convertible to the destination type via
/// any built-in or user-defined conversion.
///
/// This helper is used in rare cases involving synthesized expressions where we know the type of an expression, but do not have the actual expression.
/// The reason for this helper (as opposed to ClassifyConversionFromType) is that conversions from expressions could be different
/// from conversions from type. For example expressions of dynamic type are implicitly convertable to any type, while dynamic type itself is not.
/// </summary>
public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert((object)source != null);
Debug.Assert((object)destination != null);
// since we are converting from expression, we may have implicit dynamic conversion
if (HasImplicitDynamicConversionFromExpression(source, destination))
{
return Conversion.ImplicitDynamic;
}
return ClassifyConversionFromType(source, destination, isChecked: isChecked, ref useSiteInfo);
}
private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion)
{
var sourceIsVoid = source?.SpecialType == SpecialType.System_Void;
var destIsVoid = destination.SpecialType == SpecialType.System_Void;
// 'void' is not supposed to be able to convert to or from anything, but in practice,
// a lot of code depends on checking whether an expression of type 'void' is convertible to 'void'.
// (e.g. for an expression lambda which returns void).
// Therefore we allow an identity conversion between 'void' and 'void'.
if (sourceIsVoid && destIsVoid)
{
conversion = Conversion.Identity;
return true;
}
// If exactly one of source or destination is of type 'void' then no conversion may exist.
if (sourceIsVoid || destIsVoid)
{
conversion = Conversion.NoConversion;
return true;
}
conversion = default;
return false;
}
/// <summary>
/// Determines if the source expression is convertible to the destination type via
/// any conversion: implicit, explicit, user-defined or built-in.
/// </summary>
/// <remarks>
/// It is rare but possible for a source expression to be convertible to a destination type
/// by both an implicit user-defined conversion and a built-in explicit conversion.
/// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast"
/// </remarks>
public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false)
{
Debug.Assert(sourceExpression != null);
Debug.Assert(Compilation != null);
Debug.Assert((object)destination != null);
if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion))
{
return conversion;
}
if (forCast)
{
return ClassifyConversionFromExpressionForCast(sourceExpression, destination, isChecked: isChecked, ref useSiteInfo);
}
var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo);
if (result.Exists)
{
return result;
}
return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, isChecked: isChecked, ref useSiteInfo, forCast: false);
}
/// <summary>
/// Determines if the source type is convertible to the destination type via
/// any conversion: implicit, explicit, user-defined or built-in.
/// </summary>
/// <remarks>
/// It is rare but possible for a source type to be convertible to a destination type
/// by both an implicit user-defined conversion and a built-in explicit conversion.
/// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast"
/// </remarks>
public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false)
{
Debug.Assert((object)source != null);
Debug.Assert((object)destination != null);
if (TryGetVoidConversion(source, destination, out var voidConversion))
{
return voidConversion;
}
if (forCast)
{
return ClassifyConversionFromTypeForCast(source, destination, isChecked: isChecked, ref useSiteInfo);
}
// Try using the short-circuit "fast-conversion" path.
Conversion fastConversion = FastClassifyConversion(source, destination);
if (fastConversion.Exists)
{
return fastConversion;
}
else
{
Conversion conversion1 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo);
if (conversion1.Exists)
{
return conversion1;
}
}
Conversion conversion = GetImplicitUserDefinedConversion(source, destination, ref useSiteInfo);
if (conversion.Exists)
{
return conversion;
}
conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, isChecked: isChecked, ref useSiteInfo, forCast: false);
if (conversion.Exists)
{
return conversion;
}
return GetExplicitUserDefinedConversion(source, destination, isChecked: isChecked, ref useSiteInfo);
}
/// <summary>
/// Determines if the source expression is convertible to the destination type via
/// any conversion: implicit, explicit, user-defined or built-in.
/// </summary>
/// <remarks>
/// It is rare but possible for a source expression to be convertible to a destination type
/// by both an implicit user-defined conversion and a built-in explicit conversion.
/// In that circumstance, this method classifies the conversion as the built-in conversion.
///
/// An implicit conversion exists from an expression of a dynamic type to any type.
/// An explicit conversion exists from a dynamic type to any type.
/// When casting we prefer the explicit conversion.
/// </remarks>
private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(source != null);
Debug.Assert(Compilation != null);
Debug.Assert((object)destination != null);
Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo);
if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion))
{
return implicitConversion;
}
Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, isChecked: isChecked, ref useSiteInfo, forCast: true);
if (explicitConversion.Exists)
{
return explicitConversion;
}
// It is possible for a user-defined conversion to be unambiguous when considered as
// an implicit conversion and ambiguous when considered as an explicit conversion.
// The native compiler does not check to see if a cast could be successfully bound as
// an unambiguous user-defined implicit conversion; it goes right to the ambiguous
// user-defined explicit conversion and produces an error. This means that in
// C# 5 it is possible to have:
//
// Y y = new Y();
// Z z1 = y;
//
// succeed but
//
// Z z2 = (Z)y;
//
// fail.
//
// However, there is another interesting wrinkle. It is possible for both
// an implicit user-defined conversion and an explicit user-defined conversion
// to exist and be unambiguous. For example, if there is an implicit conversion
// double-->C and an explicit conversion from int-->C, and the user casts a short
// to C, then both the implicit and explicit conversions are applicable and
// unambiguous. The native compiler in this case prefers the explicit conversion,
// and for backwards compatibility, we match it.
return implicitConversion;
}
/// <summary>
/// Determines if the source type is convertible to the destination type via
/// any conversion: implicit, explicit, user-defined or built-in.
/// </summary>
/// <remarks>
/// It is rare but possible for a source type to be convertible to a destination type
/// by both an implicit user-defined conversion and a built-in explicit conversion.
/// In that circumstance, this method classifies the conversion as the built-in conversion.
/// </remarks>
private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert((object)source != null);
Debug.Assert((object)destination != null);
// Try using the short-circuit "fast-conversion" path.
Conversion fastConversion = FastClassifyConversion(source, destination);
if (fastConversion.Exists)
{
return fastConversion;
}
Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo);
if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion))
{
return implicitBuiltInConversion;
}
Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, isChecked: isChecked, ref useSiteInfo, forCast: true);
if (explicitBuiltInConversion.Exists)
{
return explicitBuiltInConversion;
}
if (implicitBuiltInConversion.Exists)
{
return implicitBuiltInConversion;
}
// It is possible for a user-defined conversion to be unambiguous when considered as
// an implicit conversion and ambiguous when considered as an explicit conversion.
// The native compiler does not check to see if a cast could be successfully bound as
// an unambiguous user-defined implicit conversion; it goes right to the ambiguous
// user-defined explicit conversion and produces an error. This means that in
// C# 5 it is possible to have:
//
// Y y = new Y();
// Z z1 = y;
//
// succeed but
//
// Z z2 = (Z)y;
//
// fail.
var conversion = GetExplicitUserDefinedConversion(source, destination, isChecked: isChecked, ref useSiteInfo);
if (conversion.Exists)
{
return conversion;
}
return GetImplicitUserDefinedConversion(source, destination, ref useSiteInfo);
}
/// <summary>
/// Attempt a quick classification of builtin conversions. As result of "no conversion"
/// means that there is no built-in conversion, though there still may be a user-defined
/// conversion if compiling against a custom mscorlib.
/// </summary>
public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target)
{
ConversionKind convKind = ConversionEasyOut.ClassifyConversion(source, target);
if (convKind != ConversionKind.ImplicitNullable && convKind != ConversionKind.ExplicitNullable)
{
return Conversion.GetTrivialConversion(convKind);
}
return Conversion.MakeNullableConversion(convKind, FastClassifyConversion(source.StrippedType(), target.StrippedType()));
}
public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert((object)source != null);
Debug.Assert((object)destination != null);
// Try using the short-circuit "fast-conversion" path.
Conversion fastConversion = FastClassifyConversion(source, destination);
if (fastConversion.Exists)
{
return fastConversion;
}
else
{
Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo);
if (conversion.Exists)
{
return conversion;
}
}
return ClassifyExplicitBuiltInOnlyConversion(source, destination, isChecked: isChecked, ref useSiteInfo, forCast: false);
}
/// <summary>
/// Determines if the source type is convertible to the destination type via
/// any standard implicit or standard explicit conversion.
/// </summary>
/// <remarks>
/// Not all built-in explicit conversions are standard explicit conversions.
/// </remarks>
public Conversion ClassifyStandardConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
return ClassifyStandardConversion(sourceExpression: null, source, destination, ref useSiteInfo);
}
/// <summary>
/// Determines if the source type is convertible to the destination type via
/// any standard implicit or standard explicit conversion.
/// </summary>
/// <remarks>
/// Not all built-in explicit conversions are standard explicit conversions.
/// </remarks>
public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(sourceExpression is null || Compilation is not null);
Debug.Assert(sourceExpression != null || (object)source != null);
Debug.Assert((object)destination != null);
// Note that the definition of explicit standard conversion does not include all explicit
// reference conversions! There is a standard implicit reference conversion from
// Action<Object> to Action<Exception>, thanks to contravariance. There is a standard
// implicit reference conversion from Action<Object> to Action<String> for the same reason.
// Therefore there is an explicit reference conversion from Action<Exception> to
// Action<String>; a given Action<Exception> might be an Action<Object>, and hence
// convertible to Action<String>. However, this is not a *standard* explicit conversion. The
// standard explicit conversions are all the standard implicit conversions and their
// opposites. Therefore Action<Object>-->Action<String> and Action<String>-->Action<Object>
// are both standard conversions. But Action<String>-->Action<Exception> is not a standard
// explicit conversion because neither it nor its opposite is a standard implicit
// conversion.
//
// Similarly, there is no standard explicit conversion from double to decimal, because
// there is no standard implicit conversion between the two types.
// SPEC: The standard explicit conversions are all standard implicit conversions plus
// SPEC: the subset of the explicit conversions for which an opposite standard implicit
// SPEC: conversion exists. In other words, if a standard implicit conversion exists from
// SPEC: a type A to a type B, then a standard explicit conversion exists from type A to
// SPEC: type B and from type B to type A.
Conversion conversion = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo);
if (conversion.Exists)
{
return conversion;
}
if ((object)source != null)
{
return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo);
}
return Conversion.NoConversion;
}
private static bool IsStandardImplicitConversionFromExpression(ConversionKind kind)
{
if (IsStandardImplicitConversionFromType(kind))
{
return true;
}
// See comment in ClassifyStandardImplicitConversion(BoundExpression, ...)
// where the set of standard implicit conversions is extended from the spec
// to include conversions from expression.
switch (kind)
{
case ConversionKind.AnonymousFunction:
case ConversionKind.MethodGroup:
case ConversionKind.ImplicitEnumeration:
case ConversionKind.ImplicitDynamic:
case ConversionKind.ImplicitNullToPointer:
case ConversionKind.ImplicitTupleLiteral:
case ConversionKind.StackAllocToPointerType:
case ConversionKind.StackAllocToSpanType:
case ConversionKind.InlineArray:
return true;
default:
return false;
}
}
// See https://github.com/dotnet/csharplang/blob/main/spec/conversions.md#standard-conversions:
// "The standard conversions are those pre-defined conversions that can occur as part of a user-defined conversion."
private static bool IsStandardImplicitConversionFromType(ConversionKind kind)
{
switch (kind)
{
case ConversionKind.Identity:
case ConversionKind.ImplicitNumeric:
case ConversionKind.ImplicitNullable:
case ConversionKind.ImplicitReference:
case ConversionKind.Boxing:
case ConversionKind.ImplicitConstant:
case ConversionKind.ImplicitPointer:
case ConversionKind.ImplicitPointerToVoid:
case ConversionKind.ImplicitTuple:
return true;
default:
return false;
}
}
private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(sourceExpression is null || Compilation is not null);
Debug.Assert(sourceExpression != null || (object)source != null);
Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source);
Debug.Assert((object)destination != null);
// SPEC: The following implicit conversions are classified as standard implicit conversions:
// SPEC: Identity conversions
// SPEC: Implicit numeric conversions
// SPEC: Implicit nullable conversions
// SPEC: Implicit reference conversions
// SPEC: Boxing conversions
// SPEC: Implicit constant expression conversions
// SPEC: Implicit conversions involving type parameters
//
// and in unsafe code:
//
// SPEC: From any pointer type to void*
//
// SPEC ERROR:
// The specification does not say to take into account the conversion from
// the *expression*, only its *type*. But the expression may not have a type
// (because it is null, a method group, or a lambda), or the expression might
// be convertible to the destination type via a constant numeric conversion.
// For example, the native compiler allows "C c = 1;" to work if C is a class which
// has an implicit conversion from byte to C, despite the fact that there is
// obviously no standard implicit conversion from *int* to *byte*.
// Similarly, if a struct S has an implicit conversion from string to S, then
// "S s = null;" should be allowed.
//
// We extend the definition of standard implicit conversions to include
// all of the implicit conversions that are allowed based on an expression,
// with the exception of switch expression, interpolated string builder,
// and collection literal conversions.
Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo);
if (conversion.Exists &&
!conversion.IsInterpolatedStringHandler &&
!conversion.IsCollectionLiteral)
{
Debug.Assert(IsStandardImplicitConversionFromExpression(conversion.Kind));
return conversion;
}
if ((object)source != null)
{
return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo);
}
return Conversion.NoConversion;
}
private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var conversion = classifyConversion(source, destination, ref useSiteInfo);
Debug.Assert(conversion.Kind == ConversionKind.NoConversion || IsStandardImplicitConversionFromType(conversion.Kind));
return conversion;
Conversion classifyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert((object)source != null);
Debug.Assert((object)destination != null);
if (HasIdentityConversionInternal(source, destination))
{
return Conversion.Identity;
}
if (HasImplicitNumericConversion(source, destination))
{
return Conversion.ImplicitNumeric;
}
var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteInfo);
if (nullableConversion.Exists)
{
return nullableConversion;
}
if (source is FunctionTypeSymbol)
{
Debug.Assert(false);
return Conversion.NoConversion;
}
if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo))
{
return Conversion.ImplicitReference;
}
if (HasBoxingConversion(source, destination, ref useSiteInfo))
{
return Conversion.Boxing;
}
if (HasImplicitPointerToVoidConversion(source, destination))
{
return Conversion.PointerToVoid;
}
if (HasImplicitPointerConversion(source, destination, ref useSiteInfo))
{
return Conversion.ImplicitPointer;
}
var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteInfo);
if (tupleConversion.Exists)
{
return tupleConversion;
}
return Conversion.NoConversion;
}
}
private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert((object)source != null);
Debug.Assert((object)destination != null);
if (source.IsVoidType() || destination.IsVoidType())
{
return Conversion.NoConversion;
}
Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo);
if (conversion.Exists)
{
return conversion;
}
return Conversion.NoConversion;
}
private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo);
return new Conversion(conversionResult, isImplicit: true);
}
private Conversion GetImplicitUserDefinedConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
return GetImplicitUserDefinedConversion(sourceExpression: null, source, destination, ref useSiteInfo);
}
private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast)
{
Debug.Assert((object)source != null);
Debug.Assert((object)destination != null);
if (source.IsVoidType() || destination.IsVoidType())
{
return Conversion.NoConversion;
}
// The call to HasExplicitNumericConversion isn't necessary, because it is always tested
// already by the "FastConversion" code.
Debug.Assert(!HasExplicitNumericConversion(source, destination));
//if (HasExplicitNumericConversion(source, specialTypeSource, destination, specialTypeDest))
//{
// return Conversion.ExplicitNumeric;
//}
if (HasSpecialIntPtrConversion(source, destination))
{
return Conversion.IntPtr;
}
if (HasExplicitEnumerationConversion(source, destination))
{
return Conversion.ExplicitEnumeration;
}
var nullableConversion = ClassifyExplicitNullableConversion(source, destination, isChecked: isChecked, ref useSiteInfo, forCast);
if (nullableConversion.Exists)
{
return nullableConversion;
}
if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo))
{
return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference;
}
if (HasUnboxingConversion(source, destination, ref useSiteInfo))
{
return Conversion.Unboxing;
}
var tupleConversion = ClassifyExplicitTupleConversion(source, destination, isChecked: isChecked, ref useSiteInfo, forCast);
if (tupleConversion.Exists)
{
return tupleConversion;
}
if (HasPointerToPointerConversion(source, destination))
{
return Conversion.PointerToPointer;
}
if (HasPointerToIntegerConversion(source, destination))
{
return Conversion.PointerToInteger;
}
if (HasIntegerToPointerConversion(source, destination))
{
return Conversion.IntegerToPointer;
}
if (HasExplicitDynamicConversion(source, destination))
{
return Conversion.ExplicitDynamic;
}
return Conversion.NoConversion;
}
private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, isChecked: isChecked, ref useSiteInfo);
return new Conversion(conversionResult, isImplicit: false);
}
private Conversion GetExplicitUserDefinedConversion(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
return GetExplicitUserDefinedConversion(sourceExpression: null, source, destination, isChecked, ref useSiteInfo);
}
private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo);
Conversion impliedExplicitConversion;
switch (oppositeConversion.Kind)
{
case ConversionKind.Identity:
impliedExplicitConversion = Conversion.Identity;
break;
case ConversionKind.ImplicitNumeric:
impliedExplicitConversion = Conversion.ExplicitNumeric;
break;
case ConversionKind.ImplicitReference:
impliedExplicitConversion = Conversion.ExplicitReference;
break;
case ConversionKind.Boxing:
impliedExplicitConversion = Conversion.Unboxing;
break;
case ConversionKind.NoConversion:
impliedExplicitConversion = Conversion.NoConversion;
break;
case ConversionKind.ImplicitPointerToVoid:
impliedExplicitConversion = Conversion.PointerToPointer;
break;
case ConversionKind.ImplicitTuple:
// only implicit tuple conversions are standard conversions,
// having implicit conversion in the other direction does not help here.
impliedExplicitConversion = Conversion.NoConversion;
break;
case ConversionKind.ImplicitNullable:
var strippedSource = source.StrippedType();
var strippedDestination = destination.StrippedType();
var underlyingConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(strippedSource, strippedDestination, ref useSiteInfo);
// the opposite underlying conversion may not exist
// for example if underlying conversion is implicit tuple
impliedExplicitConversion = underlyingConversion.Exists ?
Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) :
Conversion.NoConversion;
break;
default:
throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind);
}
return impliedExplicitConversion;
}
#nullable enable
/// <summary>
/// IsBaseInterface returns true if baseType is on the base interface list of derivedType or
/// any base class of derivedType. It may be on the base interface list either directly or
/// indirectly.
/// * baseType must be an interface.
/// * type parameters do not have base interfaces. (They have an "effective interface list".)
/// * an interface is not a base of itself.
/// * this does not check for variance conversions; if a type inherits from
/// IEnumerable<string> then IEnumerable<object> is not a base interface.
/// </summary>
public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert((object)baseType != null);
Debug.Assert((object)derivedType != null);
if (!baseType.IsInterfaceType())
{
return false;
}
var d = derivedType as NamedTypeSymbol;
if (d is null)
{
return false;
}
foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo))
{
if (HasIdentityConversionInternal(iface, baseType))
{
return true;
}
}
return false;
}
// IsBaseClass returns true if and only if baseType is a base class of derivedType, period.
//
// * interfaces do not have base classes. (Structs, enums and classes other than object do.)
// * a class is not a base class of itself
// * type parameters do not have base classes. (They have "effective base classes".)
// * all base classes must be classes
// * dynamics are removed; if we have class D : B<dynamic> then B<object> is a
// base class of D. However, dynamic is never a base class of anything.
public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert((object)derivedType != null);
Debug.Assert((object)baseType != null);
// A base class has got to be a class. The derived type might be a struct, enum, or delegate.
if (!baseType.IsClassType())
{
return false;
}
for (TypeSymbol b = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo))
{
if (HasIdentityConversionInternal(b, baseType))
{
return true;
}
}
return false;
}
/// <summary>
/// returns true when implicit conversion is not necessarily the same as explicit conversion
/// </summary>
private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion)
{
switch (implicitConversion.Kind)
{
case ConversionKind.ImplicitUserDefined:
case ConversionKind.ImplicitDynamic:
case ConversionKind.ImplicitTuple:
case ConversionKind.ImplicitTupleLiteral:
case ConversionKind.ImplicitNullable:
case ConversionKind.ConditionalExpression:
return true;
default:
return false;
}
}
#nullable disable
private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(sourceExpression is null || Compilation is not null);