ConversionsBase.cs 146.4 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2

3
using System;
C
Charles Stoner 已提交
4 5
using System.Collections.Generic;
using System.Collections.Immutable;
P
Pilchie 已提交
6 7 8
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
T
Tomas Matousek 已提交
9
using Microsoft.CodeAnalysis.PooledObjects;
10
using Roslyn.Utilities;
P
Pilchie 已提交
11 12 13 14 15 16 17 18

namespace Microsoft.CodeAnalysis.CSharp
{
    internal abstract partial class ConversionsBase
    {
        private const int MaximumRecursionDepth = 50;

        protected readonly AssemblySymbol corLibrary;
19
        protected readonly int currentRecursionDepth;
P
Pilchie 已提交
20

21 22
        internal readonly bool IncludeNullability;

23 24 25 26 27 28 29
        /// <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)
P
Pilchie 已提交
30 31
        {
            Debug.Assert((object)corLibrary != null);
32 33
            Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability);
            Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth);
34

P
Pilchie 已提交
35
            this.corLibrary = corLibrary;
36 37
            this.currentRecursionDepth = currentRecursionDepth;
            IncludeNullability = includeNullability;
38
            _lazyOtherNullability = otherNullabilityOpt;
P
Pilchie 已提交
39 40
        }

41 42
        /// <summary>
        /// Returns this instance if includeNullability is correct, and returns a
43
        /// cached clone of this instance with distinct IncludeNullability otherwise.
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
        /// </summary>
        internal ConversionsBase WithNullability(bool includeNullability)
        {
            if (IncludeNullability == includeNullability)
            {
                return this;
            }
            if (_lazyOtherNullability == null)
            {
                _lazyOtherNullability = WithNullabilityCore(includeNullability);
            }
            Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability);
            Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this);
            return _lazyOtherNullability;
        }

        protected abstract ConversionsBase WithNullabilityCore(bool includeNullability);

P
Pilchie 已提交
62 63
        public abstract Conversion GetMethodGroupConversion(BoundMethodGroup source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics);

64 65
        public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics);

66 67
        protected abstract ConversionsBase CreateInstance(int currentRecursionDepth);

68 69
        protected abstract Conversion GetInterpolatedStringConversion(BoundInterpolatedString source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics);

70
        internal AssemblySymbol CorLibrary { get { return corLibrary; } }
J
Julien 已提交
71

P
Pilchie 已提交
72
        /// <summary>
73 74
        /// Determines if the source expression is convertible to the destination type via
        /// any built-in or user-defined implicit conversion.
P
Pilchie 已提交
75
        /// </summary>
76
        public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
P
Pilchie 已提交
77
        {
78 79 80 81 82 83
            Debug.Assert(sourceExpression != 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
84
            if ((object)sourceType != null && HasIdentityConversionInternal(sourceType, destination))
V
VSadov 已提交
85
            {
86
                return Conversion.Identity;
V
VSadov 已提交
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
            Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteDiagnostics);
            if (conversion.Exists)
            {
                return conversion;
            }

            if ((object)sourceType != null)
            {
                // Try using the short-circuit "fast-conversion" path.
                Conversion fastConversion = FastClassifyConversion(sourceType, destination);
                if (fastConversion.Exists)
                {
                    return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion;
                }
                else
                {
                    conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteDiagnostics);
                    if (conversion.Exists)
                    {
                        return conversion;
                    }
                }
            }

            return GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteDiagnostics);
P
Pilchie 已提交
114 115 116
        }

        /// <summary>
117 118
        /// Determines if the source type is convertible to the destination type via
        /// any built-in or user-defined implicit conversion.
P
Pilchie 已提交
119
        /// </summary>
120
        public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
P
Pilchie 已提交
121
        {
122 123 124 125
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            //PERF: identity conversions are very common, check for that first.
126
            if (HasIdentityConversionInternal(source, destination))
P
Pilchie 已提交
127
            {
128
                return Conversion.Identity;
P
Pilchie 已提交
129 130
            }

131 132 133
            // Try using the short-circuit "fast-conversion" path.
            Conversion fastConversion = FastClassifyConversion(source, destination);
            if (fastConversion.Exists)
P
Pilchie 已提交
134
            {
135
                return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion;
P
Pilchie 已提交
136
            }
137
            else
P
Pilchie 已提交
138
            {
139 140
                Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteDiagnostics);
                if (conversion.Exists)
P
Pilchie 已提交
141
                {
142
                    return conversion;
P
Pilchie 已提交
143 144 145
                }
            }

146
            return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteDiagnostics);
P
Pilchie 已提交
147 148
        }

149 150 151 152 153 154 155 156 157
        /// <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, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
P
Pilchie 已提交
158
        {
159 160 161 162 163 164 165 166 167 168
            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, ref useSiteDiagnostics);
P
Pilchie 已提交
169 170
        }

171 172 173 174 175 176 177 178 179 180
        /// <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, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast = false)
P
Pilchie 已提交
181
        {
182 183
            Debug.Assert(sourceExpression != null);
            Debug.Assert((object)destination != null);
P
Pilchie 已提交
184

185
            if (forCast)
P
Pilchie 已提交
186
            {
187
                return ClassifyConversionFromExpressionForCast(sourceExpression, destination, ref useSiteDiagnostics);
P
Pilchie 已提交
188 189
            }

190 191
            var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteDiagnostics);
            if (result.Exists)
P
Pilchie 已提交
192
            {
193
                return result;
P
Pilchie 已提交
194 195
            }

196
            return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, ref useSiteDiagnostics, forCast: false);
P
Pilchie 已提交
197 198 199 200 201 202 203 204 205
        }

        /// <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.
206
        /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast"
P
Pilchie 已提交
207
        /// </remarks>
208
        public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast = false)
P
Pilchie 已提交
209 210 211 212
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

213 214 215 216 217
            if (forCast)
            {
                return ClassifyConversionFromTypeForCast(source, destination, ref useSiteDiagnostics);
            }

P
Pilchie 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
            // 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 useSiteDiagnostics);
                if (conversion1.Exists)
                {
                    return conversion1;
                }
            }

233 234
            Conversion conversion = GetImplicitUserDefinedConversion(null, source, destination, ref useSiteDiagnostics);
            if (conversion.Exists)
P
Pilchie 已提交
235
            {
236
                return conversion;
P
Pilchie 已提交
237 238
            }

239
            conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteDiagnostics, forCast: false);
P
Pilchie 已提交
240 241 242 243 244
            if (conversion.Exists)
            {
                return conversion;
            }

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
            return GetExplicitUserDefinedConversion(null, source, destination, ref useSiteDiagnostics);
        }

        /// <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, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(source != null);
            Debug.Assert((object)destination != null);

            Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteDiagnostics);
            if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion))
            {
                return implicitConversion;
            }

            Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, ref useSiteDiagnostics, 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.Exists ? implicitConversion : Conversion.NoConversion;
P
Pilchie 已提交
303 304 305 306 307 308 309 310 311 312 313
        }

        /// <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>
314
        private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
P
Pilchie 已提交
315 316 317 318 319 320 321 322 323 324
        {
            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;
            }
325 326 327

            Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteDiagnostics);
            if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion))
P
Pilchie 已提交
328
            {
329
                return implicitBuiltInConversion;
P
Pilchie 已提交
330 331
            }

332 333
            Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteDiagnostics, forCast: true);
            if (explicitBuiltInConversion.Exists)
P
Pilchie 已提交
334
            {
335 336 337 338 339 340
                return explicitBuiltInConversion;
            }

            if (implicitBuiltInConversion.Exists)
            {
                return implicitBuiltInConversion;
P
Pilchie 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
            }

            // 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.

359
            var conversion = GetExplicitUserDefinedConversion(null, source, destination, ref useSiteDiagnostics);
P
Pilchie 已提交
360 361 362 363 364 365 366 367
            if (conversion.Exists)
            {
                return conversion;
            }

            return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteDiagnostics);
        }

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
        /// <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, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            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 useSiteDiagnostics);
                if (conversion.Exists)
                {
                    return conversion;
                }
            }

            return ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteDiagnostics, forCast: false);
        }

P
Pilchie 已提交
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
        /// <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 HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            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 useSiteDiagnostics);
            if (conversion.Exists)
            {
                return conversion;
            }

            if ((object)source != null)
            {
V
VSadov 已提交
449
                return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteDiagnostics);
P
Pilchie 已提交
450 451 452 453 454
            }

            return Conversion.NoConversion;
        }

455
        private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
P
Pilchie 已提交
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
        {
            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.

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
            Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteDiagnostics);
            if (conversion.Exists)
            {
                return conversion;
            }

            if ((object)source != null)
            {
                return ClassifyStandardImplicitConversion(source, destination, ref useSiteDiagnostics);
            }

            return Conversion.NoConversion;
        }

        private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

507
            if (HasIdentityConversionInternal(source, destination))
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
            {
                return Conversion.Identity;
            }

            if (HasImplicitNumericConversion(source, destination))
            {
                return Conversion.ImplicitNumeric;
            }

            var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteDiagnostics);
            if (nullableConversion.Exists)
            {
                return nullableConversion;
            }

            if (HasImplicitReferenceConversion(source, destination, ref useSiteDiagnostics))
            {
                return Conversion.ImplicitReference;
            }

            if (HasBoxingConversion(source, destination, ref useSiteDiagnostics))
            {
                return Conversion.Boxing;
            }

            if (HasImplicitPointerConversion(source, destination))
            {
                return Conversion.PointerToVoid;
            }

            var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteDiagnostics);
            if (tupleConversion.Exists)
            {
                return tupleConversion;
            }

            return Conversion.NoConversion;
        }

        private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            if (source.SpecialType == SpecialType.System_Void || destination.SpecialType == SpecialType.System_Void)
            {
                return Conversion.NoConversion;
            }

            Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteDiagnostics);
            if (conversion.Exists)
            {
                return conversion;
            }

            return Conversion.NoConversion;
        }

        private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteDiagnostics);
            return new Conversion(conversionResult, isImplicit: true);
        }

        private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            if (source.SpecialType == SpecialType.System_Void || destination.SpecialType == SpecialType.System_Void)
            {
                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, ref useSiteDiagnostics, forCast);
            if (nullableConversion.Exists)
            {
                return nullableConversion;
            }

            if (HasExplicitReferenceConversion(source, destination, ref useSiteDiagnostics))
            {
                return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference;
            }

            if (HasUnboxingConversion(source, destination, ref useSiteDiagnostics))
            {
                return Conversion.Unboxing;
            }

            var tupleConversion = ClassifyExplicitTupleConversion(source, destination, ref useSiteDiagnostics, 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, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteDiagnostics);
            return new Conversion(conversionResult, isImplicit: false);
        }

V
VSadov 已提交
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
        private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteDiagnostics);
            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.PointerToVoid:
                    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 useSiteDiagnostics);

                    // the opposite underlying conversion may not exist 
                    // for example if underlying conversion is implicit tuple
                    impliedExplicitConversion = underlyingConversion.Exists ?
V
VSadov 已提交
692
                        Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) :
V
VSadov 已提交
693 694
                        Conversion.NoConversion;

695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
                    break;

                default:
                    throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind);
            }

            return impliedExplicitConversion;
        }

        /// <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&lt;string> then IEnumerable&lt;object> is not a base interface.
        /// </summary>
714
        public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
715 716 717
        {
            Debug.Assert((object)baseType != null);
            Debug.Assert((object)derivedType != null);
718

719 720 721 722 723 724 725 726 727 728 729 730 731
            if (!baseType.IsInterfaceType())
            {
                return false;
            }

            var d = derivedType as NamedTypeSymbol;
            if ((object)d == null)
            {
                return false;
            }

            foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
            {
732
                if (HasIdentityConversionInternal(iface, baseType))
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
                {
                    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.
749
        public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
750 751 752 753 754 755 756 757 758 759 760 761
        {
            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 useSiteDiagnostics); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
            {
762
                if (HasIdentityConversionInternal(b, baseType))
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
                {
                    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:
                    return true;
V
VSadov 已提交
784 785

                default:
786
                    return false;
V
VSadov 已提交
787 788 789
            }
        }

790
        private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
P
Pilchie 已提交
791 792 793 794 795
        {
            Debug.Assert(sourceExpression != null || (object)source != null);
            Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source);
            Debug.Assert((object)destination != null);

796 797 798 799
            if (HasImplicitDynamicConversionFromExpression(source, destination))
            {
                return Conversion.ImplicitDynamic;
            }
P
Pilchie 已提交
800

801 802 803
            // The following conversions only exist for certain form of expressions, 
            // if we have no expression none if them is applicable.
            if (sourceExpression == null)
P
Pilchie 已提交
804
            {
805
                return Conversion.NoConversion;
P
Pilchie 已提交
806 807
            }

808
            if (HasImplicitEnumerationConversion(sourceExpression, destination))
P
Pilchie 已提交
809
            {
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
                return Conversion.ImplicitEnumeration;
            }

            var constantConversion = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination);
            if (constantConversion.Exists)
            {
                return constantConversion;
            }

            switch (sourceExpression.Kind)
            {
                case BoundKind.Literal:
                    var nullLiteralConversion = ClassifyNullLiteralConversion(sourceExpression, destination);
                    if (nullLiteralConversion.Exists)
                    {
                        return nullLiteralConversion;
                    }
                    break;

829 830
                case BoundKind.DefaultExpression:
                    var defaultExpression = (BoundDefaultExpression)sourceExpression;
831
                    if ((object)defaultExpression.Type == null)
832
                    {
833
                        return Conversion.DefaultOrNullLiteral;
834 835
                    }
                    break;
836

837 838 839 840 841 842 843 844 845 846
                case BoundKind.ExpressionWithNullability:
                    {
                        var innerExpression = ((BoundExpressionWithNullability)sourceExpression).Expression;
                        var innerConversion = ClassifyImplicitBuiltInConversionFromExpression(innerExpression, innerExpression.Type, destination, ref useSiteDiagnostics);
                        if (innerConversion.Exists)
                        {
                            return innerConversion;
                        }
                        break;
                    }
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
                case BoundKind.TupleLiteral:
                    var tupleConversion = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteDiagnostics);
                    if (tupleConversion.Exists)
                    {
                        return tupleConversion;
                    }
                    break;

                case BoundKind.UnboundLambda:
                    if (HasAnonymousFunctionConversion(sourceExpression, destination))
                    {
                        return Conversion.AnonymousFunction;
                    }
                    break;

                case BoundKind.MethodGroup:
                    Conversion methodGroupConversion = GetMethodGroupConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteDiagnostics);
                    if (methodGroupConversion.Exists)
                    {
                        return methodGroupConversion;
                    }
                    break;

                case BoundKind.InterpolatedString:
                    Conversion interpolatedStringConversion = GetInterpolatedStringConversion((BoundInterpolatedString)sourceExpression, destination, ref useSiteDiagnostics);
                    if (interpolatedStringConversion.Exists)
                    {
                        return interpolatedStringConversion;
                    }
                    break;
877

878 879 880 881 882 883 884 885
                case BoundKind.StackAllocArrayCreation:
                    var stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteDiagnostics);
                    if (stackAllocConversion.Exists)
                    {
                        return stackAllocConversion;
                    }
                    break;

886 887
                case BoundKind.ThrowExpression:
                    return Conversion.ImplicitThrow;
P
Pilchie 已提交
888 889 890 891 892
            }

            return Conversion.NoConversion;
        }

893
        private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination)
P
Pilchie 已提交
894 895 896 897
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

898
            if (!source.IsLiteralNull())
P
Pilchie 已提交
899
            {
900
                return Conversion.NoConversion;
P
Pilchie 已提交
901 902
            }

903 904
            // SPEC: An implicit conversion exists from the null literal to any nullable type. 
            if (destination.IsNullableType())
P
Pilchie 已提交
905
            {
906 907
                // The spec defines a "null literal conversion" specifically as a conversion from
                // null to nullable type.
908
                return Conversion.DefaultOrNullLiteral;
P
Pilchie 已提交
909 910
            }

911 912 913 914 915 916
            // SPEC: An implicit conversion exists from the null literal to any reference type. 
            // SPEC: An implicit conversion exists from the null literal to type parameter T, 
            // SPEC: provided T is known to be a reference type. [...] The conversion [is] classified 
            // SPEC: as implicit reference conversion. 

            if (destination.IsReferenceType)
P
Pilchie 已提交
917
            {
918
                return Conversion.ImplicitReference;
P
Pilchie 已提交
919 920
            }

921 922 923 924
            // SPEC: The set of implicit conversions is extended to include...
            // SPEC: ... from the null literal to any pointer type.

            if (destination is PointerTypeSymbol)
P
Pilchie 已提交
925
            {
926
                return Conversion.NullToPointer;
P
Pilchie 已提交
927 928
            }

929 930 931 932 933 934
            return Conversion.NoConversion;
        }

        private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination)
        {
            if (HasImplicitConstantExpressionConversion(source, destination))
P
Pilchie 已提交
935
            {
936
                return Conversion.ImplicitConstant;
P
Pilchie 已提交
937 938
            }

939 940 941 942 943
            // strip nullable from the destination
            //
            // the following should work and it is an ImplicitNullable conversion
            //    int? x = 1;
            if (destination.Kind == SymbolKind.NamedType)
P
Pilchie 已提交
944
            {
945 946
                var nt = (NamedTypeSymbol)destination;
                if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T &&
C
Charles Stoner 已提交
947
                    HasImplicitConstantExpressionConversion(source, nt.TypeArgumentsNoUseSiteDiagnostics[0].TypeSymbol))
948 949 950
                {
                    return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitConstantUnderlying);
                }
P
Pilchie 已提交
951 952 953 954 955
            }

            return Conversion.NoConversion;
        }

956
        private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
P
Pilchie 已提交
957
        {
958
            var tupleConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteDiagnostics);
959
            if (tupleConversion.Exists)
960
            {
961
                return tupleConversion;
962
            }
P
Pilchie 已提交
963

964 965 966 967 968
            // strip nullable from the destination
            //
            // the following should work and it is an ImplicitNullable conversion
            //    (int, double)? x = (1,2);
            if (destination.Kind == SymbolKind.NamedType)
P
Pilchie 已提交
969
            {
970 971 972
                var nt = (NamedTypeSymbol)destination;
                if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T)
                {
C
Charles Stoner 已提交
973
                    var underlyingTupleConversion = GetImplicitTupleLiteralConversion(source, nt.TypeArgumentsNoUseSiteDiagnostics[0].TypeSymbol, ref useSiteDiagnostics);
974 975 976 977 978 979

                    if (underlyingTupleConversion.Exists)
                    {
                        return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(underlyingTupleConversion));
                    }
                }
P
Pilchie 已提交
980 981 982 983 984
            }

            return Conversion.NoConversion;
        }

985
        private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast)
P
Pilchie 已提交
986
        {
987 988
            var tupleConversion = GetExplicitTupleLiteralConversion(source, destination, ref useSiteDiagnostics, forCast);
            if (tupleConversion.Exists)
P
Pilchie 已提交
989
            {
990
                return tupleConversion;
P
Pilchie 已提交
991 992
            }

993 994 995 996 997
            // strip nullable from the destination
            //
            // the following should work and it is an ExplicitNullable conversion
            //    var x = ((byte, string)?)(1,null);
            if (destination.Kind == SymbolKind.NamedType)
P
Pilchie 已提交
998
            {
999 1000 1001
                var nt = (NamedTypeSymbol)destination;
                if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T)
                {
C
Charles Stoner 已提交
1002
                    var underlyingTupleConversion = GetExplicitTupleLiteralConversion(source, nt.TypeArgumentsNoUseSiteDiagnostics[0].TypeSymbol, ref useSiteDiagnostics, forCast);
P
Pilchie 已提交
1003

1004 1005 1006 1007 1008 1009
                    if (underlyingTupleConversion.Exists)
                    {
                        return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(underlyingTupleConversion));
                    }
                }
            }
P
Pilchie 已提交
1010 1011 1012 1013

            return Conversion.NoConversion;
        }

1014
        internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination)
P
Pilchie 已提交
1015
        {
1016 1017
            var constantValue = source.ConstantValue;

1018
            if (constantValue == null || (object)source.Type == null)
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
            {
                return false;
            }

            // An implicit constant expression conversion permits the following conversions:

            // A constant-expression of type int can be converted to type sbyte, byte, short, 
            // ushort, uint, or ulong, provided the value of the constant-expression is within the
            // range of the destination type.
            var specialSource = source.Type.GetSpecialTypeSafe();

            if (specialSource == SpecialType.System_Int32)
            {
                //if the constant value could not be computed, be generous and assume the conversion will work
                int value = constantValue.IsBad ? 0 : constantValue.Int32Value;
                switch (destination.GetSpecialTypeSafe())
                {
                    case SpecialType.System_Byte:
                        return byte.MinValue <= value && value <= byte.MaxValue;
                    case SpecialType.System_SByte:
                        return sbyte.MinValue <= value && value <= sbyte.MaxValue;
                    case SpecialType.System_Int16:
                        return short.MinValue <= value && value <= short.MaxValue;
                    case SpecialType.System_UInt32:
                        return uint.MinValue <= value;
                    case SpecialType.System_UInt64:
                        return (int)ulong.MinValue <= value;
                    case SpecialType.System_UInt16:
                        return ushort.MinValue <= value && value <= ushort.MaxValue;
                    default:
                        return false;
                }
            }
            else if (specialSource == SpecialType.System_Int64 && destination.GetSpecialTypeSafe() == SpecialType.System_UInt64 && (constantValue.IsBad || 0 <= constantValue.Int64Value))
            {
                // A constant-expression of type long can be converted to type ulong, provided the
                // value of the constant-expression is not negative.
                return true;
            }

            return false;
P
Pilchie 已提交
1060 1061
        }

1062
        private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast)
P
Pilchie 已提交
1063
        {
1064
            Debug.Assert(sourceExpression != null);
P
Pilchie 已提交
1065 1066
            Debug.Assert((object)destination != null);

1067
            var sourceType = sourceExpression.Type;
P
Pilchie 已提交
1068

1069 1070 1071 1072
            // NB: need to check for explicit tuple literal conversion before checking for explicit conversion from type
            //     The same literal may have both explicit tuple conversion and explicit tuple literal conversion to the target type.
            //     They are, however, observably different conversions via the order of argument evaluations and element-wise conversions
            if (sourceExpression.Kind == BoundKind.TupleLiteral)
P
Pilchie 已提交
1073
            {
1074 1075 1076 1077 1078
                Conversion tupleConversion = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteDiagnostics, forCast);
                if (tupleConversion.Exists)
                {
                    return tupleConversion;
                }
P
Pilchie 已提交
1079
            }
1080 1081

            if ((object)sourceType != null)
P
Pilchie 已提交
1082
            {
1083 1084 1085
                // Try using the short-circuit "fast-conversion" path.
                Conversion fastConversion = FastClassifyConversion(sourceType, destination);
                if (fastConversion.Exists)
P
Pilchie 已提交
1086
                {
1087 1088 1089 1090 1091 1092 1093 1094 1095
                    return fastConversion;
                }
                else
                {
                    var conversion = ClassifyExplicitBuiltInOnlyConversion(sourceType, destination, ref useSiteDiagnostics, forCast);
                    if (conversion.Exists)
                    {
                        return conversion;
                    }
P
Pilchie 已提交
1096 1097 1098
                }
            }

1099
            return GetExplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteDiagnostics);
P
Pilchie 已提交
1100 1101
        }

1102
        private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination)
P
Pilchie 已提交
1103 1104 1105 1106
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

1107 1108 1109 1110 1111
            // SPEC: An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type 
            // SPEC: and to any nullable-type whose underlying type is an enum-type. 
            //
            // For historical reasons we actually allow a conversion from any *numeric constant
            // zero* to be converted to any enum type, not just the literal integer zero.
P
Pilchie 已提交
1112

1113 1114 1115 1116
            bool validType = destination.IsEnumType() ||
                destination.IsNullableType() && destination.GetNullableUnderlyingType().IsEnumType();

            if (!validType)
P
Pilchie 已提交
1117
            {
1118
                return false;
P
Pilchie 已提交
1119 1120
            }

1121 1122 1123 1124 1125
            var sourceConstantValue = source.ConstantValue;
            return sourceConstantValue != null &&
                IsNumericType(source.Type.GetSpecialTypeSafe()) &&
                IsConstantNumericZero(sourceConstantValue);
        }
P
Pilchie 已提交
1126

1127 1128 1129 1130
        private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type)
        {
            Debug.Assert((object)anonymousFunction != null);
            Debug.Assert((object)type != null);
P
Pilchie 已提交
1131

1132 1133 1134 1135 1136 1137 1138 1139 1140
            // SPEC: An anonymous-method-expression or lambda-expression is classified as an anonymous function. 
            // SPEC: The expression does not have a type but can be implicitly converted to a compatible delegate 
            // SPEC: type or expression tree type. Specifically, a delegate type D is compatible with an 
            // SPEC: anonymous function F provided:

            var delegateType = (NamedTypeSymbol)type;
            var invokeMethod = delegateType.DelegateInvokeMethod;

            if ((object)invokeMethod == null || invokeMethod.HasUseSiteError)
P
Pilchie 已提交
1141
            {
1142
                return LambdaConversionResult.BadTargetType;
P
Pilchie 已提交
1143 1144
            }

1145 1146 1147 1148 1149 1150 1151
            var delegateParameters = invokeMethod.Parameters;

            // SPEC: If F contains an anonymous-function-signature, then D and F have the same number of parameters.
            // SPEC: If F does not contain an anonymous-function-signature, then D may have zero or more parameters 
            // SPEC: of any type, as long as no parameter of D has the out parameter modifier.

            if (anonymousFunction.HasSignature)
P
Pilchie 已提交
1152
            {
1153 1154 1155 1156
                if (anonymousFunction.ParameterCount != invokeMethod.ParameterCount)
                {
                    return LambdaConversionResult.BadParameterCount;
                }
P
Pilchie 已提交
1157

1158 1159 1160 1161 1162 1163 1164 1165 1166
                // SPEC: If F has an explicitly typed parameter list, each parameter in D has the same type 
                // SPEC: and modifiers as the corresponding parameter in F.
                // SPEC: If F has an implicitly typed parameter list, D has no ref or out parameters.

                if (anonymousFunction.HasExplicitlyTypedParameterList)
                {
                    for (int p = 0; p < delegateParameters.Length; ++p)
                    {
                        if (delegateParameters[p].RefKind != anonymousFunction.RefKind(p) ||
C
Charles Stoner 已提交
1167
                            !delegateParameters[p].Type.TypeSymbol.Equals(anonymousFunction.ParameterType(p).TypeSymbol, TypeCompareKind.AllIgnoreOptions))
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
                        {
                            return LambdaConversionResult.MismatchedParameterType;
                        }
                    }
                }
                else
                {
                    for (int p = 0; p < delegateParameters.Length; ++p)
                    {
                        if (delegateParameters[p].RefKind != RefKind.None)
                        {
                            return LambdaConversionResult.RefInImplicitlyTypedLambda;
                        }
                    }

                    // In C# it is not possible to make a delegate type
                    // such that one of its parameter types is a static type. But static types are 
                    // in metadata just sealed abstract types; there is nothing stopping someone in
                    // another language from creating a delegate with a static type for a parameter,
                    // though the only argument you could pass for that parameter is null.
                    // 
                    // In the native compiler we forbid conversion of an anonymous function that has
                    // an implicitly-typed parameter list to a delegate type that has a static type
                    // for a formal parameter type. However, we do *not* forbid it for an explicitly-
                    // typed lambda (because we already require that the explicitly typed parameter not
                    // be static) and we do not forbid it for an anonymous method with the entire
                    // parameter list missing (because the body cannot possibly have a parameter that
                    // is of static type, even though this means that we will be generating a hidden
                    // method with a parameter of static type.)
                    //
                    // We also allow more exotic situations to work in the native compiler. For example,
                    // though it is not possible to convert x=>{} to Action<GC>, it is possible to convert
                    // it to Action<List<GC>> should there be a language that allows you to construct 
                    // a variable of that type.
                    //
                    // We might consider beefing up this rule to disallow a conversion of *any* anonymous
                    // function to *any* delegate that has a static type *anywhere* in the parameter list.

                    for (int p = 0; p < delegateParameters.Length; ++p)
                    {
                        if (delegateParameters[p].Type.IsStatic)
                        {
                            return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda;
                        }
                    }
                }
            }
            else
P
Pilchie 已提交
1216
            {
1217 1218 1219 1220 1221 1222 1223
                for (int p = 0; p < delegateParameters.Length; ++p)
                {
                    if (delegateParameters[p].RefKind == RefKind.Out)
                    {
                        return LambdaConversionResult.MissingSignatureWithOutParameter;
                    }
                }
P
Pilchie 已提交
1224 1225
            }

1226 1227 1228
            // Ensure the body can be converted to that delegate type
            var bound = anonymousFunction.Bind(delegateType);
            if (ErrorFacts.PreventsSuccessfulDelegateConversion(bound.Diagnostics))
P
Pilchie 已提交
1229
            {
1230
                return LambdaConversionResult.BindingFailed;
P
Pilchie 已提交
1231 1232
            }

1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
            return LambdaConversionResult.Success;
        }

        private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type)
        {
            Debug.Assert((object)anonymousFunction != null);
            Debug.Assert((object)type != null);
            Debug.Assert(type.IsExpressionTree());

            // SPEC OMISSION:
            // 
            // The C# 3 spec said that anonymous methods and statement lambdas are *convertible* to expression tree
            // types if the anonymous method/statement lambda is convertible to its delegate type; however, actually
            // *using* such a conversion is an error. However, that is not what we implemented. In C# 3 we implemented
            // that an anonymous method is *not convertible* to an expression tree type, period. (Statement lambdas
            // used the rule described in the spec.)  
            //
            // This appears to be a spec omission; the intention is to make old-style anonymous methods not 
            // convertible to expression trees.

C
Charles Stoner 已提交
1253
            var delegateType = type.TypeArgumentsNoUseSiteDiagnostics[0].TypeSymbol;
1254
            if (!delegateType.IsDelegateType())
P
Pilchie 已提交
1255
            {
1256
                return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument;
P
Pilchie 已提交
1257 1258
            }

1259
            if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression)
P
Pilchie 已提交
1260
            {
1261
                return LambdaConversionResult.ExpressionTreeFromAnonymousMethod;
P
Pilchie 已提交
1262 1263
            }

1264 1265 1266 1267 1268 1269 1270 1271 1272
            return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, delegateType);
        }

        public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type)
        {
            Debug.Assert((object)anonymousFunction != null);
            Debug.Assert((object)type != null);

            if (type.IsDelegateType())
P
Pilchie 已提交
1273
            {
1274
                return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type);
P
Pilchie 已提交
1275
            }
1276
            else if (type.IsExpressionTree())
P
Pilchie 已提交
1277
            {
1278
                return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type);
P
Pilchie 已提交
1279 1280
            }

1281 1282 1283 1284 1285 1286 1287 1288 1289
            return LambdaConversionResult.BadTargetType;
        }

        private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination)
        {
            Debug.Assert(source != null);
            Debug.Assert((object)destination != null);

            if (source.Kind != BoundKind.UnboundLambda)
P
Pilchie 已提交
1290
            {
1291
                return false;
P
Pilchie 已提交
1292 1293
            }

1294 1295 1296
            return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination) == LambdaConversionResult.Success;
        }

N
Neal Gafter 已提交
1297
        internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
        {
            // SPEC:    The governing type of a switch statement is established by the switch expression.
            // SPEC:    1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint,
            // SPEC:       long, ulong, bool, char, string, or an enum-type, or if it is the nullable type
            // SPEC:       corresponding to one of these types, then that is the governing type of the switch statement. 
            // SPEC:    2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the
            // SPEC:       type of the switch expression to one of the following possible governing types:
            // SPEC:       sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type
            // SPEC:       corresponding to one of those types

            // NOTE:    We should be called only if (1) is false for source type.
            Debug.Assert((object)sourceType != null);
N
Neal Gafter 已提交
1310
            Debug.Assert(!sourceType.IsValidV6SwitchGoverningType());
1311

N
Neal Gafter 已提交
1312
            UserDefinedConversionResult result = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteDiagnostics);
1313 1314

            if (result.Kind == UserDefinedConversionResultKind.Valid)
P
Pilchie 已提交
1315
            {
1316 1317 1318
                UserDefinedConversionAnalysis analysis = result.Results[result.Best];

                switchGoverningType = analysis.ToType;
N
Neal Gafter 已提交
1319
                Debug.Assert(switchGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true));
1320 1321 1322 1323
            }
            else
            {
                switchGoverningType = null;
P
Pilchie 已提交
1324 1325
            }

1326
            return new Conversion(result, isImplicit: true);
P
Pilchie 已提交
1327 1328
        }

1329
        internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
P
Pilchie 已提交
1330
        {
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
            var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken));
            var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0);

            TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32);
            BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType);
            return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteDiagnostics);
        }

        internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            return GetCallerLineNumberConversion(destination, ref useSiteDiagnostics).Exists;
        }

        internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_String);
            Conversion conversion = ClassifyStandardImplicitConversion(expectedAttributeType, destination, ref useSiteDiagnostics);
            return conversion.Exists;
P
Pilchie 已提交
1349 1350 1351
        }

        public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2)
1352 1353 1354 1355 1356
        {
            return HasIdentityConversionInternal(type1, type2, includeNullability: false);
        }

        private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability)
P
Pilchie 已提交
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
        {
            // Spec (6.1.1):
            // An identity conversion converts from any type to the same type. This conversion exists 
            // such that an entity that already has a required type can be said to be convertible to 
            // that type.
            //
            // Because object and dynamic are considered equivalent there is an identity conversion 
            // between object and dynamic, and between constructed types that are the same when replacing 
            // all occurrences of dynamic with object.

            Debug.Assert((object)type1 != null);
            Debug.Assert((object)type2 != null);

1370 1371
            // Note, when we are paying attention to nullability, we ignore insignificant differences and oblivious mismatch. 
            // See TypeCompareKind.UnknownNullableModifierMatchesAny and TypeCompareKind.IgnoreInsignificantNullableModifiersDifference
1372
            var compareKind = includeNullability ?
1373
                TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes :
1374 1375 1376 1377 1378 1379 1380 1381 1382
                TypeCompareKind.AllIgnoreOptions;
            return type1.Equals(type2, compareKind);
        }

        private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2)
        {
            return HasIdentityConversionInternal(type1, type2, IncludeNullability);
        }

1383 1384 1385 1386 1387 1388
        /// <summary>
        /// Returns true if:
        /// - Either type has no nullability information (oblivious).
        /// - Both types cannot have different nullability at the same time,
        ///   including the case of type parameters that by themselves can represent nullable and not nullable reference types.
        /// </summary>
1389
        internal bool HasTopLevelNullabilityIdentityConversion(TypeSymbolWithAnnotations source, TypeSymbolWithAnnotations destination)
1390
        {
1391 1392 1393 1394
            if (!IncludeNullability)
            {
                return true;
            }
1395

1396
            if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious())
1397 1398 1399 1400
            {
                return true;
            }

1401
            if (source.IsPossiblyNullableTypeTypeParameter() && !destination.IsPossiblyNullableTypeTypeParameter())
1402
            {
1403
                return destination.NullableAnnotation.IsAnnotated();
1404 1405
            }

1406
            if (destination.IsPossiblyNullableTypeTypeParameter() && !source.IsPossiblyNullableTypeTypeParameter())
1407
            {
1408
                return source.NullableAnnotation.IsAnnotated();
1409 1410
            }

1411
            return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated();
1412 1413
        }

1414 1415 1416 1417 1418
        /// <summary>
        /// Returns false if source type can be nullable at the same time when destination type can be not nullable, 
        /// including the case of type parameters that by themselves can represent nullable and not nullable reference types.
        /// When either type has no nullability information (oblivious), this method returns true.
        /// </summary>
1419
        internal bool HasTopLevelNullabilityImplicitConversion(TypeSymbolWithAnnotations source, TypeSymbolWithAnnotations destination)
1420
        {
1421 1422 1423 1424
            if (!IncludeNullability)
            {
                return true;
            }
1425

1426
            if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated())
1427 1428 1429 1430
            {
                return true;
            }

1431
            if (source.IsPossiblyNullableTypeTypeParameter() && !destination.IsPossiblyNullableTypeTypeParameter())
1432 1433 1434 1435
            {
                return false;
            }

1436
            return !source.NullableAnnotation.IsAnnotated();
P
Pilchie 已提交
1437 1438 1439 1440 1441
        }

        public static bool HasIdentityConversionToAny<T>(T type, ArrayBuilder<T> targetTypes)
            where T : TypeSymbol
        {
1442
            foreach (var targetType in targetTypes)
P
Pilchie 已提交
1443
            {
1444
                if (HasIdentityConversionInternal(type, targetType, includeNullability: false))
P
Pilchie 已提交
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
                {
                    return true;
                }
            }

            return false;
        }

        public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)thisType != null);
1456
            var conversion = this.ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteDiagnostics);
P
Pilchie 已提交
1457 1458 1459
            return IsValidExtensionMethodThisArgConversion(conversion) ? conversion : Conversion.NoConversion;
        }

1460 1461 1462 1463 1464 1465 1466 1467 1468
        // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference,
        // or boxing conversion exists from expr to the type of the first parameter"
        public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(sourceExpressionOpt == null || (object)sourceExpressionOpt.Type == sourceType);
            Debug.Assert((object)destination != null);

            if ((object)sourceType != null)
            {
1469
                if (HasIdentityConversionInternal(sourceType, destination))
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
                {
                    return Conversion.Identity;
                }

                if (HasBoxingConversion(sourceType, destination, ref useSiteDiagnostics))
                {
                    return Conversion.Boxing;
                }

                if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteDiagnostics))
                {
                    return Conversion.ImplicitReference;
                }
            }

            if (sourceExpressionOpt?.Kind == BoundKind.TupleLiteral)
            {
1487 1488 1489
                // GetTupleLiteralConversion is not used with IncludeNullability currently.
                // If that changes, the delegate below will need to consider top-level nullability.
                Debug.Assert(!IncludeNullability);
1490 1491 1492 1493 1494
                var tupleConversion = GetTupleLiteralConversion(
                    (BoundTupleLiteral)sourceExpressionOpt,
                    destination,
                    ref useSiteDiagnostics,
                    ConversionKind.ImplicitTupleLiteral,
1495 1496
                    (ConversionsBase conversions, BoundExpression s, TypeSymbolWithAnnotations d, ref HashSet<DiagnosticInfo> u, bool a) =>
                        conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.TypeSymbol, ref u),
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
                    arg: false);
                if (tupleConversion.Exists)
                {
                    return tupleConversion;
                }
            }

            if ((object)sourceType != null)
            {
                var tupleConversion = ClassifyTupleConversion(
                    sourceType,
                    destination,
                    ref useSiteDiagnostics,
                    ConversionKind.ImplicitTuple,
1511
                    (ConversionsBase conversions, TypeSymbolWithAnnotations s, TypeSymbolWithAnnotations d, ref HashSet<DiagnosticInfo> u, bool a) =>
1512
                    {
1513
                        if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d))
1514 1515 1516 1517 1518
                        {
                            return Conversion.NoConversion;
                        }
                        return conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.TypeSymbol, d.TypeSymbol, ref u);
                    },
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
                    arg: false);
                if (tupleConversion.Exists)
                {
                    return tupleConversion;
                }
            }

            return Conversion.NoConversion;
        }

        // It should be possible to remove IsValidExtensionMethodThisArgConversion
        // since ClassifyImplicitExtensionMethodThisArgConversion should only
        // return valid conversions. https://github.com/dotnet/roslyn/issues/19622

P
Pilchie 已提交
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
        // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference,
        // or boxing conversion exists from expr to the type of the first parameter"
        public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion)
        {
            switch (conversion.Kind)
            {
                case ConversionKind.Identity:
                case ConversionKind.Boxing:
                case ConversionKind.ImplicitReference:
                    return true;
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555

                case ConversionKind.ImplicitTuple:
                case ConversionKind.ImplicitTupleLiteral:
                    // check if all element conversions satisfy the requirement
                    foreach (var elementConversion in conversion.UnderlyingConversions)
                    {
                        if (!IsValidExtensionMethodThisArgConversion(elementConversion))
                        {
                            return false;
                        }
                    }
                    return true;

P
Pilchie 已提交
1556
                default:
1557 1558
                    // Caller should have not have calculated another conversion.
                    Debug.Assert(conversion.Kind == ConversionKind.NoConversion);
P
Pilchie 已提交
1559 1560 1561 1562 1563 1564 1565 1566 1567
                    return false;
            }
        }

        private const bool F = false;
        private const bool T = true;

        // Notice that there is no implicit numeric conversion from a type to itself. That's an
        // identity conversion.
1568
        private static readonly bool[,] s_implicitNumericConversions =
P
Pilchie 已提交
1569
        {
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
            // to     sb  b  s  us i ui  l ul  c  f  d  m
            // from
            /* sb */
         { F, F, T, F, T, F, T, F, F, T, T, T },
            /*  b */
         { F, F, T, T, T, T, T, T, F, T, T, T },
            /*  s */
         { F, F, F, F, T, F, T, F, F, T, T, T },
            /* us */
         { F, F, F, F, T, T, T, T, F, T, T, T },
            /*  i */
         { F, F, F, F, F, F, T, F, F, T, T, T },
            /* ui */
         { F, F, F, F, F, F, T, T, F, T, T, T },
            /*  l */
         { F, F, F, F, F, F, F, F, F, T, T, T },
            /* ul */
         { F, F, F, F, F, F, F, F, F, T, T, T },
            /*  c */
         { F, F, F, T, T, T, T, T, F, T, T, T },
            /*  f */
         { F, F, F, F, F, F, F, F, F, F, T, F },
            /*  d */
         { F, F, F, F, F, F, F, F, F, F, F, F },
            /*  m */
         { F, F, F, F, F, F, F, F, F, F, F, F }
P
Pilchie 已提交
1596 1597
        };

1598
        private static readonly bool[,] s_explicitNumericConversions =
P
Pilchie 已提交
1599
        {
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
            // to     sb  b  s us  i ui  l ul  c  f  d  m
            // from
            /* sb */
         { F, T, F, T, F, T, F, T, T, F, F, F },
            /*  b */
         { T, F, F, F, F, F, F, F, T, F, F, F },
            /*  s */
         { T, T, F, T, F, T, F, T, T, F, F, F },
            /* us */
         { T, T, T, F, F, F, F, F, T, F, F, F },
            /*  i */
         { T, T, T, T, F, T, F, T, T, F, F, F },
            /* ui */
         { T, T, T, T, T, F, F, F, T, F, F, F },
            /*  l */
         { T, T, T, T, T, T, F, T, T, F, F, F },
            /* ul */
         { T, T, T, T, T, T, T, F, T, F, F, F },
            /*  c */
         { T, T, T, F, F, F, F, F, F, F, F, F },
            /*  f */
         { T, T, T, T, T, T, T, T, T, F, F, T },
            /*  d */
         { T, T, T, T, T, T, T, T, T, T, F, T },
            /*  m */
         { T, T, T, T, T, T, T, T, T, T, T, F }
P
Pilchie 已提交
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
        };

        private static int GetNumericTypeIndex(SpecialType specialType)
        {
            switch (specialType)
            {
                case SpecialType.System_SByte: return 0;
                case SpecialType.System_Byte: return 1;
                case SpecialType.System_Int16: return 2;
                case SpecialType.System_UInt16: return 3;
                case SpecialType.System_Int32: return 4;
                case SpecialType.System_UInt32: return 5;
                case SpecialType.System_Int64: return 6;
                case SpecialType.System_UInt64: return 7;
                case SpecialType.System_Char: return 8;
                case SpecialType.System_Single: return 9;
                case SpecialType.System_Double: return 10;
                case SpecialType.System_Decimal: return 11;
                default: return -1;
            }
        }

        private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            int sourceIndex = GetNumericTypeIndex(source.SpecialType);
            if (sourceIndex < 0)
            {
                return false;
            }

            int destinationIndex = GetNumericTypeIndex(destination.SpecialType);
            if (destinationIndex < 0)
            {
                return false;
            }

1665
            return s_implicitNumericConversions[sourceIndex, destinationIndex];
P
Pilchie 已提交
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
        }

        private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination)
        {
            // SPEC: The explicit numeric conversions are the conversions from a numeric-type to another 
            // SPEC: numeric-type for which an implicit numeric conversion does not already exist.
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            int sourceIndex = GetNumericTypeIndex(source.SpecialType);
            if (sourceIndex < 0)
            {
                return false;
            }

            int destinationIndex = GetNumericTypeIndex(destination.SpecialType);
            if (destinationIndex < 0)
            {
                return false;
            }

1687
            return s_explicitNumericConversions[sourceIndex, destinationIndex];
P
Pilchie 已提交
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
        }

        public static bool IsConstantNumericZero(ConstantValue value)
        {
            switch (value.Discriminator)
            {
                case ConstantValueTypeDiscriminator.SByte:
                    return value.SByteValue == 0;
                case ConstantValueTypeDiscriminator.Byte:
                    return value.ByteValue == 0;
                case ConstantValueTypeDiscriminator.Int16:
                    return value.Int16Value == 0;
                case ConstantValueTypeDiscriminator.Int32:
                    return value.Int32Value == 0;
                case ConstantValueTypeDiscriminator.Int64:
                    return value.Int64Value == 0;
                case ConstantValueTypeDiscriminator.UInt16:
                    return value.UInt16Value == 0;
                case ConstantValueTypeDiscriminator.UInt32:
                    return value.UInt32Value == 0;
                case ConstantValueTypeDiscriminator.UInt64:
                    return value.UInt64Value == 0;
                case ConstantValueTypeDiscriminator.Single:
                case ConstantValueTypeDiscriminator.Double:
                    return value.DoubleValue == 0;
                case ConstantValueTypeDiscriminator.Decimal:
                    return value.DecimalValue == 0;
            }
            return false;
        }

        public static bool IsNumericType(SpecialType specialType)
        {
            switch (specialType)
            {
                case SpecialType.System_Char:
                case SpecialType.System_SByte:
                case SpecialType.System_Byte:
                case SpecialType.System_Int16:
                case SpecialType.System_UInt16:
                case SpecialType.System_Int32:
                case SpecialType.System_UInt32:
                case SpecialType.System_Int64:
                case SpecialType.System_UInt64:
                case SpecialType.System_Single:
                case SpecialType.System_Double:
                case SpecialType.System_Decimal:
                    return true;
                default:
                    return false;
            }
        }

        private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)target != null);

            // There are only a total of twelve user-defined explicit conversions on IntPtr and UIntPtr:
            //
            // IntPtr  <---> int
            // IntPtr  <---> long
            // IntPtr  <---> void*
            // UIntPtr <---> uint
            // UIntPtr <---> ulong
            // UIntPtr <---> void*
            //
            // The specification says that you can put any *standard* implicit or explicit conversion
            // on "either side" of a user-defined explicit conversion, so the specification allows, say,
            // UIntPtr --> byte because the conversion UIntPtr --> uint is user-defined and the 
            // conversion uint --> byte is "standard". It is "standard" because the conversion 
            // byte --> uint is an implicit numeric conversion.

            // This means that certain conversions should be illegal. For example, IntPtr --> ulong
            // should be illegal because none of int --> ulong, long --> ulong and void* --> ulong 
            // are "standard" conversions. 

            // Similarly, some conversions involving IntPtr should be illegal because they are 
            // ambiguous. byte --> IntPtr?, for example, is ambiguous. (There are four possible
            // UD operators: int --> IntPtr and long --> IntPtr, and their lifted versions. The
            // best possible source type is int, the best possible target type is IntPtr?, and
            // there is an ambiguity between the unlifted int --> IntPtr, and the lifted 
            // int? --> IntPtr? conversions.)

            // In practice, the native compiler, and hence, the Roslyn compiler, allows all 
            // these conversions. Any conversion from a numeric type to IntPtr, or from an IntPtr
            // to a numeric type, is allowed. Also, any conversion from a pointer type to IntPtr
            // or vice versa is allowed.

            var s0 = source.StrippedType();
            var t0 = target.StrippedType();

            if (s0.SpecialType != SpecialType.System_UIntPtr &&
                s0.SpecialType != SpecialType.System_IntPtr &&
                t0.SpecialType != SpecialType.System_UIntPtr &&
                t0.SpecialType != SpecialType.System_IntPtr)
            {
                return false;
            }

            TypeSymbol otherType = (s0.SpecialType == SpecialType.System_UIntPtr || s0.SpecialType == SpecialType.System_IntPtr) ? t0 : s0;

1790
            if (otherType.TypeKind == TypeKind.Pointer)
P
Pilchie 已提交
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
            {
                return true;
            }

            if (otherType.TypeKind == TypeKind.Enum)
            {
                return true;
            }

            switch (otherType.SpecialType)
            {
                case SpecialType.System_SByte:
                case SpecialType.System_Byte:
                case SpecialType.System_Int16:
                case SpecialType.System_UInt16:
                case SpecialType.System_Char:
                case SpecialType.System_Int32:
                case SpecialType.System_UInt32:
                case SpecialType.System_Int64:
                case SpecialType.System_UInt64:
                case SpecialType.System_Double:
                case SpecialType.System_Single:
                case SpecialType.System_Decimal:
                    return true;
            }

            return false;
        }

        private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            // SPEC: The explicit enumeration conversions are:
            // SPEC: From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or decimal to any enum-type.
            // SPEC: From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or decimal.
            // SPEC: From any enum-type to any other enum-type.

            if (IsNumericType(source.SpecialType) && destination.IsEnumType())
            {
                return true;
            }

            if (IsNumericType(destination.SpecialType) && source.IsEnumType())
            {
                return true;
            }

            if (source.IsEnumType() && destination.IsEnumType())
            {
                return true;
            }

            return false;
        }

V
VSadov 已提交
1848
        private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
P
Pilchie 已提交
1849 1850 1851 1852 1853
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            // SPEC: Predefined implicit conversions that operate on non-nullable value types can also be used with 
1854
            // SPEC: nullable forms of those types. For each of the predefined implicit identity, numeric and tuple conversions
P
Pilchie 已提交
1855 1856
            // SPEC: that convert from a non-nullable value type S to a non-nullable value type T, the following implicit 
            // SPEC: nullable conversions exist:
1857 1858
            // SPEC: * An implicit conversion from S? to T?.
            // SPEC: * An implicit conversion from S to T?.
P
Pilchie 已提交
1859 1860
            if (!destination.IsNullableType())
            {
V
VSadov 已提交
1861
                return Conversion.NoConversion;
P
Pilchie 已提交
1862 1863 1864 1865 1866 1867 1868
            }

            TypeSymbol unwrappedDestination = destination.GetNullableUnderlyingType();
            TypeSymbol unwrappedSource = source.StrippedType();

            if (!unwrappedSource.IsValueType)
            {
V
VSadov 已提交
1869
                return Conversion.NoConversion;
P
Pilchie 已提交
1870 1871
            }

1872
            if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination))
P
Pilchie 已提交
1873
            {
V
VSadov 已提交
1874
                return new Conversion(ConversionKind.ImplicitNullable, Conversion.IdentityUnderlying);
P
Pilchie 已提交
1875 1876 1877 1878
            }

            if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination))
            {
V
VSadov 已提交
1879
                return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitNumericUnderlying);
P
Pilchie 已提交
1880 1881
            }

1882 1883
            var tupleConversion = ClassifyImplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteDiagnostics);
            if (tupleConversion.Exists)
1884
            {
1885
                return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(tupleConversion));
1886 1887
            }

V
VSadov 已提交
1888
            return Conversion.NoConversion;
P
Pilchie 已提交
1889 1890
        }

1891
        private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeSymbolWithAnnotations destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool arg);
1892
        private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeSymbolWithAnnotations source, TypeSymbolWithAnnotations destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool arg);
1893 1894

        private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
1895
        {
1896 1897 1898
            // GetTupleLiteralConversion is not used with IncludeNullability currently.
            // If that changes, the delegate below will need to consider top-level nullability.
            Debug.Assert(!IncludeNullability);
1899 1900 1901 1902 1903
            return GetTupleLiteralConversion(
                source,
                destination,
                ref useSiteDiagnostics,
                ConversionKind.ImplicitTupleLiteral,
1904 1905
                (ConversionsBase conversions, BoundExpression s, TypeSymbolWithAnnotations d, ref HashSet<DiagnosticInfo> u, bool a)
                    => conversions.ClassifyImplicitConversionFromExpression(s, d.TypeSymbol, ref u),
1906 1907
                arg: false);
        }
1908

1909 1910
        private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast)
        {
1911 1912 1913
            // GetTupleLiteralConversion is not used with IncludeNullability currently.
            // If that changes, the delegate below will need to consider top-level nullability.
            Debug.Assert(!IncludeNullability);
1914 1915 1916 1917 1918
            return GetTupleLiteralConversion(
                source,
                destination,
                ref useSiteDiagnostics,
                ConversionKind.ExplicitTupleLiteral,
1919
                (ConversionsBase conversions, BoundExpression s, TypeSymbolWithAnnotations d, ref HashSet<DiagnosticInfo> u, bool a) => conversions.ClassifyConversionFromExpression(s, d.TypeSymbol, ref u, a),
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
                forCast);
        }

        private Conversion GetTupleLiteralConversion(
            BoundTupleLiteral source,
            TypeSymbol destination,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics,
            ConversionKind kind,
            ClassifyConversionFromExpressionDelegate classifyConversion,
            bool arg)
        {
            var arguments = source.Arguments;

            // check if the type is actually compatible type for a tuple of given cardinality
            if (!destination.IsTupleOrCompatibleWithTupleOfCardinality(arguments.Length))
1935
            {
1936
                return Conversion.NoConversion;
1937 1938
            }

1939
            var targetElementTypes = destination.GetElementTypesOfTupleOrCompatible();
1940 1941 1942 1943 1944
            Debug.Assert(arguments.Length == targetElementTypes.Length);

            // check arguments against flattened list of target element types 
            var argumentConversions = ArrayBuilder<Conversion>.GetInstance(arguments.Length);
            for (int i = 0; i < arguments.Length; i++)
1945
            {
1946
                var argument = arguments[i];
1947
                var result = classifyConversion(this, argument, targetElementTypes[i], ref useSiteDiagnostics, arg);
1948
                if (!result.Exists)
1949
                {
1950
                    argumentConversions.Free();
1951 1952 1953
                    return Conversion.NoConversion;
                }

1954
                argumentConversions.Add(result);
1955 1956
            }

1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
            return new Conversion(kind, argumentConversions.ToImmutableAndFree());
        }

        private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            return ClassifyTupleConversion(
                source,
                destination,
                ref useSiteDiagnostics,
                ConversionKind.ImplicitTuple,
1967 1968
                (ConversionsBase conversions, TypeSymbolWithAnnotations s, TypeSymbolWithAnnotations d, ref HashSet<DiagnosticInfo> u, bool a) =>
                {
1969
                    if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d))
1970 1971 1972 1973 1974
                    {
                        return Conversion.NoConversion;
                    }
                    return conversions.ClassifyImplicitConversionFromType(s.TypeSymbol, d.TypeSymbol, ref u);
                },
1975
                arg: false);
1976 1977 1978
        }

        private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast)
1979 1980 1981 1982 1983 1984
        {
            return ClassifyTupleConversion(
                source,
                destination,
                ref useSiteDiagnostics,
                ConversionKind.ExplicitTuple,
1985
                (ConversionsBase conversions, TypeSymbolWithAnnotations s, TypeSymbolWithAnnotations d, ref HashSet<DiagnosticInfo> u, bool a) =>
1986
                {
1987
                    if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d))
1988 1989 1990 1991 1992
                    {
                        return Conversion.NoConversion;
                    }
                    return conversions.ClassifyConversionFromType(s.TypeSymbol, d.TypeSymbol, ref u, a);
                },
1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
                forCast);
        }

        private Conversion ClassifyTupleConversion(
            TypeSymbol source,
            TypeSymbol destination,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics,
            ConversionKind kind,
            ClassifyConversionFromTypeDelegate classifyConversion,
            bool arg)
2003
        {
2004 2005
            ImmutableArray<TypeSymbolWithAnnotations> sourceTypes;
            ImmutableArray<TypeSymbolWithAnnotations> destTypes;
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016

            if (!source.TryGetElementTypesIfTupleOrCompatible(out sourceTypes) ||
                !destination.TryGetElementTypesIfTupleOrCompatible(out destTypes) ||
                sourceTypes.Length != destTypes.Length)
            {
                return Conversion.NoConversion;
            }

            var nestedConversions = ArrayBuilder<Conversion>.GetInstance(sourceTypes.Length);
            for (int i = 0; i < sourceTypes.Length; i++)
            {
2017
                var conversion = classifyConversion(this, sourceTypes[i], destTypes[i], ref useSiteDiagnostics, arg);
2018 2019 2020 2021
                if (!conversion.Exists)
                {
                    nestedConversions.Free();
                    return Conversion.NoConversion;
2022
                }
2023 2024

                nestedConversions.Add(conversion);
2025 2026
            }

2027
            return new Conversion(kind, nestedConversions.ToImmutableAndFree());
P
Pilchie 已提交
2028 2029
        }

2030
        private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast)
P
Pilchie 已提交
2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            // SPEC: Explicit nullable conversions permit predefined explicit conversions that operate on 
            // SPEC: non-nullable value types to also be used with nullable forms of those types. For 
            // SPEC: each of the predefined explicit conversions that convert from a non-nullable value type 
            // SPEC: S to a non-nullable value type T, the following nullable conversions exist:
            // SPEC: An explicit conversion from S? to T?.
            // SPEC: An explicit conversion from S to T?.
            // SPEC: An explicit conversion from S? to T.

            if (!source.IsNullableType() && !destination.IsNullableType())
            {
2045
                return Conversion.NoConversion;
P
Pilchie 已提交
2046 2047
            }

2048 2049
            TypeSymbol unwrappedSource = source.StrippedType();
            TypeSymbol unwrappedDestination = destination.StrippedType();
P
Pilchie 已提交
2050

2051
            if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination))
P
Pilchie 已提交
2052
            {
V
VSadov 已提交
2053
                return new Conversion(ConversionKind.ExplicitNullable, Conversion.IdentityUnderlying);
P
Pilchie 已提交
2054 2055
            }

2056
            if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination))
P
Pilchie 已提交
2057
            {
V
VSadov 已提交
2058
                return new Conversion(ConversionKind.ExplicitNullable, Conversion.ImplicitNumericUnderlying);
P
Pilchie 已提交
2059 2060
            }

2061
            if (HasExplicitNumericConversion(unwrappedSource, unwrappedDestination))
P
Pilchie 已提交
2062
            {
V
VSadov 已提交
2063
                return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitNumericUnderlying);
P
Pilchie 已提交
2064 2065
            }

2066 2067
            var tupleConversion = ClassifyExplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteDiagnostics, forCast);
            if (tupleConversion.Exists)
P
Pilchie 已提交
2068
            {
2069
                return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(tupleConversion));
P
Pilchie 已提交
2070 2071
            }

2072
            if (HasExplicitEnumerationConversion(unwrappedSource, unwrappedDestination))
P
Pilchie 已提交
2073
            {
V
VSadov 已提交
2074
                return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitEnumerationUnderlying);
P
Pilchie 已提交
2075 2076
            }

2077 2078
            if (HasPointerToIntegerConversion(unwrappedSource, unwrappedDestination))
            {
V
VSadov 已提交
2079
                return new Conversion(ConversionKind.ExplicitNullable, Conversion.PointerToIntegerUnderlying);
2080 2081 2082
            }

            return Conversion.NoConversion;
P
Pilchie 已提交
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
        }

        private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);
            var s = source as ArrayTypeSymbol;
            var d = destination as ArrayTypeSymbol;
            if ((object)s == null || (object)d == null)
            {
                return false;
            }

            // * S and T differ only in element type. In other words, S and T have the same number of dimensions.
2097 2098 2099 2100 2101
            if (!s.HasSameShapeAs(d))
            {
                return false;
            }

P
Pilchie 已提交
2102 2103
            // * Both SE and TE are reference types.
            // * An implicit reference conversion exists from SE to TE.
2104
            return HasImplicitReferenceConversion(s.ElementType, d.ElementType, ref useSiteDiagnostics);
P
Pilchie 已提交
2105 2106 2107 2108 2109 2110
        }

        public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);
2111 2112

            if (HasIdentityConversionInternal(source, destination))
P
Pilchie 已提交
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
            {
                return true;
            }

            return HasImplicitReferenceConversion(source, destination, ref useSiteDiagnostics);
        }

        private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination)
        {
            // Spec (§6.1.8)
            // An implicit dynamic conversion exists from an expression of type dynamic to any type T.

            Debug.Assert((object)destination != null);
2126
            return expressionType?.Kind == SymbolKind.DynamicType && !destination.IsPointerType();
P
Pilchie 已提交
2127 2128 2129 2130
        }

        private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination)
        {
2131 2132
            // SPEC: An explicit dynamic conversion exists from an expression of [sic] type dynamic to any type T.
            // ISSUE: The "an expression of" part of the spec is probably an error; see https://github.com/dotnet/csharplang/issues/132
P
Pilchie 已提交
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143

            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);
            return source.Kind == SymbolKind.DynamicType && !destination.IsPointerType();
        }

        private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

2144
            if (!source.IsSZArray)
P
Pilchie 已提交
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
            {
                return false;
            }

            if (!destination.IsInterfaceType())
            {
                return false;
            }

            // The specification says that there is a conversion:

            // * From a single-dimensional array type S[] to IList<T> and its base
            //   interfaces, provided that there is an implicit identity or reference
            //   conversion from S to T.
            //
            // Newer versions of the framework also have arrays be convertible to
2161
            // IReadOnlyList<T> and IReadOnlyCollection<T>; we honor that as well.
P
Pilchie 已提交
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188
            //
            // Therefore we must check for:
            //
            // IList<T>
            // ICollection<T>
            // IEnumerable<T>
            // IEnumerable
            // IReadOnlyList<T>
            // IReadOnlyCollection<T>

            if (destination.SpecialType == SpecialType.System_Collections_IEnumerable)
            {
                return true;
            }

            NamedTypeSymbol destinationAgg = (NamedTypeSymbol)destination;

            if (destinationAgg.AllTypeArgumentCount() != 1)
            {
                return false;
            }

            if (!destinationAgg.IsPossibleArrayGenericInterface())
            {
                return false;
            }

2189
            TypeSymbol argument0 = destinationAgg.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteDiagnostics).TypeSymbol;
P
Pilchie 已提交
2190

2191
            return HasIdentityOrImplicitReferenceConversion(source.ElementType.TypeSymbol, argument0, ref useSiteDiagnostics);
P
Pilchie 已提交
2192 2193
        }

2194 2195
        private bool HasImplicitReferenceConversion(TypeSymbolWithAnnotations source, TypeSymbolWithAnnotations destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
2196
            if (IncludeNullability)
2197
            {
2198 2199 2200 2201 2202 2203
                if (!HasTopLevelNullabilityImplicitConversion(source, destination))
                {
                    return false;
                }
                // Check for identity conversion of underlying types if the top-level nullability is distinct.
                // (An identity conversion where nullability matches is not considered an implicit reference conversion.)
2204
                if (source.NullableAnnotation != destination.NullableAnnotation &&
2205 2206 2207 2208
                    HasIdentityConversionInternal(source.TypeSymbol, destination.TypeSymbol, includeNullability: true))
                {
                    return true;
                }
2209 2210 2211 2212
            }
            return HasImplicitReferenceConversion(source.TypeSymbol, destination.TypeSymbol, ref useSiteDiagnostics);
        }

P
Pilchie 已提交
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
        private bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            if (source.IsErrorType())
            {
                return false;
            }

            if (!source.IsReferenceType)
            {
                return false;
            }

            // SPEC: The implicit reference conversions are:

            // SPEC: UNDONE: From any reference-type to a reference-type T if it has an implicit identity 
            // SPEC: UNDONE: or reference conversion to a reference-type T0 and T0 has an identity conversion to T.
            // UNDONE: Is the right thing to do here to strip dynamic off and check for convertibility?

            // SPEC: From any reference type to object and dynamic.
            if (destination.SpecialType == SpecialType.System_Object || destination.Kind == SymbolKind.DynamicType)
            {
                return true;
            }

            switch (source.TypeKind)
            {
                case TypeKind.Class:
                    // SPEC:  From any class type S to any class type T provided S is derived from T.
                    if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteDiagnostics))
                    {
                        return true;
                    }

2249
                    return HasImplicitConversionToInterface(source, destination, ref useSiteDiagnostics);
P
Pilchie 已提交
2250 2251 2252 2253

                case TypeKind.Interface:
                    // SPEC: From any interface-type S to any interface-type T, provided S is derived from T.
                    // NOTE: This handles variance conversions
2254
                    return HasImplicitConversionToInterface(source, destination, ref useSiteDiagnostics);
P
Pilchie 已提交
2255 2256 2257 2258

                case TypeKind.Delegate:
                    // SPEC: From any delegate-type to System.Delegate and the interfaces it implements.
                    // NOTE: This handles variance conversions.
2259
                    return HasImplicitConversionFromDelegate(source, destination, ref useSiteDiagnostics);
P
Pilchie 已提交
2260 2261

                case TypeKind.TypeParameter:
2262
                    return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteDiagnostics);
P
Pilchie 已提交
2263

2264
                case TypeKind.Array:
P
Pilchie 已提交
2265 2266 2267
                    // SPEC: From an array-type S ... to an array-type T, provided ...
                    // SPEC: From any array-type to System.Array and the interfaces it implements.
                    // SPEC: From a single-dimensional array type S[] to IList<T>, provided ...
2268
                    return HasImplicitConversionFromArray(source, destination, ref useSiteDiagnostics);
P
Pilchie 已提交
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
            }

            // UNDONE: Implicit conversions involving type parameters that are known to be reference types.

            return false;
        }

        private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            if (!destination.IsInterfaceType())
            {
                return false;
            }

            // * From any class type S to any interface type T provided S implements an interface
            //   convertible to T.
2285 2286 2287 2288 2289
            if (source.IsClassType())
            {
                return HasAnyBaseInterfaceConversion(source, destination, ref useSiteDiagnostics);
            }

P
Pilchie 已提交
2290 2291 2292 2293
            // * From any interface type S to any interface type T provided S implements an interface
            //   convertible to T.
            // * From any interface type S to any interface type T provided S is not T and S is 
            //   an interface convertible to T.
2294
            if (source.IsInterfaceType())
P
Pilchie 已提交
2295
            {
2296 2297 2298 2299
                if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteDiagnostics))
                {
                    return true;
                }
P
Pilchie 已提交
2300

2301 2302 2303 2304
                if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteDiagnostics))
                {
                    return true;
                }
P
Pilchie 已提交
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
            }

            return false;
        }

        private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            ArrayTypeSymbol s = source as ArrayTypeSymbol;
            if ((object)s == null)
            {
                return false;
            }

            // * From an array type S with an element type SE to an array type T with element type TE
            //   provided that all of the following are true:
            //   * S and T differ only in element type. In other words, S and T have the same number of dimensions.
            //   * Both SE and TE are reference types.
            //   * An implicit reference conversion exists from SE to TE.
            if (HasCovariantArrayConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            // * From any array type to System.Array or any interface implemented by System.Array.
            if (destination.GetSpecialTypeSafe() == SpecialType.System_Array)
            {
                return true;
            }

            if (IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array), ref useSiteDiagnostics))
            {
                return true;
            }

            // * From a single-dimensional array type S[] to IList<T> and its base
            //   interfaces, provided that there is an implicit identity or reference
            //   conversion from S to T.

            if (HasArrayConversionToInterface(s, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            return false;
        }

        private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            if (!source.IsDelegateType())
            {
                return false;
            }

            // * From any delegate type to System.Delegate
            // 
            // SPEC OMISSION:
            // 
            // The spec should actually say
            //
            // * From any delegate type to System.Delegate 
            // * From any delegate type to System.MulticastDelegate
            // * From any delegate type to any interface implemented by System.MulticastDelegate
            var specialDestination = destination.GetSpecialTypeSafe();

            if (specialDestination == SpecialType.System_MulticastDelegate ||
                specialDestination == SpecialType.System_Delegate ||
                IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate), ref useSiteDiagnostics))
            {
                return true;
            }

            // * From any delegate type S to a delegate type T provided S is not T and
            //   S is a delegate convertible to T

            if (HasDelegateVarianceConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            return false;
        }

        public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            if ((destination.TypeKind == TypeKind.TypeParameter) &&
                source.DependsOn((TypeParameterSymbol)destination))
            {
                return true;
            }

            return false;
        }

        private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            if (source.IsValueType)
            {
                return false; // Not a reference conversion.
            }

            // The following implicit conversions exist for a given type parameter T:
            //
            // * From T to its effective base class C.
            // * From T to any base class of C.
            // * From T to any interface implemented by C (or any interface variance-compatible with such)
            if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            // * From T to any interface type I in T's effective interface set, and
            //   from T to any base interface of I (or any interface variance-compatible with such)
            if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            // * From T to a type parameter U, provided T depends on U.
            if ((destination.TypeKind == TypeKind.TypeParameter) &&
                source.DependsOn((TypeParameterSymbol)destination))
            {
                return true;
            }

            return false;
        }

        // Spec 6.1.10: Implicit conversions involving type parameters
        private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            // * From T to its effective base class C.
            var effectiveBaseClass = source.EffectiveBaseClass(ref useSiteDiagnostics);
2450
            if (HasIdentityConversionInternal(effectiveBaseClass, destination))
P
Pilchie 已提交
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
            {
                return true;
            }

            // * From T to any base class of C.
            if (IsBaseClass(effectiveBaseClass, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            // * From T to any interface implemented by C (or any interface variance-compatible with such)
            if (HasAnyBaseInterfaceConversion(effectiveBaseClass, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            return false;
        }

        private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            if (!destination.IsInterfaceType())
            {
                return false;
            }

            // * From T to any interface type I in T's effective interface set, and
            //   from T to any base interface of I (or any interface variance-compatible with such)
            foreach (var i in source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
            {
                if (HasInterfaceVarianceConversion(i, destination, ref useSiteDiagnostics))
                {
                    return true;
                }
            }

            return false;
        }

        private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)derivedType != null);
            Debug.Assert((object)baseType != null);
            if (!baseType.IsInterfaceType())
            {
                return false;
            }

            var d = derivedType as NamedTypeSymbol;
            if ((object)d == null)
            {
                return false;
            }

            foreach (var i in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
            {
                if (HasInterfaceVarianceConversion(i, baseType, ref useSiteDiagnostics))
                {
                    return true;
                }
            }

            return false;
        }

        ////////////////////////////////////////////////////////////////////////////////
        // The rules for variant interface and delegate conversions are the same:
        //
        // An interface/delegate type S is convertible to an interface/delegate type T 
        // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all
        // parameters of U:
        //
        // * if the ith parameter of U is invariant then Si is exactly equal to Ti.
        // * if the ith parameter of U is covariant then either Si is exactly equal
        //   to Ti, or there is an implicit reference conversion from Si to Ti.
        // * if the ith parameter of U is contravariant then either Si is exactly
        //   equal to Ti, or there is an implicit reference conversion from Ti to Si.

        private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);
            NamedTypeSymbol s = source as NamedTypeSymbol;
            NamedTypeSymbol d = destination as NamedTypeSymbol;
            if ((object)s == null || (object)d == null)
            {
                return false;
            }

            if (!s.IsInterfaceType() || !d.IsInterfaceType())
            {
                return false;
            }

            return HasVariantConversion(s, d, ref useSiteDiagnostics);
        }

        private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);
            NamedTypeSymbol s = source as NamedTypeSymbol;
            NamedTypeSymbol d = destination as NamedTypeSymbol;
            if ((object)s == null || (object)d == null)
            {
                return false;
            }

            if (!s.IsDelegateType() || !d.IsDelegateType())
            {
                return false;
            }

            return HasVariantConversion(s, d, ref useSiteDiagnostics);
        }

        private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            // We check for overflows in HasVariantConversion, because they are only an issue
            // in the presence of contravariant type parameters, which are not involved in 
            // most conversions.
            // See VarianceTests for examples (e.g. TestVarianceConversionCycle, 
            // TestVarianceConversionInfiniteExpansion).
            //
            // CONSIDER: A more rigorous solution would mimic the CLI approach, which uses
            // a combination of requiring finite instantiation closures (see section 9.2 of
            // the CLI spec) and records previous conversion steps to check for cycles.
2578
            if (currentRecursionDepth >= MaximumRecursionDepth)
P
Pilchie 已提交
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593
            {
                // NOTE: The spec doesn't really address what happens if there's an overflow
                // in our conversion check.  It's sort of implied that the conversion "proof"
                // should be finite, so we'll just say that no conversion is possible.
                return false;
            }

            // Do a quick check up front to avoid instantiating a new Conversions object,
            // if possible.
            var quickResult = HasVariantConversionQuick(source, destination);
            if (quickResult.HasValue())
            {
                return quickResult.Value();
            }

2594
            return this.CreateInstance(currentRecursionDepth + 1).
P
Pilchie 已提交
2595 2596 2597
                HasVariantConversionNoCycleCheck(source, destination, ref useSiteDiagnostics);
        }

2598
        private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination)
P
Pilchie 已提交
2599 2600 2601 2602
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

2603
            if (HasIdentityConversionInternal(source, destination))
P
Pilchie 已提交
2604 2605 2606 2607 2608
            {
                return ThreeState.True;
            }

            NamedTypeSymbol typeSymbol = source.OriginalDefinition;
2609
            if (!TypeSymbol.Equals(typeSymbol, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2))
P
Pilchie 已提交
2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
            {
                return ThreeState.False;
            }

            return ThreeState.Unknown;
        }

        private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

2622 2623 2624
            var typeParameters = ArrayBuilder<TypeSymbolWithAnnotations>.GetInstance();
            var sourceTypeArguments = ArrayBuilder<TypeSymbolWithAnnotations>.GetInstance();
            var destinationTypeArguments = ArrayBuilder<TypeSymbolWithAnnotations>.GetInstance();
P
Pilchie 已提交
2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636

            try
            {
                source.OriginalDefinition.GetAllTypeArguments(typeParameters, ref useSiteDiagnostics);
                source.GetAllTypeArguments(sourceTypeArguments, ref useSiteDiagnostics);
                destination.GetAllTypeArguments(destinationTypeArguments, ref useSiteDiagnostics);

                Debug.Assert(typeParameters.Count == sourceTypeArguments.Count);
                Debug.Assert(typeParameters.Count == destinationTypeArguments.Count);

                for (int paramIndex = 0; paramIndex < typeParameters.Count; ++paramIndex)
                {
2637 2638
                    var sourceTypeArgument = sourceTypeArguments[paramIndex];
                    var destinationTypeArgument = destinationTypeArguments[paramIndex];
P
Pilchie 已提交
2639 2640

                    // If they're identical then this one is automatically good, so skip it.
2641
                    if (HasIdentityConversionInternal(sourceTypeArgument.TypeSymbol, destinationTypeArgument.TypeSymbol) &&
2642
                        HasTopLevelNullabilityIdentityConversion(sourceTypeArgument, destinationTypeArgument))
P
Pilchie 已提交
2643 2644 2645 2646
                    {
                        continue;
                    }

2647
                    TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeParameters[paramIndex].TypeSymbol;
P
Pilchie 已提交
2648

2649
                    switch (typeParameterSymbol.Variance)
P
Pilchie 已提交
2650
                    {
2651 2652
                        case VarianceKind.None:
                            return false;
P
Pilchie 已提交
2653

2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
                        case VarianceKind.Out:
                            if (!HasImplicitReferenceConversion(sourceTypeArgument, destinationTypeArgument, ref useSiteDiagnostics))
                            {
                                return false;
                            }
                            break;

                        case VarianceKind.In:
                            if (!HasImplicitReferenceConversion(destinationTypeArgument, sourceTypeArgument, ref useSiteDiagnostics))
                            {
                                return false;
                            }
                            break;

                        default:
                            throw ExceptionUtilities.UnexpectedValue(typeParameterSymbol.Variance);
P
Pilchie 已提交
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
                    }
                }
            }
            finally
            {
                typeParameters.Free();
                sourceTypeArguments.Free();
                destinationTypeArguments.Free();
            }

            return true;
        }

        // Spec 6.1.10
        private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            if (source.IsReferenceType)
            {
                return false; // Not a boxing conversion; both source and destination are references.
            }

            // The following implicit conversions exist for a given type parameter T:
            //
            // * From T to its effective base class C.
            // * From T to any base class of C.
            // * From T to any interface implemented by C (or any interface variance-compatible with such)
            if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            // * From T to any interface type I in T's effective interface set, and
            //   from T to any base interface of I (or any interface variance-compatible with such)
            if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            // SPEC: From T to a type parameter U, provided T depends on U
            if ((destination.TypeKind == TypeKind.TypeParameter) &&
                source.DependsOn((TypeParameterSymbol)destination))
            {
                return true;
            }

            // SPEC: From T to a reference type I if it has an implicit conversion to a reference 
            // SPEC: type S0 and S0 has an identity conversion to S. At run-time the conversion 
            // SPEC: is executed the same way as the conversion to S0.

            // REVIEW: If T is not known to be a reference type then the only way this clause can
            // REVIEW: come into effect is if the target type is dynamic. Is that correct?

            if (destination.Kind == SymbolKind.DynamicType)
            {
                return true;
            }

            return false;
        }

        public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            // Certain type parameter conversions are classified as boxing conversions.
            if ((source.TypeKind == TypeKind.TypeParameter) &&
                HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            // The rest of the boxing conversions only operate when going from a value type to a
            // reference type.
            if (!source.IsValueType || !destination.IsReferenceType)
            {
                return false;
            }

            // A boxing conversion exists from a nullable type to a reference type if and only if a
            // boxing conversion exists from the underlying type.
            if (source.IsNullableType())
            {
                return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteDiagnostics);
            }

            // A boxing conversion exists from any non-nullable value type to object and dynamic, to
            // System.ValueType, and to any interface type variance-compatible with one implemented
            // by the non-nullable value type.  

C
Charles Stoner 已提交
2763
            // Furthermore, an enum type can be converted to the type System.Enum.
P
Pilchie 已提交
2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811

            // We set the base class of the structs to System.ValueType, System.Enum, etc, so we can
            // just check here.

            // There are a couple of exceptions. The very special types ArgIterator, ArgumentHandle and 
            // TypedReference are not boxable: 

            if (source.IsRestrictedType())
            {
                return false;
            }

            if (destination.Kind == SymbolKind.DynamicType)
            {
                return !source.IsPointerType();
            }

            if (IsBaseClass(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            return false;
        }

        private static bool HasImplicitPointerConversion(TypeSymbol source, TypeSymbol destination)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            // SPEC: The set of implicit conversions is extended to include...
            // SPEC: ... from any pointer type to the type void*.

            PointerTypeSymbol pd = destination as PointerTypeSymbol;
            PointerTypeSymbol ps = source as PointerTypeSymbol;
            return (object)pd != null && (object)ps != null && pd.PointedAtType.SpecialType == SpecialType.System_Void;
        }

        private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

2812
            if (HasIdentityConversionInternal(source, destination))
P
Pilchie 已提交
2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
            {
                return true;
            }

            if (HasImplicitReferenceConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            if (HasExplicitReferenceConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            return false;
        }

        private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            // SPEC: The explicit reference conversions are:
            // SPEC: From object and dynamic to any other reference type.

            if (source.SpecialType == SpecialType.System_Object)
            {
                if (destination.IsReferenceType)
                {
                    return true;
                }
            }
            else if (source.Kind == SymbolKind.DynamicType && destination.IsReferenceType)
            {
                return true;
            }

            // SPEC: From any class-type S to any class-type T, provided S is a base class of T.
2851
            if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteDiagnostics))
P
Pilchie 已提交
2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921
            {
                return true;
            }

            // SPEC: From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T.
            // ISSUE: class C : IEnumerable<Mammal> { } converting this to IEnumerable<Animal> is not an explicit conversion,
            // ISSUE: it is an implicit conversion.
            if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            // SPEC: From any interface-type S to any class-type T, provided T is not sealed or provided T implements S.
            // ISSUE: What if T is sealed and implements an interface variance-convertible to S?
            // ISSUE: eg, sealed class C : IEnum<Mammal> { ... } you should be able to cast an IEnum<Animal> to C.
            if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteDiagnostics)))
            {
                return true;
            }

            // SPEC: From any interface-type S to any interface-type T, provided S is not derived from T.
            // ISSUE: This does not rule out identity conversions, which ought not to be classified as 
            // ISSUE: explicit reference conversions.
            // ISSUE: IEnumerable<Mammal> and IEnumerable<Animal> do not derive from each other but this is
            // ISSUE: not an explicit reference conversion, this is an implicit reference conversion.
            if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            // SPEC: UNDONE: From a reference type to a reference type T if it has an explicit reference conversion to a reference type T0 and T0 has an identity conversion T.
            // SPEC: UNDONE: From a reference type to an interface or delegate type T if it has an explicit reference conversion to an interface or delegate type T0 and either T0 is variance-convertible to T or T is variance-convertible to T0 (§13.1.3.2).

            if (HasExplicitArrayConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            if (HasExplicitDelegateConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            return false;
        }

        // Spec 6.2.7 Explicit conversions involving type parameters
        private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            TypeParameterSymbol s = source as TypeParameterSymbol;
            TypeParameterSymbol t = destination as TypeParameterSymbol;

            // SPEC: The following explicit conversions exist for a given type parameter T:

            // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions.
            // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions.

            // SPEC: From the effective base class C of T to T and from any base class of C to T. 
            if ((object)t != null && t.IsReferenceType)
            {
                for (var type = t.EffectiveBaseClass(ref useSiteDiagnostics); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
                {
2922
                    if (HasIdentityConversionInternal(type, source))
P
Pilchie 已提交
2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968
                    {
                        return true;
                    }
                }
            }

            // SPEC: From any interface type to T. 
            if ((object)t != null && source.IsInterfaceType() && t.IsReferenceType)
            {
                return true;
            }

            // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I.
            if ((object)s != null && s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5)
            if ((object)s != null && (object)t != null && t.IsReferenceType && t.DependsOn(s))
            {
                return true;
            }

            return false;
        }

        // Spec 6.2.7 Explicit conversions involving type parameters
        private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            TypeParameterSymbol s = source as TypeParameterSymbol;
            TypeParameterSymbol t = destination as TypeParameterSymbol;

            // SPEC: The following explicit conversions exist for a given type parameter T:

            // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions.
            // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions.

            // SPEC: From the effective base class C of T to T and from any base class of C to T. 
            if ((object)t != null && !t.IsReferenceType)
            {
                for (var type = t.EffectiveBaseClass(ref useSiteDiagnostics); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
                {
2969
                    if (TypeSymbol.Equals(type, source, TypeCompareKind.ConsiderEverything2))
P
Pilchie 已提交
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027
                    {
                        return true;
                    }
                }
            }

            // SPEC: From any interface type to T. 
            if (source.IsInterfaceType() && (object)t != null && !t.IsReferenceType)
            {
                return true;
            }

            // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I.
            if ((object)s != null && !s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5)
            if ((object)s != null && (object)t != null && !t.IsReferenceType && t.DependsOn(s))
            {
                return true;
            }

            return false;
        }

        private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            // SPEC: From System.Delegate and the interfaces it implements to any delegate-type.
            // We also support System.MulticastDelegate in the implementation, in spite of it not being mentioned in the spec.
            if (destination.IsDelegateType())
            {
                if (source.SpecialType == SpecialType.System_Delegate || source.SpecialType == SpecialType.System_MulticastDelegate)
                {
                    return true;
                }

                if (HasImplicitConversionToInterface(this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Delegate), source, ref useSiteDiagnostics))
                {
                    return true;
                }
            }

            // SPEC: From D<S1...Sn> to a D<T1...Tn> where D<X1...Xn> is a generic delegate type, D<S1...Sn> is not compatible with or identical to D<T1...Tn>, 
            // SPEC: and for each type parameter Xi of D the following holds:
            // SPEC: If Xi is invariant, then Si is identical to Ti.
            // SPEC: If Xi is covariant, then there is an implicit or explicit identity or reference conversion from Si to Ti.
            // SPECL If Xi is contravariant, then Si and Ti are either identical or both reference types.

            if (!source.IsDelegateType() || !destination.IsDelegateType())
            {
                return false;
            }

3028
            if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2))
P
Pilchie 已提交
3029 3030 3031 3032 3033 3034 3035 3036
            {
                return false;
            }

            var sourceType = (NamedTypeSymbol)source;
            var destinationType = (NamedTypeSymbol)destination;
            var original = sourceType.OriginalDefinition;

3037
            if (HasIdentityConversionInternal(source, destination))
P
Pilchie 已提交
3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051
            {
                return false;
            }

            if (HasDelegateVarianceConversion(source, destination, ref useSiteDiagnostics))
            {
                return false;
            }

            var sourceTypeArguments = sourceType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
            var destinationTypeArguments = destinationType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);

            for (int i = 0; i < sourceTypeArguments.Length; ++i)
            {
3052 3053
                var sourceArg = sourceTypeArguments[i].TypeSymbol;
                var destinationArg = destinationTypeArguments[i].TypeSymbol;
P
Pilchie 已提交
3054 3055 3056 3057

                switch (original.TypeParameters[i].Variance)
                {
                    case VarianceKind.None:
3058
                        if (!HasIdentityConversionInternal(sourceArg, destinationArg))
P
Pilchie 已提交
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071
                        {
                            return false;
                        }

                        break;
                    case VarianceKind.Out:
                        if (!HasIdentityOrReferenceConversion(sourceArg, destinationArg, ref useSiteDiagnostics))
                        {
                            return false;
                        }

                        break;
                    case VarianceKind.In:
3072
                        bool hasIdentityConversion = HasIdentityConversionInternal(sourceArg, destinationArg);
P
Pilchie 已提交
3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105
                        bool bothAreReferenceTypes = sourceArg.IsReferenceType && destinationArg.IsReferenceType;
                        if (!(hasIdentityConversion || bothAreReferenceTypes))
                        {
                            return false;
                        }

                        break;
                }
            }

            return true;
        }

        private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            var sourceArray = source as ArrayTypeSymbol;
            var destinationArray = destination as ArrayTypeSymbol;

            // SPEC: From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true:
            // SPEC: S and T differ only in element type. (In other words, S and T have the same number of dimensions.)
            // SPEC: Both SE and TE are reference-types.
            // SPEC: An explicit reference conversion exists from SE to TE.
            if ((object)sourceArray != null && (object)destinationArray != null)
            {
                // HasExplicitReferenceConversion checks that SE and TE are reference types so
                // there's no need for that check here. Moreover, it's not as simple as checking
                // IsReferenceType, at least not in the case of type parameters, since SE will be
                // considered a reference type implicitly in the case of "where TE : class, SE" even
                // though SE.IsReferenceType may be false. Again, HasExplicitReferenceConversion
                // already handles these cases.
3106
                return sourceArray.HasSameShapeAs(destinationArray) &&
3107
                    HasExplicitReferenceConversion(sourceArray.ElementType.TypeSymbol, destinationArray.ElementType.TypeSymbol, ref useSiteDiagnostics);
P
Pilchie 已提交
3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119
            }

            // SPEC: From System.Array and the interfaces it implements to any array-type.
            if ((object)destinationArray != null)
            {
                if (source.SpecialType == SpecialType.System_Array)
                {
                    return true;
                }

                foreach (var iface in this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
                {
3120
                    if (HasIdentityConversionInternal(iface, source))
P
Pilchie 已提交
3121 3122 3123 3124 3125 3126 3127 3128 3129 3130
                    {
                        return true;
                    }
                }
            }

            // SPEC: From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces
            // SPEC: provided that there is an explicit reference conversion from S to T.

            // The framework now also allows arrays to be converted to IReadOnlyList<T> and IReadOnlyCollection<T>; we 
3131
            // honor that as well.
P
Pilchie 已提交
3132

3133
            if ((object)sourceArray != null && sourceArray.IsSZArray && destination.IsPossibleArrayGenericInterface())
P
Pilchie 已提交
3134
            {
3135
                if (HasExplicitReferenceConversion(sourceArray.ElementType.TypeSymbol, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteDiagnostics).TypeSymbol, ref useSiteDiagnostics))
P
Pilchie 已提交
3136 3137 3138 3139 3140 3141 3142 3143
                {
                    return true;
                }
            }

            // SPEC: From System.Collections.Generic.IList<S> and its base interfaces to a single-dimensional array type T[], 
            // provided that there is an explicit identity or reference conversion from S to T.

3144
            // Similarly, we honor IReadOnlyList<S> and IReadOnlyCollection<S> in the same way.
3145
            if ((object)destinationArray != null && destinationArray.IsSZArray)
P
Pilchie 已提交
3146 3147 3148 3149 3150 3151 3152 3153 3154
            {
                var specialDefinition = ((TypeSymbol)source.OriginalDefinition).SpecialType;

                if (specialDefinition == SpecialType.System_Collections_Generic_IList_T ||
                    specialDefinition == SpecialType.System_Collections_Generic_ICollection_T ||
                    specialDefinition == SpecialType.System_Collections_Generic_IEnumerable_T ||
                    specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyList_T ||
                    specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyCollection_T)
                {
3155 3156
                    var sourceElement = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteDiagnostics).TypeSymbol;
                    var destinationElement = destinationArray.ElementType.TypeSymbol;
P
Pilchie 已提交
3157

3158
                    if (HasIdentityConversionInternal(sourceElement, destinationElement))
P
Pilchie 已提交
3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187
                    {
                        return true;
                    }

                    if (HasImplicitReferenceConversion(sourceElement, destinationElement, ref useSiteDiagnostics))
                    {
                        return true;
                    }

                    if (HasExplicitReferenceConversion(sourceElement, destinationElement, ref useSiteDiagnostics))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            if (destination.IsPointerType())
            {
                return false;
            }

3188 3189 3190 3191 3192 3193
            // Ref-like types cannot be boxed or unboxed
            if (destination.IsRestrictedType())
            {
                return false;
            }

P
Pilchie 已提交
3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267
            // SPEC: An unboxing conversion permits a reference type to be explicitly converted to a value-type. 
            // SPEC: An unboxing conversion exists from the types object and System.ValueType to any non-nullable-value-type, 
            var specialTypeSource = source.SpecialType;

            if (specialTypeSource == SpecialType.System_Object || specialTypeSource == SpecialType.System_ValueType)
            {
                if (destination.IsValueType && !destination.IsNullableType())
                {
                    return true;
                }
            }

            // SPEC: and from any interface-type to any non-nullable-value-type that implements the interface-type. 

            if (source.IsInterfaceType() &&
                destination.IsValueType &&
                !destination.IsNullableType() &&
                HasBoxingConversion(destination, source, ref useSiteDiagnostics))
            {
                return true;
            }

            // SPEC: Furthermore type System.Enum can be unboxed to any enum-type.
            if (source.SpecialType == SpecialType.System_Enum && destination.IsEnumType())
            {
                return true;
            }

            // SPEC: An unboxing conversion exists from a reference type to a nullable-type if an unboxing 
            // SPEC: conversion exists from the reference type to the underlying non-nullable-value-type 
            // SPEC: of the nullable-type.
            if (source.IsReferenceType &&
                destination.IsNullableType() &&
                HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteDiagnostics))
            {
                return true;
            }

            // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing 
            // SPEC: UNDONE conversion from an interface type I0 and I0 has an identity conversion to I.

            // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing conversion 
            // SPEC: UNDONE from an interface or delegate type I0 and either I0 is variance-convertible to I or I is variance-convertible to I0.

            if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteDiagnostics))
            {
                return true;
            }

            return false;
        }

        private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            return source is PointerTypeSymbol && destination is PointerTypeSymbol;
        }

        private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            if (!(source is PointerTypeSymbol))
            {
                return false;
            }

            // SPEC OMISSION: 
            // 
            // The spec should state that any pointer type is convertible to
            // sbyte, byte, ... etc, or any corresponding nullable type.
3268

P
Pilchie 已提交
3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
            switch (destination.StrippedType().SpecialType)
            {
                case SpecialType.System_SByte:
                case SpecialType.System_Byte:
                case SpecialType.System_Int16:
                case SpecialType.System_UInt16:
                case SpecialType.System_Int32:
                case SpecialType.System_UInt32:
                case SpecialType.System_Int64:
                case SpecialType.System_UInt64:
                    return true;
            }

            return false;
        }

        private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination)
        {
            Debug.Assert((object)source != null);
            Debug.Assert((object)destination != null);

            if (!(destination is PointerTypeSymbol))
            {
                return false;
            }

            // Note that void* is convertible to int?, but int? is not convertible to void*.

            switch (source.SpecialType)
            {
                case SpecialType.System_SByte:
                case SpecialType.System_Byte:
                case SpecialType.System_Int16:
                case SpecialType.System_UInt16:
                case SpecialType.System_Int32:
                case SpecialType.System_UInt32:
                case SpecialType.System_Int64:
                case SpecialType.System_UInt64:
                    return true;
            }

            return false;
        }
    }
}