NullableWalker.cs 187.5 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

#if DEBUG
// See comment in DataFlowPass.
#define REFERENCE_STATE
#endif

using System;
9
using System.Collections.Generic;
10 11
using System.Collections.Immutable;
using System.Diagnostics;
12
using System.Linq;
13
using Microsoft.CodeAnalysis.CSharp.Symbols;
14
using Microsoft.CodeAnalysis.CSharp.Syntax;
15 16 17 18 19 20
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    /// <summary>
21
    /// Nullability flow analysis.
22 23 24 25
    /// </summary>
    internal sealed partial class NullableWalker : DataFlowPassBase<NullableWalker.LocalState>
    {
        /// <summary>
26 27
        /// Used to copy variable slots and types from the NullableWalker for the containing method
        /// or lambda to the NullableWalker created for a nested lambda or local function.
28
        /// </summary>
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
        internal sealed class VariableState
        {
            // PROTOTYPE(NullableReferenceTypes): Reference the collections directly from the original
            // NullableWalker ratherthan coping the collections. (Items are added to the collections
            // but never replaced so the collections are lazily populated but otherwise immutable.)
            internal readonly ImmutableDictionary<VariableIdentifier, int> VariableSlot;
            internal readonly ImmutableArray<VariableIdentifier> VariableBySlot;
            internal readonly ImmutableDictionary<Symbol, TypeSymbolWithAnnotations> VariableTypes;

            internal VariableState(
                ImmutableDictionary<VariableIdentifier, int> variableSlot,
                ImmutableArray<VariableIdentifier> variableBySlot,
                ImmutableDictionary<Symbol, TypeSymbolWithAnnotations> variableTypes)
            {
                VariableSlot = variableSlot;
                VariableBySlot = variableBySlot;
                VariableTypes = variableTypes;
            }
        }

        /// <summary>
        /// The inferred type at the point of declaration of var locals and parameters.
        /// </summary>
        private readonly PooledDictionary<Symbol, TypeSymbolWithAnnotations> _variableTypes = PooledDictionary<Symbol, TypeSymbolWithAnnotations>.GetInstance();
53 54 55 56 57 58

        /// <summary>
        /// The current source assembly.
        /// </summary>
        private readonly SourceAssemblySymbol _sourceAssembly;

59 60
        // PROTOTYPE(NullableReferenceTypes): Remove the Binder if possible. 
        private readonly Binder _binder;
61 62
        private readonly Conversions _conversions;

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
        /// <summary>
        /// Use the return type and nullability from _methodSignatureOpt to calculate return
        /// expression conversions. If false, the signature of _member is used instead.
        /// </summary>
        private readonly bool _useMethodSignatureReturnType;

        /// <summary>
        /// Use the the parameter types and nullability from _methodSignatureOpt for initial
        /// parameter state. If false, the signature of _member is used instead.
        /// </summary>
        private readonly bool _useMethodSignatureParameterTypes;

        /// <summary>
        /// Method signature used for return type or parameter types. Distinct from _member
        /// signature when _member is a lambda and type is inferred from MethodTypeInferrer.
        /// </summary>
        private readonly MethodSymbol _methodSignatureOpt;

        /// <summary>
        /// Types from return expressions. Used when inferring lambda return type in MethodTypeInferrer.
        /// </summary>
        private readonly ArrayBuilder<(RefKind, TypeSymbolWithAnnotations)> _returnTypes;

        /// <summary>
        /// An optional callback for callers to receive notification of the inferred type and nullability
        /// of each expression in the method. Since the walker may require multiple passes, the callback
        /// may be invoked multiple times for a single expression, potentially with different nullability
        /// each time. The last call for each expression will include the final inferred type and nullability.
        /// </summary>
92 93
        private readonly Action<BoundExpression, TypeSymbolWithAnnotations> _callbackOpt;

94 95
        /// <summary>
        /// Invalid type, used only to catch Visit methods that do not set
96
        /// _result.Type. See VisitExpressionWithoutStackGuard.
97 98 99
        /// </summary>
        private static readonly TypeSymbolWithAnnotations _invalidType = TypeSymbolWithAnnotations.Create(ErrorTypeSymbol.UnknownResultType);

100
        private TypeSymbolWithAnnotations _resultType; // PROTOTYPE(NullableReferenceTypes): Should be return value from the visitor, not mutable state.
101

102 103 104
        /// <summary>
        /// Instances being constructed.
        /// </summary>
105 106
        private PooledDictionary<BoundExpression, ObjectCreationPlaceholderLocal> _placeholderLocals;

107 108 109 110 111 112
        /// <summary>
        /// For methods with annotations, we'll need to visit the arguments twice.
        /// Once for diagnostics and once for result state (but disabling diagnostics).
        /// </summary>
        private bool _disableDiagnostics = false;

113 114 115 116 117 118
        /// <summary>
        /// Used to allow <see cref="MakeSlot(BoundExpression)"/> to substitute the correct slot for a <see cref="BoundConditionalReceiver"/> when
        /// it's encountered.
        /// </summary>
        private int _lastConditionalAccessSlot = -1;

119 120
        protected override void Free()
        {
121
            _variableTypes.Free();
122 123 124 125
            _placeholderLocals?.Free();
            base.Free();
        }

126
        private NullableWalker(
127
            CSharpCompilation compilation,
128 129 130 131
            MethodSymbol method,
            bool useMethodSignatureReturnType,
            bool useMethodSignatureParameterTypes,
            MethodSymbol methodSignatureOpt,
132
            BoundNode node,
133 134
            ArrayBuilder<(RefKind, TypeSymbolWithAnnotations)> returnTypes,
            VariableState initialState,
135
            Action<BoundExpression, TypeSymbolWithAnnotations> callbackOpt)
136
            : base(compilation, method, node, new EmptyStructTypeCache(compilation, dev12CompilerCompatibility: false), trackUnassignments: false)
137
        {
138
            _sourceAssembly = (method is null) ? null : (SourceAssemblySymbol)method.ContainingAssembly;
139
            _callbackOpt = callbackOpt;
140 141
            // PROTOTYPE(NullableReferenceTypes): Do we really need a Binder?
            // If so, are we interested in an InMethodBinder specifically?
142
            _binder = compilation.GetBinderFactory(node.SyntaxTree).GetBinder(node.Syntax);
143 144
            Debug.Assert(!_binder.Conversions.IncludeNullability);
            _conversions = _binder.Conversions.WithNullability(true);
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
            _useMethodSignatureReturnType = (object)methodSignatureOpt != null && useMethodSignatureReturnType;
            _useMethodSignatureParameterTypes = (object)methodSignatureOpt != null && useMethodSignatureParameterTypes;
            _methodSignatureOpt = methodSignatureOpt;
            _returnTypes = returnTypes;
            if (initialState != null)
            {
                var variableBySlot = initialState.VariableBySlot;
                nextVariableSlot = variableBySlot.Length;
                foreach (var (variable, slot) in initialState.VariableSlot)
                {
                    Debug.Assert(slot < nextVariableSlot);
                    _variableSlot.Add(variable, slot);
                }
                this.variableBySlot = variableBySlot.ToArray();
                foreach (var pair in initialState.VariableTypes)
                {
                    _variableTypes.Add(pair.Key, pair.Value);
                }
            }
164 165 166 167 168 169 170 171 172
        }

        protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()
        {
            return true;
        }

        protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion)
        {
173 174 175 176
            if (_returnTypes != null)
            {
                _returnTypes.Clear();
            }
177 178 179 180
            this.Diagnostics.Clear();
            ParameterSymbol methodThisParameter = MethodThisParameter;
            this.State = ReachableState();                   // entry point is reachable
            this.regionPlace = RegionPlace.Before;
181
            EnterParameters();                               // with parameters assigned
182 183
            if ((object)methodThisParameter != null)
            {
184
                EnterParameter(methodThisParameter, methodThisParameter.Type);
185 186 187 188 189 190
            }

            ImmutableArray<PendingBranch> pendingReturns = base.Scan(ref badRegion);
            return pendingReturns;
        }

191 192 193 194 195 196
        internal static void Analyze(
            CSharpCompilation compilation,
            MethodSymbol method,
            BoundNode node,
            DiagnosticBag diagnostics,
            Action<BoundExpression, TypeSymbolWithAnnotations> callbackOpt = null)
197
        {
198
            if (method.IsImplicitlyDeclared)
199 200 201
            {
                return;
            }
202 203
            Analyze(compilation, method, node, diagnostics, useMethodSignatureReturnType: false, useMethodSignatureParameterTypes: false, methodSignatureOpt: null, returnTypes: null, initialState: null, callbackOpt);
        }
204

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        internal static void Analyze(
            CSharpCompilation compilation,
            BoundLambda lambda,
            DiagnosticBag diagnostics,
            MethodSymbol delegateInvokeMethod,
            ArrayBuilder<(RefKind, TypeSymbolWithAnnotations)> returnTypes,
            VariableState initialState)
        {
            Analyze(
                compilation,
                lambda.Symbol,
                lambda.Body,
                diagnostics,
                useMethodSignatureReturnType: true,
                useMethodSignatureParameterTypes: !lambda.UnboundLambda.HasExplicitlyTypedParameterList,
                methodSignatureOpt: delegateInvokeMethod,
                returnTypes, initialState,
                callbackOpt: null);
        }

        private static void Analyze(
            CSharpCompilation compilation,
            MethodSymbol method,
            BoundNode node,
            DiagnosticBag diagnostics,
            bool useMethodSignatureReturnType,
            bool useMethodSignatureParameterTypes,
            MethodSymbol methodSignatureOpt,
            ArrayBuilder<(RefKind, TypeSymbolWithAnnotations)> returnTypes,
            VariableState initialState,
            Action<BoundExpression, TypeSymbolWithAnnotations> callbackOpt)
        {
            Debug.Assert(diagnostics != null);
            var walker = new NullableWalker(compilation, method, useMethodSignatureReturnType, useMethodSignatureParameterTypes, methodSignatureOpt, node, returnTypes, initialState, callbackOpt);
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
            try
            {
                bool badRegion = false;
                ImmutableArray<PendingBranch> returns = walker.Analyze(ref badRegion);
                diagnostics.AddRange(walker.Diagnostics);
                Debug.Assert(!badRegion);
            }
            catch (BoundTreeVisitor.CancelledByStackGuardException ex) when (diagnostics != null)
            {
                ex.AddAnError(diagnostics);
            }
            finally
            {
                walker.Free();
            }
        }

        protected override void Normalize(ref LocalState state)
        {
258
            int oldNext = state.Capacity;
259
            state.EnsureCapacity(nextVariableSlot);
260 261 262 263 264 265 266
            Populate(ref state, oldNext);
        }

        private void Populate(ref LocalState state, int start)
        {
            int capacity = state.Capacity;
            for (int slot = start; slot < capacity; slot++)
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
            {
                var value = GetDefaultState(ref state, slot);
                state[slot] = value;
            }
        }

        private bool? GetDefaultState(ref LocalState state, int slot)
        {
            if (slot == 0)
            {
                return null;
            }

            var variable = variableBySlot[slot];
            var symbol = variable.Symbol;

            switch (symbol.Kind)
            {
                case SymbolKind.Local:
                    return null;
                case SymbolKind.Parameter:
                    {
                        var parameter = (ParameterSymbol)symbol;
290 291 292 293 294 295 296 297 298 299
                        if (parameter.RefKind == RefKind.Out)
                        {
                            return null;
                        }
                        TypeSymbolWithAnnotations parameterType;
                        if (!_variableTypes.TryGetValue(parameter, out parameterType))
                        {
                            parameterType = parameter.Type;
                        }
                        return !parameterType.IsNullable;
300 301 302
                    }
                case SymbolKind.Field:
                case SymbolKind.Property:
303
                case SymbolKind.Event:
304
                    {
305
                        // PROTOTYPE(NullableReferenceTypes): State of containing struct should not be important.
306
                        // And if it is important, what about fields of structs that are fields of other structs, etc.?
307
                        int containingSlot = variable.ContainingSlot;
308 309
                        if (containingSlot > 0 &&
                            variableBySlot[containingSlot].Symbol.GetTypeOrReturnType().TypeKind == TypeKind.Struct &&
310 311 312 313 314 315 316 317 318
                            state[containingSlot] == null)
                        {
                            return null;
                        }
                        return !symbol.GetTypeOrReturnType().IsNullable;
                    }
                default:
                    throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
            }
319 320 321 322
        }

        protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression receiver, out Symbol member)
        {
323 324 325 326
            receiver = null;
            member = null;

            switch (expr.Kind)
327
            {
328
                case BoundKind.FieldAccess:
329
                    {
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
                        var fieldAccess = (BoundFieldAccess)expr;
                        var fieldSymbol = fieldAccess.FieldSymbol;
                        if (fieldSymbol.IsStatic || fieldSymbol.IsFixed)
                        {
                            return false;
                        }
                        member = fieldSymbol;
                        receiver = fieldAccess.ReceiverOpt;
                        break;
                    }
                case BoundKind.EventAccess:
                    {
                        var eventAccess = (BoundEventAccess)expr;
                        var eventSymbol = eventAccess.EventSymbol;
                        if (eventSymbol.IsStatic)
                        {
                            return false;
                        }
348 349
                        // PROTOTYPE(NullableReferenceTypes): Use AssociatedField for field-like events?
                        member = eventSymbol;
350 351 352 353 354 355 356 357 358 359 360
                        receiver = eventAccess.ReceiverOpt;
                        break;
                    }
                case BoundKind.PropertyAccess:
                    {
                        var propAccess = (BoundPropertyAccess)expr;
                        var propSymbol = propAccess.PropertySymbol;
                        if (propSymbol.IsStatic)
                        {
                            return false;
                        }
361
                        member = GetBackingFieldIfStructProperty(propSymbol);
362 363
                        receiver = propAccess.ReceiverOpt;
                        break;
364 365
                    }
            }
366 367 368 369 370

            return (object)member != null &&
                (object)receiver != null &&
                receiver.Kind != BoundKind.TypeExpression &&
                (object)receiver.Type != null;
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
        // PROTOTYPE(NullableReferenceTypes): Use backing field for struct property
        // for now, to avoid cycles if the struct type contains a property of the struct type.
        // Remove this and populate struct members lazily to match classes.
        private Symbol GetBackingFieldIfStructProperty(Symbol symbol)
        {
            if (symbol.Kind == SymbolKind.Property)
            {
                var property = (PropertySymbol)symbol;
                var containingType = property.ContainingType;
                if (containingType.TypeKind == TypeKind.Struct)
                {
                    // PROTOTYPE(NullableReferenceTypes): Relying on field name
                    // will not work for properties declared in other languages.
                    var fieldName = GeneratedNames.MakeBackingFieldName(property.Name);
                    return _emptyStructTypeCache.GetStructInstanceFields(containingType).FirstOrDefault(f => f.Name == fieldName);
                }
            }
            return symbol;
        }

        // PROTOTYPE(NullableReferenceTypes): Temporary, until we're using
        // properties on structs directly.
        private new int GetOrCreateSlot(Symbol symbol, int containingSlot = 0)
        {
            symbol = GetBackingFieldIfStructProperty(symbol);
            if ((object)symbol == null)
            {
                return -1;
            }
            return base.GetOrCreateSlot(symbol, containingSlot);
        }

        // PROTOTYPE(NullableReferenceTypes): Remove use of MakeSlot.
406 407 408 409 410
        protected override int MakeSlot(BoundExpression node)
        {
            switch (node.Kind)
            {
                case BoundKind.ObjectCreationExpression:
411
                case BoundKind.DynamicObjectCreationExpression:
412 413 414 415 416 417
                case BoundKind.AnonymousObjectCreationExpression:
                    if (_placeholderLocals != null && _placeholderLocals.TryGetValue(node, out ObjectCreationPlaceholderLocal placeholder))
                    {
                        return GetOrCreateSlot(placeholder);
                    }
                    break;
418 419 420 421 422 423 424 425
                case BoundKind.ConditionalReceiver:
                    if (_lastConditionalAccessSlot != -1)
                    {
                        int slot = _lastConditionalAccessSlot;
                        _lastConditionalAccessSlot = -1;
                        return slot;
                    }
                    break;
426 427 428 429
            }
            return base.MakeSlot(node);
        }

430
        private new void VisitLvalue(BoundExpression node)
431 432 433 434
        {
            switch (node.Kind)
            {
                case BoundKind.Local:
435
                    _resultType = GetDeclaredLocalResult(((BoundLocal)node).LocalSymbol);
436
                    break;
437
                case BoundKind.Parameter:
438
                    _resultType = GetDeclaredParameterResult(((BoundParameter)node).ParameterSymbol);
439
                    break;
440 441 442
                case BoundKind.FieldAccess:
                    {
                        var fieldAccess = (BoundFieldAccess)node;
443
                        VisitMemberAccess(fieldAccess.ReceiverOpt, fieldAccess.FieldSymbol, asLvalue: true);
444
                    }
445
                    break;
446 447 448
                case BoundKind.PropertyAccess:
                    {
                        var propertyAccess = (BoundPropertyAccess)node;
449
                        VisitMemberAccess(propertyAccess.ReceiverOpt, propertyAccess.PropertySymbol, asLvalue: true);
450 451
                    }
                    break;
452
                case BoundKind.EventAccess:
453
                    {
454 455
                        var eventAccess = (BoundEventAccess)node;
                        VisitMemberAccess(eventAccess.ReceiverOpt, eventAccess.EventSymbol, asLvalue: true);
456 457
                    }
                    break;
458 459
                case BoundKind.ObjectInitializerMember:
                    throw ExceptionUtilities.UnexpectedValue(node.Kind); // Should have been handled in VisitObjectCreationExpression().
460
                default:
461
                    VisitRvalue(node);
462 463
                    break;
            }
464 465 466

            if (_callbackOpt != null)
            {
467
                _callbackOpt(node, _resultType);
468
            }
469 470
        }

471
        private TypeSymbolWithAnnotations VisitRvalueWithResult(BoundExpression node)
472 473
        {
            base.VisitRvalue(node);
474
            return _resultType;
475 476 477 478 479 480 481 482
        }

        private static object GetTypeAsDiagnosticArgument(TypeSymbol typeOpt)
        {
            // PROTOTYPE(NullableReferenceTypes): Avoid hardcoded string.
            return typeOpt ?? (object)"<null>";
        }

483 484 485
        /// <summary>
        /// Reports top-level nullability problem in assignment.
        /// </summary>
486 487 488 489 490 491 492 493 494 495 496 497 498 499
        private bool ReportNullReferenceAssignmentIfNecessary(BoundExpression value, TypeSymbolWithAnnotations targetType, TypeSymbolWithAnnotations valueType, bool useLegacyWarnings)
        {
            Debug.Assert(value != null);
            Debug.Assert(!IsConditionalState);

            if (targetType is null || valueType is null)
            {
                return false;
            }

            if (targetType.IsReferenceType && targetType.IsNullable == false && valueType.IsNullable == true)
            {
                if (useLegacyWarnings)
                {
500
                    ReportWWarning(value.Syntax);
501 502 503 504 505 506 507 508 509 510 511
                }
                else if (!ReportNullAsNonNullableReferenceIfNecessary(value))
                {
                    ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullReferenceAssignment, value.Syntax);
                }
                return true;
            }

            return false;
        }

C
Charles Stoner 已提交
512 513 514 515 516 517 518 519 520 521 522 523
        private void ReportAssignmentWarnings(BoundExpression value, TypeSymbolWithAnnotations targetType, TypeSymbolWithAnnotations valueType, bool useLegacyWarnings)
        {
            Debug.Assert(value != null);
            Debug.Assert(!IsConditionalState);

            if (this.State.Reachable)
            {
                if (targetType is null || valueType is null)
                {
                    return;
                }

524
                ReportNullReferenceAssignmentIfNecessary(value, targetType, valueType, useLegacyWarnings);
C
Charles Stoner 已提交
525 526 527 528
                ReportNullabilityMismatchInAssignmentIfNecessary(value, valueType.TypeSymbol, targetType.TypeSymbol);
            }
        }

529
        /// <summary>
C
Charles Stoner 已提交
530
        /// Update tracked value on assignment.
531
        /// </summary>
532
        private void TrackNullableStateForAssignment(BoundExpression value, TypeSymbolWithAnnotations targetType, int targetSlot, TypeSymbolWithAnnotations valueType, int valueSlot = -1)
533
        {
C
Charles Stoner 已提交
534
            Debug.Assert(value != null);
535
            Debug.Assert(!IsConditionalState);
C
Charles Stoner 已提交
536

537 538
            if (this.State.Reachable)
            {
539 540 541 542
                if ((object)targetType == null)
                {
                    return;
                }
543

C
Charles Stoner 已提交
544
                if (targetSlot <= 0)
545
                {
C
Charles Stoner 已提交
546 547
                    return;
                }
548

C
Charles Stoner 已提交
549 550
                bool isByRefTarget = IsByRefTarget(targetSlot);
                if (targetSlot >= this.State.Capacity) Normalize(ref this.State);
551

C
Charles Stoner 已提交
552 553
                this.State[targetSlot] = isByRefTarget ?
                    // Since reference can point to the heap, we cannot assume the value is not null after this assignment,
554
                    // regardless of what value is being assigned.
C
Charles Stoner 已提交
555 556 557 558 559 560
                    (targetType.IsNullable == true) ? (bool?)false : null :
                    !valueType?.IsNullable;

                // PROTOTYPE(NullableReferenceTypes): Might this clear state that
                // should be copied in InheritNullableStateOfTrackableType?
                InheritDefaultState(targetSlot);
561

562 563
                if (targetType.IsReferenceType)
                {
C
Charles Stoner 已提交
564 565 566 567 568 569 570 571 572 573 574
                    // PROTOTYPE(NullableReferenceTypes): We should copy all tracked state from `value`,
                    // regardless of BoundNode type, but we'll need to handle cycles. (For instance, the
                    // assignment to C.F below. See also StaticNullChecking_Members.FieldCycle_01.)
                    // class C
                    // {
                    //     C? F;
                    //     C() { F = this; }
                    // }
                    // For now, we copy a limited set of BoundNode types that shouldn't contain cycles.
                    if ((value.Kind == BoundKind.ObjectCreationExpression || value.Kind == BoundKind.AnonymousObjectCreationExpression || value.Kind == BoundKind.DynamicObjectCreationExpression || targetType.TypeSymbol.IsAnonymousType) &&
                        targetType.TypeSymbol.Equals(valueType?.TypeSymbol, TypeCompareKind.ConsiderEverything)) // PROTOTYPE(NullableReferenceTypes): Allow assignment to base type.
575
                    {
C
Charles Stoner 已提交
576
                        if (valueSlot > 0)
577
                        {
C
Charles Stoner 已提交
578
                            InheritNullableStateOfTrackableType(targetSlot, valueSlot, isByRefTarget, slotWatermark: GetSlotWatermark());
579
                        }
580 581
                    }
                }
C
Charles Stoner 已提交
582 583
                else if (EmptyStructTypeCache.IsTrackableStructType(targetType.TypeSymbol) &&
                        targetType.TypeSymbol.Equals(valueType?.TypeSymbol, TypeCompareKind.ConsiderEverything))
584
                {
585
                    InheritNullableStateOfTrackableStruct(targetType.TypeSymbol, targetSlot, valueSlot, IsByRefTarget(targetSlot), slotWatermark: GetSlotWatermark());
586 587 588 589
                }
            }
        }

590
        private int GetSlotWatermark() => this.nextVariableSlot;
591

592 593 594 595
        private bool IsByRefTarget(int slot)
        {
            if (slot > 0)
            {
596
                Symbol associatedNonMemberSymbol = GetNonMemberSymbol(slot);
597 598 599 600 601 602 603 604 605 606 607 608 609 610

                switch (associatedNonMemberSymbol.Kind)
                {
                    case SymbolKind.Local:
                        return ((LocalSymbol)associatedNonMemberSymbol).RefKind != RefKind.None;
                    case SymbolKind.Parameter:
                        var parameter = (ParameterSymbol)associatedNonMemberSymbol;
                        return !parameter.IsThis && parameter.RefKind != RefKind.None;
                }
            }

            return false;
        }

611 612 613 614 615
        private void ReportWWarning(SyntaxNode syntax)
        {
            ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_ConvertingNullableToNonNullable, syntax);
        }

616 617
        private void ReportStaticNullCheckingDiagnostics(ErrorCode errorCode, SyntaxNode syntaxNode, params object[] arguments)
        {
618 619 620 621
            if (!_disableDiagnostics)
            {
                Diagnostics.Add(errorCode, syntaxNode.GetLocation(), arguments);
            }
622 623
        }

624
        private void InheritNullableStateOfTrackableStruct(TypeSymbol targetType, int targetSlot, int valueSlot, bool isByRefTarget, int slotWatermark)
625 626 627 628
        {
            Debug.Assert(targetSlot > 0);
            Debug.Assert(EmptyStructTypeCache.IsTrackableStructType(targetType));

629 630
            // PROTOTYPE(NullableReferenceTypes): Handle properties not backed by fields.
            // See ModifyMembers_StructPropertyNoBackingField and PropertyCycle_Struct tests.
631 632
            foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(targetType))
            {
C
Misc.  
Charles Stoner 已提交
633
                InheritNullableStateOfMember(targetSlot, valueSlot, field, isByRefTarget, slotWatermark);
634 635 636
            }
        }

637
        // 'slotWatermark' is used to avoid inheriting members from inherited members.
C
Misc.  
Charles Stoner 已提交
638
        private void InheritNullableStateOfMember(int targetContainerSlot, int valueContainerSlot, Symbol member, bool isByRefTarget, int slotWatermark)
639
        {
640 641
            Debug.Assert(valueContainerSlot <= slotWatermark);

C
Misc.  
Charles Stoner 已提交
642
            TypeSymbolWithAnnotations fieldOrPropertyType = member.GetTypeOrReturnType();
643 644 645 646 647 648 649

            if (fieldOrPropertyType.IsReferenceType)
            {
                // If statically declared as not-nullable, no need to adjust the tracking info. 
                // Declaration information takes priority.
                if (fieldOrPropertyType.IsNullable != false)
                {
C
Misc.  
Charles Stoner 已提交
650
                    int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot);
651
                    bool? value = !fieldOrPropertyType.IsNullable;
652 653
                    if (isByRefTarget)
                    {
C
Misc.  
Charles Stoner 已提交
654 655 656
                        // This is a member access through a by ref entity and it isn't considered declared as not-nullable. 
                        // Since reference can point to the heap, we cannot assume the member doesn't have null value
                        // after this assignment, regardless of what value is being assigned.
657 658 659
                    }
                    else if (valueContainerSlot > 0)
                    {
C
Misc.  
Charles Stoner 已提交
660
                        int valueMemberSlot = VariableSlot(member, valueContainerSlot);
661
                        value = valueMemberSlot > 0 && valueMemberSlot < this.State.Capacity ?
662 663 664 665
                            this.State[valueMemberSlot] :
                            null;
                    }

666
                    this.State[targetMemberSlot] = value;
667 668
                }

669
                if (valueContainerSlot > 0)
670
                {
C
Misc.  
Charles Stoner 已提交
671
                    int valueMemberSlot = VariableSlot(member, valueContainerSlot);
672
                    if (valueMemberSlot > 0 && valueMemberSlot <= slotWatermark)
673
                    {
C
Misc.  
Charles Stoner 已提交
674
                        int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot);
675
                        InheritNullableStateOfTrackableType(targetMemberSlot, valueMemberSlot, isByRefTarget, slotWatermark);
676
                    }
677 678 679 680
                }
            }
            else if (EmptyStructTypeCache.IsTrackableStructType(fieldOrPropertyType.TypeSymbol))
            {
C
Misc.  
Charles Stoner 已提交
681
                int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot);
682
                if (targetMemberSlot > 0)
683
                {
684 685 686
                    int valueMemberSlot = -1;
                    if (valueContainerSlot > 0)
                    {
C
Misc.  
Charles Stoner 已提交
687
                        int slot = GetOrCreateSlot(member, valueContainerSlot);
688 689 690 691 692 693
                        if (slot < slotWatermark)
                        {
                            valueMemberSlot = slot;
                        }
                    }
                    InheritNullableStateOfTrackableStruct(fieldOrPropertyType.TypeSymbol, targetMemberSlot, valueMemberSlot, isByRefTarget, slotWatermark);
694 695 696 697
                }
            }
        }

698
        private void InheritDefaultState(int targetSlot)
699 700 701
        {
            Debug.Assert(targetSlot > 0);

702 703
            // Reset the state of any members of the target.
            for (int slot = targetSlot + 1; slot < nextVariableSlot; slot++)
704
            {
705 706
                var variable = variableBySlot[slot];
                if (variable.ContainingSlot != targetSlot)
707 708 709
                {
                    continue;
                }
710 711 712 713
                this.State[slot] = !variable.Symbol.GetTypeOrReturnType().IsNullable;
                InheritDefaultState(slot);
            }
        }
714

715
        private void InheritNullableStateOfTrackableType(int targetSlot, int valueSlot, bool isByRefTarget, int slotWatermark)
716 717 718
        {
            Debug.Assert(targetSlot > 0);
            Debug.Assert(valueSlot > 0);
719

720 721 722 723 724
            // Clone the state for members that have been set on the value.
            for (int slot = valueSlot + 1; slot < nextVariableSlot; slot++)
            {
                var variable = variableBySlot[slot];
                if (variable.ContainingSlot != valueSlot)
725 726 727
                {
                    continue;
                }
728
                var member = variable.Symbol;
C
Misc.  
Charles Stoner 已提交
729 730
                Debug.Assert(member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property || member.Kind == SymbolKind.Event);
                InheritNullableStateOfMember(targetSlot, valueSlot, member, isByRefTarget, slotWatermark);
731 732 733 734 735
            }
        }

        protected override LocalState ReachableState()
        {
736 737 738
            var state = new LocalState(BitVector.Create(nextVariableSlot), BitVector.Create(nextVariableSlot));
            Populate(ref state, start: 0);
            return state;
739 740 741 742
        }

        protected override LocalState UnreachableState()
        {
743
            return new LocalState(BitVector.Empty, BitVector.Empty);
744 745 746 747
        }

        protected override LocalState AllBitsSet()
        {
748
            return new LocalState(BitVector.Create(nextVariableSlot), BitVector.Create(nextVariableSlot));
749 750
        }

751
        private void EnterParameters()
752
        {
753 754 755 756 757
            var methodParameters = ((MethodSymbol)_member).Parameters;
            var signatureParameters = _useMethodSignatureParameterTypes ? _methodSignatureOpt.Parameters : methodParameters;
            Debug.Assert(signatureParameters.Length == methodParameters.Length);
            int n = methodParameters.Length;
            for (int i = 0; i < n; i++)
758
            {
759 760 761 762
                var parameter = methodParameters[i];
                var parameterType = signatureParameters[i].Type;
                _variableTypes[parameter] = parameterType;
                EnterParameter(parameter, parameterType);
763 764 765
            }
        }

766
        private void EnterParameter(ParameterSymbol parameter, TypeSymbolWithAnnotations parameterType)
767 768
        {
            int slot = GetOrCreateSlot(parameter);
769 770
            Debug.Assert(!IsConditionalState);
            if (slot > 0 && parameter.RefKind != RefKind.Out)
771
            {
772
                if (EmptyStructTypeCache.IsTrackableStructType(parameterType.TypeSymbol))
773
                {
774
                    InheritNullableStateOfTrackableStruct(parameterType.TypeSymbol, slot, valueSlot: -1, isByRefTarget: parameter.RefKind != RefKind.None, slotWatermark: GetSlotWatermark());
775 776 777 778
                }
            }
        }

779
        #region Visitors
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813

        public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node)
        {
            // PROTOTYPE(NullableReferenceTypes): Move these asserts to base class.
            Debug.Assert(!IsConditionalState);

            // Create slot when the state is unconditional since EnsureCapacity should be
            // called on all fields and that is simpler if state is limited to this.State.
            int slot = -1;
            if (this.State.Reachable)
            {
                var pattern = node.Pattern;
                // PROTOTYPE(NullableReferenceTypes): Handle patterns that ensure x is not null:
                // x is T y // where T is not inferred via var
                // x is K // where K is a constant other than null
                if (pattern.Kind == BoundKind.ConstantPattern && ((BoundConstantPattern)pattern).ConstantValue?.IsNull == true)
                {
                    slot = MakeSlot(node.Expression);
                    if (slot > 0)
                    {
                        Normalize(ref this.State);
                    }
                }
            }

            var result = base.VisitIsPatternExpression(node);

            Debug.Assert(IsConditionalState);
            if (slot > 0)
            {
                this.StateWhenTrue[slot] = false;
                this.StateWhenFalse[slot] = true;
            }

814
            SetResult(node);
815 816 817 818 819 820 821 822 823 824
            return result;
        }

        public override void VisitPattern(BoundExpression expression, BoundPattern pattern)
        {
            base.VisitPattern(expression, pattern);
            var whenFail = StateWhenFalse;
            SetState(StateWhenTrue);
            AssignPatternVariables(pattern);
            SetConditionalState(this.State, whenFail);
825
            SetUnknownResultNullability();
826 827 828 829 830 831 832
        }

        private void AssignPatternVariables(BoundPattern pattern)
        {
            switch (pattern.Kind)
            {
                case BoundKind.DeclarationPattern:
833 834
                    // PROTOTYPE(NullableReferenceTypes): Handle.
                    break;
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
                case BoundKind.WildcardPattern:
                    break;
                case BoundKind.ConstantPattern:
                    {
                        var pat = (BoundConstantPattern)pattern;
                        this.VisitRvalue(pat.Value);
                        break;
                    }
                default:
                    break;
            }
        }

        protected override BoundNode VisitReturnStatementNoAdjust(BoundReturnStatement node)
        {
            Debug.Assert(!IsConditionalState);
851 852 853 854 855 856 857

            BoundExpression expr = node.ExpressionOpt;
            if (expr == null)
            {
                return null;
            }

858 859
            Conversion conversion;
            (expr, conversion) = RemoveConversion(expr, includeExplicitConversions: false);
860
            TypeSymbolWithAnnotations result = VisitRvalueWithResult(expr);
861 862 863 864 865 866 867

            //if (this.State.Reachable) // PROTOTYPE(NullableReferenceTypes): Consider reachability?
            if (expr.Type?.IsErrorType() == true)
            {
                return null;
            }

868
            if (_returnTypes != null)
869
            {
870
                // Inferring return type. Should not convert to method return type.
871
                _returnTypes.Add((node.RefKind, result));
872 873
                return null;
            }
874

875 876
            // Convert to method return type.
            var returnType = GetReturnType();
877
            TypeSymbolWithAnnotations resultType = ApplyConversion(expr, expr, conversion, returnType.TypeSymbol, result, checkConversion: true, fromExplicitCast: false, out bool canConvertNestedNullability);
878 879
            if (!canConvertNestedNullability)
            {
880
                ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullabilityMismatchInAssignment, expr.Syntax, GetTypeAsDiagnosticArgument(result?.TypeSymbol), returnType.TypeSymbol);
881 882 883 884 885 886 887 888 889
            }

            bool returnTypeIsNonNullable = IsNonNullable(returnType);
            bool returnTypeIsUnconstrainedTypeParameter = IsUnconstrainedTypeParameter(returnType.TypeSymbol);
            bool reportedNullable = false;
            if (returnTypeIsNonNullable || returnTypeIsUnconstrainedTypeParameter)
            {
                reportedNullable = ReportNullAsNonNullableReferenceIfNecessary(node.ExpressionOpt);
            }
890

891 892 893 894
            if (!reportedNullable)
            {
                if (IsNullable(resultType) && (returnTypeIsNonNullable || returnTypeIsUnconstrainedTypeParameter) ||
                    IsUnconstrainedTypeParameter(resultType?.TypeSymbol) && returnTypeIsNonNullable)
895
                {
896
                    ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullReferenceReturn, node.ExpressionOpt.Syntax);
897 898 899
                }
            }

900 901 902
            return null;
        }

903
        private TypeSymbolWithAnnotations GetReturnType()
904
        {
905 906 907
            var method = (MethodSymbol)_member;
            var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt : method).ReturnType;
            Debug.Assert((object)returnType != LambdaSymbol.ReturnTypeIsBeingInferred);
908 909 910
            return method.IsGenericTaskReturningAsync(compilation) ?
                ((NamedTypeSymbol)returnType.TypeSymbol).TypeArgumentsNoUseSiteDiagnostics.Single() :
                returnType;
911 912
        }

913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
        private static bool IsNullable(TypeSymbolWithAnnotations typeOpt)
        {
            return typeOpt?.IsNullable == true;
        }

        private static bool IsNonNullable(TypeSymbolWithAnnotations typeOpt)
        {
            return typeOpt?.IsNullable == false && typeOpt.IsReferenceType;
        }

        private static bool IsUnconstrainedTypeParameter(TypeSymbol typeOpt)
        {
            return typeOpt?.IsUnconstrainedTypeParameter() == true;
        }

928 929 930 931
        /// <summary>
        /// Report warning assigning value where nested nullability does not match
        /// target (e.g.: `object[] a = new[] { maybeNull }`).
        /// </summary>
C
Charles Stoner 已提交
932 933 934 935 936 937 938 939
        private void ReportNullabilityMismatchInAssignmentIfNecessary(BoundExpression node, TypeSymbol sourceType, TypeSymbol destinationType)
        {
            if ((object)sourceType != null && IsNullabilityMismatch(destinationType, sourceType))
            {
                ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullabilityMismatchInAssignment, node.Syntax, sourceType, destinationType);
            }
        }

940 941
        public override BoundNode VisitLocal(BoundLocal node)
        {
942 943 944 945
            var local = node.LocalSymbol;
            int slot = GetOrCreateSlot(local);
            var type = GetDeclaredLocalResult(local);
            _resultType = GetAdjustedResult(type, slot);
946 947 948 949 950
            return null;
        }

        public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node)
        {
951 952 953 954
            var local = node.LocalSymbol;
            int slot = GetOrCreateSlot(local);

            var initializer = node.InitializerOpt;
955
            if (initializer is null)
956
            {
957 958
                return null;
            }
959

960 961 962
            Conversion conversion;
            (initializer, conversion) = RemoveConversion(initializer, includeExplicitConversions: false);

963
            TypeSymbolWithAnnotations valueType = VisitRvalueWithResult(initializer);
964 965 966 967 968 969
            TypeSymbolWithAnnotations type = local.Type;

            if (node.DeclaredType.InferredType)
            {
                Debug.Assert(conversion.IsIdentity);
                if (valueType is null)
970
                {
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
                    Debug.Assert(type.IsErrorType());
                    valueType = type;
                }
                _variableTypes[local] = valueType;
                type = valueType;
            }
            else
            {
                var unconvertedType = valueType;
                valueType = ApplyConversion(initializer, initializer, conversion, type.TypeSymbol, valueType, checkConversion: true, fromExplicitCast: false, out bool canConvertNestedNullability);
                // Need to report all warnings that apply since the warnings can be suppressed individually.
                ReportNullReferenceAssignmentIfNecessary(initializer, type, valueType, useLegacyWarnings: true);
                if (!canConvertNestedNullability)
                {
                    ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullabilityMismatchInAssignment, initializer.Syntax, GetTypeAsDiagnosticArgument(unconvertedType?.TypeSymbol), type.TypeSymbol);
986
                }
987
            }
988

989
            TrackNullableStateForAssignment(initializer, type, slot, valueType, MakeSlot(initializer));
990
            return null;
991 992 993 994 995
        }

        protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node)
        {
            Debug.Assert(!IsConditionalState);
996
            _resultType = _invalidType; // PROTOTYPE(NullableReferenceTypes): Move to `Visit` method?
997 998
            var result = base.VisitExpressionWithoutStackGuard(node);
#if DEBUG
999
            // Verify Visit method set _result.
1000
            TypeSymbolWithAnnotations resultType = _resultType;
1001 1002
            Debug.Assert((object)resultType != _invalidType);
            Debug.Assert(AreCloseEnough(resultType?.TypeSymbol, node.Type));
1003
#endif
1004 1005
            if (_callbackOpt != null)
            {
1006
                _callbackOpt(node, _resultType);
1007
            }
1008
            return result;
1009 1010
        }

1011 1012 1013 1014
#if DEBUG
        // For asserts only.
        private static bool AreCloseEnough(TypeSymbol typeA, TypeSymbol typeB)
        {
1015 1016 1017 1018 1019 1020 1021 1022
            if ((object)typeA == typeB)
            {
                return true;
            }
            if (typeA is null || typeB is null)
            {
                return false;
            }
1023 1024 1025
            bool canIgnoreType(TypeSymbol type) => (object)type.VisitType((t, unused1, unused2) => t.IsErrorType() || t.IsDynamic() || t.HasUseSiteError, (object)null) != null;
            return canIgnoreType(typeA) ||
                canIgnoreType(typeB) ||
1026 1027 1028 1029 1030
                typeA.Equals(typeB, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); // Ignore TupleElementNames (see https://github.com/dotnet/roslyn/issues/23651).
        }
#endif

        protected override void VisitStatement(BoundStatement statement)
1031
        {
1032
            _resultType = _invalidType;
1033
            base.VisitStatement(statement);
1034
            _resultType = _invalidType;
1035
        }
1036

1037 1038
        public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node)
        {
1039
            Debug.Assert(!IsConditionalState);
1040
            VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, node.Constructor, node.ArgsToParamsOpt, node.Expanded);
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
            VisitObjectOrDynamicObjectCreation(node, node.InitializerExpressionOpt);
            return null;
        }

        private void VisitObjectOrDynamicObjectCreation(BoundExpression node, BoundExpression initializerOpt)
        {
            Debug.Assert(node.Kind == BoundKind.ObjectCreationExpression || node.Kind == BoundKind.DynamicObjectCreationExpression);

            LocalSymbol receiver = null;
            int slot = -1;
            TypeSymbol type = node.Type;
            if ((object)type != null)
1053
            {
1054 1055
                bool isTrackableStructType = EmptyStructTypeCache.IsTrackableStructType(type);
                if (type.IsReferenceType || isTrackableStructType)
1056
                {
1057 1058 1059
                    receiver = GetOrCreateObjectCreationPlaceholder(node);
                    slot = GetOrCreateSlot(receiver);
                    if (slot > 0 && isTrackableStructType)
1060
                    {
1061
                        this.State[slot] = true;
1062
                        InheritNullableStateOfTrackableStruct(type, slot, valueSlot: -1, isByRefTarget: false, slotWatermark: GetSlotWatermark());
1063 1064 1065 1066 1067 1068 1069 1070 1071
                    }
                }
            }

            if (initializerOpt != null)
            {
                VisitObjectCreationInitializer(receiver, slot, initializerOpt);
            }

1072
            _resultType = TypeSymbolWithAnnotations.Create(type);
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
        }

        private void VisitObjectCreationInitializer(Symbol containingSymbol, int containingSlot, BoundExpression node)
        {
            switch (node.Kind)
            {
                case BoundKind.ObjectInitializerExpression:
                    foreach (var initializer in ((BoundObjectInitializerExpression)node).Initializers)
                    {
                        switch (initializer.Kind)
1083
                        {
1084 1085 1086 1087 1088 1089
                            case BoundKind.AssignmentOperator:
                                VisitObjectElementInitializer(containingSymbol, containingSlot, (BoundAssignmentOperator)initializer);
                                break;
                            default:
                                VisitRvalue(initializer);
                                break;
1090 1091
                        }
                    }
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
                    break;
                case BoundKind.CollectionInitializerExpression:
                    foreach (var initializer in ((BoundCollectionInitializerExpression)node).Initializers)
                    {
                        switch (initializer.Kind)
                        {
                            case BoundKind.CollectionElementInitializer:
                                VisitCollectionElementInitializer((BoundCollectionElementInitializer)initializer);
                                break;
                            default:
                                VisitRvalue(initializer);
                                break;
                        }
                    }
                    break;
                default:
1108
                    TypeSymbolWithAnnotations resultType = VisitRvalueWithResult(node);
1109 1110
                    if ((object)containingSymbol != null)
                    {
1111
                        var type = containingSymbol.GetTypeOrReturnType();
1112 1113
                        ReportAssignmentWarnings(node, type, resultType, useLegacyWarnings: false);
                        TrackNullableStateForAssignment(node, type, containingSlot, resultType, MakeSlot(node));
1114
                    }
1115
                    break;
1116
            }
1117
        }
1118

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
        private void VisitObjectElementInitializer(Symbol containingSymbol, int containingSlot, BoundAssignmentOperator node)
        {
            var left = node.Left;
            switch (left.Kind)
            {
                case BoundKind.ObjectInitializerMember:
                    {
                        var objectInitializer = (BoundObjectInitializerMember)left;
                        var symbol = objectInitializer.MemberSymbol;
                        if (!objectInitializer.Arguments.IsDefaultOrEmpty)
                        {
1130
                            VisitArguments(objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, (PropertySymbol)symbol, objectInitializer.ArgsToParamsOpt, objectInitializer.Expanded);
1131
                        }
1132 1133 1134 1135 1136
                        if ((object)symbol != null)
                        {
                            int slot = (containingSlot < 0) ? -1 : GetOrCreateSlot(symbol, containingSlot);
                            VisitObjectCreationInitializer(symbol, slot, node.Right);
                        }
1137 1138 1139 1140 1141 1142 1143
                    }
                    break;
                default:
                    VisitLvalue(node);
                    break;
            }
        }
1144

1145 1146 1147 1148 1149 1150 1151
        private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node)
        {
            if (node.AddMethod.CallsAreOmitted(node.SyntaxTree))
            {
                // PROTOTYPE(NullableReferenceTypes): Should skip state set in arguments
                // of omitted call. See PreciseAbstractFlowPass.VisitCollectionElementInitializer.
            }
1152

1153
            VisitArguments(node, node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod, node.ArgsToParamsOpt, node.Expanded);
1154
            SetUnknownResultNullability();
1155 1156
        }

1157
        private void SetResult(BoundExpression node)
1158
        {
1159
            _resultType = TypeSymbolWithAnnotations.Create(node.Type);
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
        }

        private ObjectCreationPlaceholderLocal GetOrCreateObjectCreationPlaceholder(BoundExpression node)
        {
            ObjectCreationPlaceholderLocal placeholder;
            if (_placeholderLocals == null)
            {
                _placeholderLocals = PooledDictionary<BoundExpression, ObjectCreationPlaceholderLocal>.GetInstance();
                placeholder = null;
            }
            else
            {
                _placeholderLocals.TryGetValue(node, out placeholder);
            }

            if ((object)placeholder == null)
            {
                placeholder = new ObjectCreationPlaceholderLocal(_member, node);
                _placeholderLocals.Add(node, placeholder);
            }

            return placeholder;
        }

        public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node)
        {
            Debug.Assert(!IsConditionalState);
1187

1188
            int receiverSlot = -1;
1189 1190 1191 1192 1193
            var arguments = node.Arguments;
            var constructor = node.Constructor;
            for (int i = 0; i < arguments.Length; i++)
            {
                var argument = arguments[i];
1194
                TypeSymbolWithAnnotations argumentType = VisitRvalueWithResult(argument);
1195
                var parameter = constructor.Parameters[i];
1196
                ReportArgumentWarnings(argument, argumentType, parameter);
1197

1198 1199
                // PROTOTYPE(NullableReferenceTypes): node.Declarations includes
                // explicitly-named properties only. For now, skip expressions
1200
                // with implicit names. See NullableReferenceTypesTests.AnonymousTypes_05.
1201 1202 1203 1204
                if (node.Declarations.Length < arguments.Length)
                {
                    continue;
                }
1205

1206 1207 1208 1209 1210
                PropertySymbol property = node.Declarations[i].Property;
                if (receiverSlot <= 0)
                {
                    ObjectCreationPlaceholderLocal implicitReceiver = GetOrCreateObjectCreationPlaceholder(node);
                    receiverSlot = GetOrCreateSlot(implicitReceiver);
1211
                }
1212

1213 1214
                ReportAssignmentWarnings(argument, property.Type, argumentType, useLegacyWarnings: false);
                TrackNullableStateForAssignment(argument, property.Type, GetOrCreateSlot(property, receiverSlot), argumentType, MakeSlot(argument));
1215
            }
1216

1217
            // PROTOTYPE(NullableReferenceTypes): _result may need to be a new anonymous
1218 1219
            // type since the properties may have distinct nullability from original.
            // (See StaticNullChecking_FlowAnalysis.AnonymousObjectCreation_02.)
1220
            _resultType = TypeSymbolWithAnnotations.Create(node.Type);
1221
            return null;
1222 1223 1224 1225
        }

        public override BoundNode VisitArrayCreation(BoundArrayCreation node)
        {
1226 1227 1228 1229 1230
            foreach (var expr in node.Bounds)
            {
                VisitRvalue(expr);
            }
            TypeSymbol resultType = (node.InitializerOpt == null) ? node.Type : VisitArrayInitializer(node);
1231
            _resultType = TypeSymbolWithAnnotations.Create(resultType);
1232
            return null;
1233 1234
        }

1235
        private ArrayTypeSymbol VisitArrayInitializer(BoundArrayCreation node)
1236
        {
1237 1238
            var arrayType = (ArrayTypeSymbol)node.Type;
            var elementType = arrayType.ElementType;
1239

1240 1241 1242
            BoundArrayInitialization initialization = node.InitializerOpt;
            var elementBuilder = ArrayBuilder<BoundExpression>.GetInstance(initialization.Initializers.Length);
            GetArrayElements(initialization, elementBuilder);
1243

1244
            // PROTOTYPE(NullableReferenceTypes): Removing and recalculating conversions should not
1245 1246
            // be necessary for explicitly typed arrays. In those cases, VisitConversion should warn
            // on nullability mismatch (although we'll need to ensure we handle the case where
1247
            // initial binding calculated an Identity conversion, even though nullability was distinct).
1248
            int n = elementBuilder.Count;
1249
            var conversionBuilder = ArrayBuilder<Conversion>.GetInstance(n);
1250
            var resultBuilder = ArrayBuilder<TypeSymbolWithAnnotations>.GetInstance(n);
1251
            for (int i = 0; i < n; i++)
1252
            {
1253
                (BoundExpression element, Conversion conversion) = RemoveConversion(elementBuilder[i], includeExplicitConversions: false);
1254
                elementBuilder[i] = element;
1255
                conversionBuilder.Add(conversion);
1256 1257 1258
                resultBuilder.Add(VisitRvalueWithResult(element));
            }

1259
            // PROTOTYPE(NullableReferenceTypes): Record in the BoundArrayCreation
1260 1261 1262
            // whether the array was implicitly typed, rather than relying on syntax.
            if (node.Syntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression)
            {
1263
                var resultTypes = resultBuilder.ToImmutable();
1264
                // PROTOTYPE(NullableReferenceTypes): Initial binding calls InferBestType(ImmutableArray<BoundExpression>, ...)
1265
                // overload. Why are we calling InferBestType(ImmutableArray<TypeSymbolWithAnnotations>, ...) here?
1266
                // PROTOTYPE(NullableReferenceTypes): InferBestType(ImmutableArray<BoundExpression>, ...)
1267 1268
                // uses a HashSet<TypeSymbol> to reduce the candidates to the unique types before comparing.
                // Should do the same here.
1269 1270 1271 1272 1273
                HashSet<DiagnosticInfo> useSiteDiagnostics = null;
                // If there are error types, use the first error type. (Matches InferBestType(ImmutableArray<BoundExpression>, ...).)
                var bestType = resultTypes.FirstOrDefault(t => t?.IsErrorType() == true) ??
                    BestTypeInferrer.InferBestType(resultTypes, _conversions, useSiteDiagnostics: ref useSiteDiagnostics);
                // PROTOTYPE(NullableReferenceTypes): Report a special ErrorCode.WRN_NoBestNullabilityArrayElements
1274 1275
                // when InferBestType fails, and avoid reporting conversion warnings for each element in those cases.
                // (See similar code for conditional expressions: ErrorCode.WRN_NoBestNullabilityConditionalExpression.)
1276
                if ((object)bestType != null)
1277
                {
1278
                    elementType = bestType;
1279
                }
1280
                arrayType = arrayType.WithElementType(elementType);
1281
            }
1282

1283
            if ((object)elementType != null)
1284
            {
1285 1286
                bool elementTypeIsReferenceType = elementType.IsReferenceType == true;
                for (int i = 0; i < n; i++)
1287
                {
1288
                    var conversion = conversionBuilder[i];
1289
                    var element = elementBuilder[i];
1290
                    var resultType = resultBuilder[i];
1291 1292 1293
                    var sourceType = resultType?.TypeSymbol;
                    if (elementTypeIsReferenceType)
                    {
1294 1295 1296 1297 1298 1299
                        resultType = ApplyConversion(element, element, conversion, elementType.TypeSymbol, resultType, checkConversion: true, fromExplicitCast: false, out bool canConvertNestedNullability);
                        ReportNullReferenceAssignmentIfNecessary(element, elementType, resultType, useLegacyWarnings: false);
                        if (!canConvertNestedNullability)
                        {
                            ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullabilityMismatchInAssignment, element.Syntax, sourceType, elementType.TypeSymbol);
                        }
1300
                    }
1301 1302 1303
                }
            }

1304
            resultBuilder.Free();
1305
            elementBuilder.Free();
1306
            _resultType = _invalidType;
1307
            return arrayType;
1308 1309
        }

1310
        private static void GetArrayElements(BoundArrayInitialization node, ArrayBuilder<BoundExpression> builder)
1311
        {
1312
            foreach (var child in node.Initializers)
1313
            {
1314
                if (child.Kind == BoundKind.ArrayInitialization)
1315
                {
1316 1317 1318 1319 1320
                    GetArrayElements((BoundArrayInitialization)child, builder);
                }
                else
                {
                    builder.Add(child);
1321 1322 1323 1324
                }
            }
        }

1325
        public override BoundNode VisitArrayAccess(BoundArrayAccess node)
1326
        {
1327 1328 1329
            Debug.Assert(!IsConditionalState);

            VisitRvalue(node.Expression);
1330 1331 1332 1333 1334 1335

            Debug.Assert(!IsConditionalState);
            // No need to check expression type since System.Array is a reference type.
            Debug.Assert(node.Expression.Type.IsReferenceType);
            CheckPossibleNullReceiver(node.Expression, checkType: false);

1336
            var type = _resultType?.TypeSymbol as ArrayTypeSymbol;
1337

1338 1339 1340 1341 1342
            foreach (var i in node.Indices)
            {
                VisitRvalue(i);
            }

1343
            _resultType = type?.ElementType;
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
            return null;
        }

        private TypeSymbolWithAnnotations InferResultNullability(BoundBinaryOperator node, TypeSymbolWithAnnotations leftType, TypeSymbolWithAnnotations rightType)
        {
            return InferResultNullability(node.OperatorKind, node.MethodOpt, node.Type, leftType, rightType);
        }

        private TypeSymbolWithAnnotations InferResultNullability(BinaryOperatorKind operatorKind, MethodSymbol methodOpt, TypeSymbol resultType, TypeSymbolWithAnnotations leftType, TypeSymbolWithAnnotations rightType)
        {
1354
            bool? isNullable = null;
1355 1356
            if (operatorKind.IsUserDefined())
            {
1357
                if (operatorKind.IsLifted())
1358
                {
1359 1360
                    // PROTOTYPE(NullableReferenceTypes): Conversions: Lifted operator
                    return TypeSymbolWithAnnotations.Create(resultType, isNullableIfReferenceType: null);
1361
                }
1362 1363
                // PROTOTYPE(NullableReferenceTypes): Update method based on operand types.
                if ((object)methodOpt != null && methodOpt.ParameterCount == 2)
1364
                {
1365
                    return methodOpt.ReturnType;
1366 1367
                }
            }
1368
            else if (!operatorKind.IsDynamic() && resultType.IsReferenceType == true)
1369 1370 1371 1372 1373
            {
                switch (operatorKind.Operator() | operatorKind.OperandTypes())
                {
                    case BinaryOperatorKind.DelegateCombination:
                        {
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
                            bool? leftIsNullable = leftType?.IsNullable;
                            bool? rightIsNullable = rightType?.IsNullable;
                            if (leftIsNullable == false || rightIsNullable == false)
                            {
                                isNullable = false;
                            }
                            else if (leftIsNullable == true && rightIsNullable == true)
                            {
                                isNullable = true;
                            }
                            else
                            {
                                Debug.Assert(leftIsNullable == null || rightIsNullable == null);
                            }
1388
                        }
1389
                        break;
1390
                    case BinaryOperatorKind.DelegateRemoval:
1391 1392 1393 1394 1395
                        isNullable = true; // Delegate removal can produce null.
                        break;
                    default:
                        isNullable = false;
                        break;
1396 1397
                }
            }
1398
            return TypeSymbolWithAnnotations.Create(resultType, isNullable);
1399 1400 1401 1402 1403
        }

        protected override void AfterLeftChildHasBeenVisited(BoundBinaryOperator binary)
        {
            Debug.Assert(!IsConditionalState);
1404
            //if (this.State.Reachable) // PROTOTYPE(NullableReferenceTypes): Consider reachability?
1405
            {
1406
                TypeSymbolWithAnnotations leftType = _resultType;
1407 1408 1409 1410
                bool warnOnNullReferenceArgument = (binary.OperatorKind.IsUserDefined() && (object)binary.MethodOpt != null && binary.MethodOpt.ParameterCount == 2);

                if (warnOnNullReferenceArgument)
                {
1411
                    ReportArgumentWarnings(binary.Left, leftType, binary.MethodOpt.Parameters[0]);
1412 1413 1414 1415
                }

                VisitRvalue(binary.Right);
                Debug.Assert(!IsConditionalState);
1416

1417 1418
                // At this point, State.Reachable may be false for
                // invalid code such as `s + throw new Exception()`.
1419
                TypeSymbolWithAnnotations rightType = _resultType;
1420 1421 1422

                if (warnOnNullReferenceArgument)
                {
1423
                    ReportArgumentWarnings(binary.Right, rightType, binary.MethodOpt.Parameters[1]);
1424 1425 1426
                }

                Debug.Assert(!IsConditionalState);
1427
                _resultType = InferResultNullability(binary, leftType, rightType);
1428 1429 1430 1431 1432

                BinaryOperatorKind op = binary.OperatorKind.Operator();
                if (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual)
                {
                    BoundExpression operandComparedToNull = null;
1433
                    TypeSymbolWithAnnotations operandComparedToNullType = null;
1434 1435 1436 1437

                    if (binary.Right.ConstantValue?.IsNull == true)
                    {
                        operandComparedToNull = binary.Left;
1438
                        operandComparedToNullType = leftType;
1439 1440 1441 1442
                    }
                    else if (binary.Left.ConstantValue?.IsNull == true)
                    {
                        operandComparedToNull = binary.Right;
1443
                        operandComparedToNullType = rightType;
1444 1445 1446 1447
                    }

                    if (operandComparedToNull != null)
                    {
1448 1449 1450
                        // PROTOTYPE(NullableReferenceTypes): This check is incorrect since it compares declared
                        // nullability rather than tracked nullability. Moreover, we should only report such
                        // diagnostics for locals that are set or checked explicitly within this method.
1451
                        if (operandComparedToNullType?.IsNullable == false)
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
                        {
                            ReportStaticNullCheckingDiagnostics(op == BinaryOperatorKind.Equal ?
                                                                    ErrorCode.HDN_NullCheckIsProbablyAlwaysFalse :
                                                                    ErrorCode.HDN_NullCheckIsProbablyAlwaysTrue,
                                                                binary.Syntax);
                        }

                        // Skip reference conversions
                        operandComparedToNull = SkipReferenceConversions(operandComparedToNull);

                        if (operandComparedToNull.Type?.IsReferenceType == true)
                        {
F
Fredric Silberberg 已提交
1464
                            var slotBuilder = ArrayBuilder<int>.GetInstance();
F
Fredric Silberberg 已提交
1465 1466

                            // Set all nested conditional slots. For example in a?.b?.c we'll set a, b, and c
F
Fredric Silberberg 已提交
1467 1468
                            getOperandSlots(operandComparedToNull, slotBuilder);
                            if (slotBuilder.Count != 0)
1469
                            {
F
Fredric Silberberg 已提交
1470
                                Normalize(ref this.State);
1471
                                Split();
F
Fredric Silberberg 已提交
1472 1473
                                ref LocalState state = ref (op == BinaryOperatorKind.Equal) ? ref this.StateWhenFalse : ref this.StateWhenTrue;
                                foreach (int slot in slotBuilder)
1474
                                {
F
Fredric Silberberg 已提交
1475
                                    state[slot] = true;
1476 1477
                                }
                            }
F
Fredric Silberberg 已提交
1478 1479

                            slotBuilder.Free();
1480 1481 1482 1483 1484
                        }
                    }
                }
            }

F
Fredric Silberberg 已提交
1485
            void getOperandSlots(BoundExpression operand, ArrayBuilder<int> slotBuilder)
1486 1487 1488
            {
                Debug.Assert(operand != null);
                Debug.Assert(_lastConditionalAccessSlot == -1);
1489

1490 1491 1492 1493
                do
                {
                    // Due to the nature of binding, if there are conditional access they will be at the top of the bound tree,
                    // potentially with a conversion on top of it. We go through any conditional accesses, adding slots for the
F
Fredric Silberberg 已提交
1494
                    // conditional receivers if they have them. If we ever get to a receiver that MakeSlot doesn't return a slot
1495 1496 1497 1498 1499
                    // for, nothing underneath is trackable and we bail at that point. Example:
                    //
                    //     a?.GetB()?.C // a is a field, GetB is a method, and C is a property
                    //
                    // The top of the tree is the a?.GetB() conditional call. We'll ask for a slot for a, and we'll get one because
F
Fredric Silberberg 已提交
1500 1501
                    // locals have slots. The AccessExpression of the BoundConditionalAccess is another BoundConditionalAccess, this time
                    // with a receiver of the GetB() BoundCall. Attempting to get a slot for this receiver will fail, and we'll
1502
                    // return an array with just the slot for a.
F
Fredric Silberberg 已提交
1503
                    int slot;
1504 1505 1506
                    switch (operand.Kind)
                    {
                        case BoundKind.Conversion:
F
Fredric Silberberg 已提交
1507
                            // PROTOTYPE(NullableReferenceTypes): Detect when conversion has a nullable operand
1508 1509 1510 1511 1512 1513
                            operand = ((BoundConversion)operand).Operand;
                            continue;
                        case BoundKind.ConditionalAccess:
                            var conditional = (BoundConditionalAccess)operand;

                            slot = MakeSlot(conditional.Receiver);
1514 1515
                            if (slot > 0)
                            {
1516 1517
                                // If we got a slot we must have processed the previous conditional receiver.
                                Debug.Assert(_lastConditionalAccessSlot == -1);
1518

F
Fredric Silberberg 已提交
1519
                                slotBuilder.Add(slot);
1520 1521

                                // When MakeSlot is called on the nested AccessExpression, it will recurse through receivers
F
Fredric Silberberg 已提交
1522
                                // until it gets to the BoundConditionalReceiver associated with this node. In our override,
F
Fredric Silberberg 已提交
1523
                                // we substitute this slot when we encounter a BoundConditionalReceiver, and reset the
F
Fredric Silberberg 已提交
1524
                                // _lastConditionalAccess field.
1525 1526 1527 1528 1529
                                _lastConditionalAccessSlot = slot;
                                operand = conditional.AccessExpression;
                                continue;
                            }

F
Fredric Silberberg 已提交
1530 1531 1532
                            // If there's no slot for this receiver, there cannot be another slot for any of the remaining
                            // access expressions.
                            break;
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
                        default:
                            // Attempt to create a slot for the current thing. If there were any more conditional accesses,
                            // they would have been on top, so this is the last thing we need to specially handle.

                            // PROTOTYPE(NullableReferenceTypes): When we handle unconditional access survival (ie after
                            // c.D has been invoked, c must be nonnull or we've thrown a NullRef), revisit whether
                            // we need more special handling here

                            slot = MakeSlot(operand);
                            if (slot > 0)
                            {
F
Fredric Silberberg 已提交
1544 1545 1546
                                // If we got a slot then all previous BoundCondtionalReceivers must have been handled.
                                Debug.Assert(_lastConditionalAccessSlot == -1);

F
Fredric Silberberg 已提交
1547
                                slotBuilder.Add(slot);
1548
                            }
F
Fredric Silberberg 已提交
1549

F
Fredric Silberberg 已提交
1550
                            break;
1551
                    }
F
Fredric Silberberg 已提交
1552 1553 1554 1555 1556

                    // If we didn't get a slot, it's possible that the current _lastConditionalSlot was never processed,
                    // so we reset before leaving the function.
                    _lastConditionalAccessSlot = -1;
                    return;
1557
                } while (true);
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
            }
        }

        private static BoundExpression SkipReferenceConversions(BoundExpression possiblyConversion)
        {
            while (possiblyConversion.Kind == BoundKind.Conversion)
            {
                var conversion = (BoundConversion)possiblyConversion;
                switch (conversion.ConversionKind)
                {
                    case ConversionKind.ImplicitReference:
                    case ConversionKind.ExplicitReference:
                        possiblyConversion = conversion.Operand;
                        break;

                    default:
                        return possiblyConversion;
                }
            }

            return possiblyConversion;
        }

        public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node)
        {
            Debug.Assert(!IsConditionalState);

1585 1586 1587
            BoundExpression leftOperand = node.LeftOperand;
            BoundExpression rightOperand = node.RightOperand;

1588 1589
            TypeSymbolWithAnnotations leftResult = VisitRvalueWithResult(leftOperand);
            TypeSymbolWithAnnotations rightResult;
1590

1591
            if (IsConstantNull(leftOperand))
1592
            {
1593 1594 1595
                rightResult = VisitRvalueWithResult(rightOperand);
                // Should be able to use rightResult for the result of the operator but
                // binding may have generated a different result type in the case of errors.
1596
                _resultType = TypeSymbolWithAnnotations.Create(node.Type, getIsNullable(rightOperand, rightResult));
1597
                return null;
1598 1599
            }

1600
            var leftState = this.State.Clone();
1601
            if (leftResult?.IsNullable == false)
1602
            {
1603
                ReportStaticNullCheckingDiagnostics(ErrorCode.HDN_ExpressionIsProbablyNeverNull, leftOperand.Syntax);
1604 1605
            }

1606
            bool leftIsConstant = leftOperand.ConstantValue != null;
1607 1608 1609 1610 1611
            if (leftIsConstant)
            {
                SetUnreachable();
            }

1612 1613
            // PROTOTYPE(NullableReferenceTypes): For cases where the left operand determines
            // the type, we should unwrap the right conversion and re-apply.
1614
            rightResult = VisitRvalueWithResult(rightOperand);
1615
            IntersectWith(ref this.State, ref leftState);
1616
            TypeSymbol resultType;
1617 1618
            var leftResultType = leftResult?.TypeSymbol;
            var rightResultType = rightResult?.TypeSymbol;
1619
            switch (node.OperatorResultKind)
1620
            {
1621 1622 1623 1624
                case BoundNullCoalescingOperatorResultKind.NoCommonType:
                    resultType = node.Type;
                    break;
                case BoundNullCoalescingOperatorResultKind.LeftType:
1625
                    resultType = getLeftResultType(leftResultType, rightResultType);
1626 1627
                    break;
                case BoundNullCoalescingOperatorResultKind.LeftUnwrappedType:
1628
                    resultType = getLeftResultType(leftResultType.StrippedType(), rightResultType);
1629 1630
                    break;
                case BoundNullCoalescingOperatorResultKind.RightType:
1631
                    resultType = getRightResultType(leftResultType, rightResultType);
1632 1633
                    break;
                case BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType:
1634
                    resultType = getRightResultType(leftResultType.StrippedType(), rightResultType);
1635 1636
                    break;
                case BoundNullCoalescingOperatorResultKind.RightDynamicType:
1637
                    resultType = rightResultType;
1638 1639 1640
                    break;
                default:
                    throw ExceptionUtilities.UnexpectedValue(node.OperatorResultKind);
1641 1642
            }

1643
            bool? resultIsNullable = getIsNullable(leftOperand, leftResult) == false ? false : getIsNullable(rightOperand, rightResult);
1644
            _resultType = TypeSymbolWithAnnotations.Create(resultType, resultIsNullable);
1645
            return null;
1646

1647
            bool? getIsNullable(BoundExpression e, TypeSymbolWithAnnotations t) => (t is null) ? e.IsNullable() : t.IsNullable;
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
            TypeSymbol getLeftResultType(TypeSymbol leftType, TypeSymbol rightType)
            {
                // If there was an identity conversion between the two operands (in short, if there
                // is no implicit conversion on the right operand), then check nullable conversions
                // in both directions since it's possible the right operand is the better result type.
                if ((object)rightType != null &&
                    (node.RightOperand as BoundConversion)?.ExplicitCastInCode != false &&
                    GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: false).Exists)
                {
                    return rightType;
                }
1659

1660 1661 1662 1663 1664 1665 1666
                GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true);
                return leftType;
            }
            TypeSymbol getRightResultType(TypeSymbol leftType, TypeSymbol rightType)
            {
                GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: true);
                return rightType;
1667
            }
1668 1669 1670 1671 1672 1673
        }

        public override BoundNode VisitConditionalAccess(BoundConditionalAccess node)
        {
            Debug.Assert(!IsConditionalState);

1674
            var receiver = node.Receiver;
1675
            var receiverType = VisitRvalueWithResult(receiver);
1676

1677
            var receiverState = this.State.Clone();
1678

1679 1680
            if (receiver.Type?.IsReferenceType == true)
            {
1681
                if (receiverType?.IsNullable == false)
1682 1683 1684
                {
                    ReportStaticNullCheckingDiagnostics(ErrorCode.HDN_ExpressionIsProbablyNeverNull, receiver.Syntax);
                }
1685

1686 1687 1688 1689 1690 1691 1692 1693 1694
                int slot = MakeSlot(SkipReferenceConversions(receiver));
                if (slot > 0)
                {
                    if (slot >= this.State.Capacity) Normalize(ref this.State);
                    this.State[slot] = true;
                }
            }

            if (IsConstantNull(node.Receiver))
1695
            {
1696
                SetUnreachable();
1697 1698
            }

1699 1700
            VisitRvalue(node.AccessExpression);
            IntersectWith(ref this.State, ref receiverState);
1701

1702 1703
            // PROTOTYPE(NullableReferenceTypes): Use flow analysis type rather than node.Type
            // so that nested nullability is inferred from flow analysis. See VisitConditionalOperator.
1704
            _resultType = TypeSymbolWithAnnotations.Create(node.Type, isNullableIfReferenceType: receiverType?.IsNullable | _resultType?.IsNullable);
1705 1706 1707 1708 1709 1710
            // PROTOTYPE(NullableReferenceTypes): Report conversion warnings.
            return null;
        }

        public override BoundNode VisitConditionalOperator(BoundConditionalOperator node)
        {
C
Charles Stoner 已提交
1711
            var isByRef = node.IsRef;
1712 1713 1714 1715

            VisitCondition(node.Condition);
            var consequenceState = this.StateWhenTrue;
            var alternativeState = this.StateWhenFalse;
1716 1717 1718

            BoundExpression consequence;
            BoundExpression alternative;
1719 1720
            TypeSymbolWithAnnotations consequenceResult;
            TypeSymbolWithAnnotations alternativeResult;
1721 1722
            bool? isNullableIfReferenceType;

1723 1724
            if (IsConstantTrue(node.Condition))
            {
1725 1726 1727
                (alternative, alternativeResult) = visitConditionalOperand(alternativeState, node.Alternative);
                (consequence, consequenceResult) = visitConditionalOperand(consequenceState, node.Consequence);
                isNullableIfReferenceType = getIsNullableIfReferenceType(consequence, consequenceResult);
1728 1729 1730
            }
            else if (IsConstantFalse(node.Condition))
            {
1731 1732 1733
                (consequence, consequenceResult) = visitConditionalOperand(consequenceState, node.Consequence);
                (alternative, alternativeResult) = visitConditionalOperand(alternativeState, node.Alternative);
                isNullableIfReferenceType = getIsNullableIfReferenceType(alternative, alternativeResult);
1734 1735
            }
            else
1736
            {
1737
                (consequence, consequenceResult) = visitConditionalOperand(consequenceState, node.Consequence);
1738
                Unsplit();
1739
                (alternative, alternativeResult) = visitConditionalOperand(alternativeState, node.Alternative);
1740 1741
                Unsplit();
                IntersectWith(ref this.State, ref consequenceState);
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
                isNullableIfReferenceType = (getIsNullableIfReferenceType(consequence, consequenceResult) | getIsNullableIfReferenceType(alternative, alternativeResult));
            }

            TypeSymbolWithAnnotations resultType;
            if (node.HasErrors)
            {
                resultType = null;
            }
            else
            {
                // Determine nested nullability using BestTypeInferrer.
                // For constant conditions, we could use the nested nullability of the particular
                // branch, but that requires using the nullability of the branch as it applies to the
                // target type. For instance, the result of the conditional in the following should
                // be `IEnumerable<object>` not `object[]`:
                //   object[] a = ...;
                //   IEnumerable<object?> b = ...;
                //   var c = true ? a : b;
                HashSet<DiagnosticInfo> useSiteDiagnostics = null;
                resultType = BestTypeInferrer.InferBestTypeForConditionalOperator(
                    createPlaceholderIfNecessary(consequence, consequenceResult),
                    createPlaceholderIfNecessary(alternative, alternativeResult),
                    _conversions,
                    out _,
                    ref useSiteDiagnostics);
                if (resultType is null)
1768
                {
1769 1770 1771
                    ReportStaticNullCheckingDiagnostics(
                        ErrorCode.WRN_NoBestNullabilityConditionalExpression,
                        node.Syntax,
1772 1773
                        GetTypeAsDiagnosticArgument(consequenceResult?.TypeSymbol),
                        GetTypeAsDiagnosticArgument(alternativeResult?.TypeSymbol));
1774
                }
1775
            }
1776
            resultType = TypeSymbolWithAnnotations.Create(resultType?.TypeSymbol ?? node.Type.SetUnknownNullabilityForReferenceTypes(), isNullableIfReferenceType);
1777

1778
            _resultType = resultType;
1779 1780
            return null;

1781
            bool? getIsNullableIfReferenceType(BoundExpression expr, TypeSymbolWithAnnotations type)
1782 1783
            {
                if ((object)type != null)
1784
                {
1785
                    return type.IsNullable;
1786
                }
1787 1788 1789 1790 1791
                if (expr.IsLiteralNullOrDefault())
                {
                    return true;
                }
                return null;
1792 1793
            }

1794
            BoundExpression createPlaceholderIfNecessary(BoundExpression expr, TypeSymbolWithAnnotations type)
1795 1796 1797 1798 1799
            {
                return type is null ?
                    expr :
                    new BoundValuePlaceholder(expr.Syntax, type.IsNullable, type.TypeSymbol);
            }
1800

1801
            (BoundExpression, TypeSymbolWithAnnotations) visitConditionalOperand(LocalState state, BoundExpression operand)
1802 1803 1804 1805 1806 1807 1808 1809
            {
                SetState(state);
                if (isByRef)
                {
                    VisitLvalue(operand);
                }
                else
                {
1810
                    (operand, _) = RemoveConversion(operand, includeExplicitConversions: false);
1811 1812
                    Visit(operand);
                }
1813
                return (operand, _resultType);
1814
            }
1815 1816
        }

1817 1818 1819
        public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node)
        {
            var result = base.VisitConditionalReceiver(node);
1820
            SetResult(node);
1821 1822 1823 1824 1825
            return result;
        }

        public override BoundNode VisitCall(BoundCall node)
        {
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
            var method = node.Method;

            if (method.CallsAreOmitted(node.SyntaxTree))
            {
                // PROTOTYPE(NullableReferenceTypes): Should skip state set in
                // arguments of omitted call. See PreciseAbstractFlowPass.VisitCall.
            }

            var receiverOpt = node.ReceiverOpt;
            if (receiverOpt != null && method.MethodKind != MethodKind.Constructor)
            {
                VisitRvalue(receiverOpt);
                CheckPossibleNullReceiver(receiverOpt);
                // PROTOTYPE(NullableReferenceTypes): Update method based on inferred receiver type.
            }
1841

1842 1843 1844
            // PROTOTYPE(NullableReferenceTypes): Can we handle some error cases?
            // (Compare with CSharpOperationFactory.CreateBoundCallOperation.)
            if (!node.HasErrors)
1845
            {
1846
                ImmutableArray<RefKind> refKindsOpt = node.ArgumentRefKindsOpt;
1847
                (ImmutableArray<BoundExpression> arguments, ImmutableArray<Conversion> conversions) = RemoveArgumentConversions(node.Arguments, refKindsOpt);
1848 1849
                ImmutableArray<int> argsToParamsOpt = node.ArgsToParamsOpt;

1850
                method = VisitArguments(node, arguments, refKindsOpt, method.Parameters, argsToParamsOpt, node.Expanded, method, conversions);
1851 1852 1853 1854 1855 1856 1857
            }

            UpdateStateForCall(node);

            if (method.MethodKind == MethodKind.LocalFunction)
            {
                var localFunc = (LocalFunctionSymbol)method.OriginalDefinition;
1858 1859 1860
                ReplayReadsAndWrites(localFunc, node.Syntax, writes: true);
            }

1861
            //if (this.State.Reachable) // PROTOTYPE(NullableReferenceTypes): Consider reachability?
1862
            {
1863
                _resultType = method.ReturnType;
1864 1865
            }

1866
            return null;
1867 1868
        }

1869 1870 1871 1872
        /// <summary>
        /// For each argument, figure out if its corresponding parameter is annotated with NotNullWhenFalse or
        /// EnsuresNotNull.
        /// </summary>
1873
        private static ImmutableArray<FlowAnalysisAnnotations> GetAnnotations(int numArguments,
1874 1875
            bool expanded, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<int> argsToParamsOpt)
        {
1876
            ArrayBuilder<FlowAnalysisAnnotations> builder = null;
1877 1878 1879 1880

            for (int i = 0; i < numArguments; i++)
            {
                (ParameterSymbol parameter, _) = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded);
1881
                FlowAnalysisAnnotations annotations = parameter?.FlowAnalysisAnnotations ?? FlowAnalysisAnnotations.None;
1882

1883
                annotations = removeInapplicableAnnotations(parameter, annotations);
1884

1885
                if (annotations != FlowAnalysisAnnotations.None && builder == null)
1886
                {
1887 1888
                    builder = ArrayBuilder<FlowAnalysisAnnotations>.GetInstance(numArguments);
                    builder.AddMany(FlowAnalysisAnnotations.None, i);
1889 1890 1891 1892 1893 1894 1895 1896 1897
                }

                if (builder != null)
                {
                    builder.Add(annotations);
                }
            }

            return builder == null ? default : builder.ToImmutableAndFree();
1898

1899
            FlowAnalysisAnnotations removeInapplicableAnnotations(ParameterSymbol parameter, FlowAnalysisAnnotations annotations)
1900
            {
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
                // Ignore NotNullWhenTrue that is inapplicable
                annotations = removeInapplicableNotNullWhenSense(parameter, annotations, sense: true);

                // Ignore NotNullWhenFalse that is inapplicable
                annotations = removeInapplicableNotNullWhenSense(parameter, annotations, sense: false);

                const FlowAnalysisAnnotations both = FlowAnalysisAnnotations.AssertsTrue | FlowAnalysisAnnotations.AssertsFalse;
                if (parameter?.Type.SpecialType != SpecialType.System_Boolean)
                {
                    // AssertsTrue and AssertsFalse must be applied to a bool parameter
                    annotations &= ~both;
                }
                else if ((annotations & both) == both)
                {
                    // We'll ignore AssertsTrue and AssertsFalse if both set
                    annotations &= ~both;
                }

                return annotations;
            }

            FlowAnalysisAnnotations removeInapplicableNotNullWhenSense(ParameterSymbol parameter, FlowAnalysisAnnotations annotations, bool sense)
            {
                if (parameter is null)
                {
                    return annotations;
                }

                var whenSense = sense ? FlowAnalysisAnnotations.NotNullWhenTrue : FlowAnalysisAnnotations.NotNullWhenFalse;
                var whenNotSense = sense ? FlowAnalysisAnnotations.NotNullWhenFalse : FlowAnalysisAnnotations.NotNullWhenTrue;
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953

                // NotNullWhenSense (without NotNullWhenNotSense) must be applied on a bool-returning member
                if ((annotations & whenSense) != 0 &&
                    (annotations & whenNotSense) == 0 &&
                    parameter.ContainingSymbol.GetTypeOrReturnType().SpecialType != SpecialType.System_Boolean)
                {
                    annotations &= ~whenSense;
                }

                // NotNullWhenSense must be applied to a reference or unconstrained generic type
                if ((annotations & whenSense) != 0 && parameter.Type.IsValueType != false)
                {
                    annotations &= ~whenSense;
                }

                // NotNullWhenSense is inapplicable when argument corresponds to params parameter and we're in expanded form
                if ((annotations & whenSense) != 0 && expanded && ReferenceEquals(parameter, parameters.Last()))
                {
                    annotations &= ~whenSense;
                }

                return annotations;
            }
1954 1955
        }

1956 1957 1958
        // PROTOTYPE(NullableReferenceTypes): Record in the node whether type
        // arguments were implicit, to allow for cases where the syntax is not an
        // invocation (such as a synthesized call from a query interpretation).
1959
        private static bool HasImplicitTypeArguments(BoundExpression node)
1960
        {
1961 1962 1963
            var syntax = node.Syntax;
            if (syntax.Kind() != SyntaxKind.InvocationExpression)
            {
1964
                // Unexpected syntax kind.
1965 1966
                return false;
            }
1967
            var nameSyntax = Binder.GetNameSyntax(((InvocationExpressionSyntax)syntax).Expression, out var _);
1968
            if (nameSyntax == null)
1969
            {
1970 1971
                // Unexpected syntax kind.
                return false;
1972
            }
1973 1974
            nameSyntax = nameSyntax.GetUnqualifiedName();
            return nameSyntax.Kind() != SyntaxKind.GenericName;
1975 1976
        }

1977
        protected override void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method)
1978
        {
1979 1980 1981
            // Callers should be using VisitArguments overload below.
            throw ExceptionUtilities.Unreachable;
        }
1982

1983 1984 1985 1986 1987 1988 1989
        private void VisitArguments(
            BoundExpression node,
            ImmutableArray<BoundExpression> arguments,
            ImmutableArray<RefKind> refKindsOpt,
            MethodSymbol method,
            ImmutableArray<int> argsToParamsOpt,
            bool expanded)
1990
        {
1991
            // PROTOTYPE(NullableReferenceTypes): What about conversions here?
1992
            VisitArguments(node, arguments, refKindsOpt, method is null ? default : method.Parameters, argsToParamsOpt, expanded);
1993 1994
        }

1995 1996
        private void VisitArguments(
            BoundExpression node,
1997 1998
            ImmutableArray<BoundExpression> arguments,
            ImmutableArray<RefKind> refKindsOpt,
1999
            PropertySymbol property,
2000 2001
            ImmutableArray<int> argsToParamsOpt,
            bool expanded)
2002
        {
2003
            // PROTOTYPE(NullableReferenceTypes): What about conversions here?
2004 2005 2006
            VisitArguments(node, arguments, refKindsOpt, property is null ? default : property.Parameters, argsToParamsOpt, expanded);
        }

2007 2008 2009 2010
        /// <summary>
        /// If you pass in a method symbol, its types will be re-inferred and the re-inferred method will be returned.
        /// </summary>
        private MethodSymbol VisitArguments(
2011 2012 2013 2014 2015
            BoundExpression node,
            ImmutableArray<BoundExpression> arguments,
            ImmutableArray<RefKind> refKindsOpt,
            ImmutableArray<ParameterSymbol> parameters,
            ImmutableArray<int> argsToParamsOpt,
2016
            bool expanded,
2017 2018
            MethodSymbol method = null,
            ImmutableArray<Conversion> conversions = default)
2019 2020
        {
            Debug.Assert(!arguments.IsDefault);
2021 2022 2023
            var savedState = this.State.Clone();

            // We do a first pass to work through the arguments without making any assumptions
2024
            ImmutableArray<TypeSymbolWithAnnotations> results = VisitArgumentsEvaluate(arguments, refKindsOpt);
2025 2026 2027

            if ((object)method != null && method.IsGenericMethod && HasImplicitTypeArguments(node))
            {
2028
                method = InferMethodTypeArguments((BoundCall)node, method, GetArgumentsForMethodTypeInference(arguments, results));
2029 2030 2031
                parameters = method.Parameters;
            }

2032 2033 2034 2035
            // PROTOTYPE(NullableReferenceTypes): Can we handle some error cases?
            // (Compare with CSharpOperationFactory.CreateBoundCallOperation.)
            if (!node.HasErrors && !parameters.IsDefault)
            {
2036
                VisitArgumentConversions(arguments, conversions, refKindsOpt, parameters, argsToParamsOpt, expanded, results);
2037
            }
2038 2039 2040

            // We do a second pass through the arguments, ignoring any diagnostics produced, but honoring the annotations,
            // to get the proper result state.
2041
            ImmutableArray<FlowAnalysisAnnotations> annotations = GetAnnotations(arguments.Length, expanded, parameters, argsToParamsOpt);
2042 2043 2044 2045

            if (!annotations.IsDefault)
            {
                this.SetState(savedState);
2046 2047 2048 2049 2050

                bool saveDisableDiagnostics = _disableDiagnostics;
                _disableDiagnostics = true;
                if (!node.HasErrors && !parameters.IsDefault)
                {
2051
                    VisitArgumentConversions(arguments, conversions, refKindsOpt, parameters, argsToParamsOpt, expanded, results); // recompute out vars after state was reset
2052
                }
2053
                VisitArgumentsEvaluateHonoringAnnotations(arguments, refKindsOpt, annotations);
2054 2055

                _disableDiagnostics = saveDisableDiagnostics;
2056 2057
            }

2058
            return method;
2059 2060
        }

2061
        private ImmutableArray<TypeSymbolWithAnnotations> VisitArgumentsEvaluate(
2062 2063
            ImmutableArray<BoundExpression> arguments,
            ImmutableArray<RefKind> refKindsOpt)
2064 2065 2066 2067
        {
            Debug.Assert(!IsConditionalState);
            int n = arguments.Length;
            if (n == 0)
2068
            {
2069
                return ImmutableArray<TypeSymbolWithAnnotations>.Empty;
2070
            }
2071
            var builder = ArrayBuilder<TypeSymbolWithAnnotations>.GetInstance(n);
2072
            for (int i = 0; i < n; i++)
2073
            {
2074
                VisitArgumentEvaluate(arguments, refKindsOpt, i, preserveConditionalState: false);
2075
                builder.Add(_resultType);
2076 2077
            }

2078
            _resultType = _invalidType;
2079 2080 2081
            return builder.ToImmutableAndFree();
        }

2082
        private void VisitArgumentEvaluate(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, int i, bool preserveConditionalState)
2083
        {
2084
            Debug.Assert(!IsConditionalState);
2085 2086 2087 2088 2089
            RefKind refKind = GetRefKind(refKindsOpt, i);
            var argument = arguments[i];
            if (refKind != RefKind.Out)
            {
                // PROTOTYPE(NullReferenceTypes): `ref` arguments should be treated as l-values
2090
                // for assignment. See `ref x3` in NullableReferenceTypesTests.PassingParameters_01.
2091 2092 2093 2094 2095 2096 2097 2098 2099
                if (preserveConditionalState)
                {
                    Visit(argument);
                    // No Unsplit
                }
                else
                {
                    VisitRvalue(argument);
                }
2100 2101 2102
            }
            else
            {
2103 2104
                // As far as we can tell, there is no scenario relevant to nullability analysis
                // where splitting an L-value (for instance with a ref ternary) would affect the result.
2105 2106 2107 2108 2109 2110
                VisitLvalue(argument);
            }
        }

        /// <summary>
        /// Visit all the arguments for the purpose of computing the exit state of the method,
2111
        /// given the annotations.
2112
        /// If there is any [NotNullWhenTrue/False] annotation, then we'll return in a conditional state for the invocation.
2113 2114 2115 2116
        /// </summary>
        private void VisitArgumentsEvaluateHonoringAnnotations(
            ImmutableArray<BoundExpression> arguments,
            ImmutableArray<RefKind> refKindsOpt,
2117
            ImmutableArray<FlowAnalysisAnnotations> annotations)
2118 2119 2120
        {
            Debug.Assert(!IsConditionalState);
            Debug.Assert(annotations.Length == arguments.Length);
2121
            Debug.Assert(_disableDiagnostics);
2122 2123 2124

            for (int i = 0; i < arguments.Length; i++)
            {
2125 2126 2127 2128
                FlowAnalysisAnnotations annotation = annotations[i];
                bool assertsTrue = (annotation & FlowAnalysisAnnotations.AssertsTrue) != 0;
                bool assertsFalse = (annotation & FlowAnalysisAnnotations.AssertsFalse) != 0;

2129
                if (this.IsConditionalState)
2130
                {
2131
                    // We could be in a conditional state because of a conditional annotation (like NotNullWhenFalse)
2132 2133
                    // Then WhenTrue/False states correspond to the invocation returning true/false

2134
                    // We'll first assume that we're in the unconditional state where the method returns true,
2135 2136 2137 2138 2139 2140
                    // then we'll repeat assuming the method returns false.

                    LocalState whenTrue = this.StateWhenTrue.Clone();
                    LocalState whenFalse = this.StateWhenFalse.Clone();

                    this.SetState(whenTrue);
2141
                    visitArgumentEvaluateAndUnsplit(i, assertsTrue, assertsFalse);
2142 2143 2144 2145
                    Debug.Assert(!IsConditionalState);
                    whenTrue = this.State; // LocalState may be a struct

                    this.SetState(whenFalse);
2146
                    visitArgumentEvaluateAndUnsplit(i, assertsTrue, assertsFalse);
2147 2148 2149 2150
                    Debug.Assert(!IsConditionalState);
                    whenFalse = this.State; // LocalState may be a struct

                    this.SetConditionalState(whenTrue, whenFalse);
2151 2152 2153
                }
                else
                {
2154
                    visitArgumentEvaluateAndUnsplit(i, assertsTrue, assertsFalse);
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
                }

                var argument = arguments[i];
                if (argument.Type?.IsReferenceType != true)
                {
                    continue;
                }

                int slot = MakeSlot(argument);
                if (slot <= 0)
                {
                    continue;
                }

2169 2170
                bool notNullWhenTrue = (annotation & FlowAnalysisAnnotations.NotNullWhenTrue) != 0;
                bool notNullWhenFalse = (annotation & FlowAnalysisAnnotations.NotNullWhenFalse) != 0;
2171 2172 2173 2174
                // The WhenTrue/False states correspond to the invocation returning true/false
                bool wasPreviouslySplit = this.IsConditionalState;
                Split();
                if (notNullWhenTrue)
2175
                {
2176
                    this.StateWhenTrue[slot] = true;
2177
                }
2178
                if (notNullWhenFalse)
2179 2180
                {
                    this.StateWhenFalse[slot] = true;
2181
                    if (notNullWhenTrue && !wasPreviouslySplit) Unsplit();
2182
                }
2183
            }
2184

2185
            _resultType = _invalidType;
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210

            // Evaluate an argument, potentially producing a split state.
            // Then unsplit it based on [AssertsTrue] or [AssertsFalse] attributes, or default Unsplit otherwise.
            void visitArgumentEvaluateAndUnsplit(int argumentIndex, bool assertsTrue, bool assertsFalse)
            {
                Debug.Assert(!IsConditionalState);
                VisitArgumentEvaluate(arguments, refKindsOpt, argumentIndex, preserveConditionalState: true);

                if (!this.IsConditionalState)
                {
                    return;
                }
                else if (assertsTrue)
                {
                    this.SetState(this.StateWhenTrue);
                }
                else if (assertsFalse)
                {
                    this.SetState(this.StateWhenFalse);
                }
                else
                {
                    this.Unsplit();
                }
            }
2211 2212
        }

2213
        private void VisitArgumentConversions(
2214
            ImmutableArray<BoundExpression> arguments,
2215
            ImmutableArray<Conversion> conversions,
2216
            ImmutableArray<RefKind> refKindsOpt,
2217
            ImmutableArray<ParameterSymbol> parameters,
2218 2219
            ImmutableArray<int> argsToParamsOpt,
            bool expanded,
2220
            ImmutableArray<TypeSymbolWithAnnotations> results)
2221
        {
2222
            for (int i = 0; i < arguments.Length; i++)
2223
            {
2224 2225
                (ParameterSymbol parameter, TypeSymbolWithAnnotations parameterType) = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded);
                if (parameter is null)
2226
                {
2227
                    continue;
2228
                }
2229
                VisitArgumentConversion(
2230
                    arguments[i],
2231
                    conversions.IsDefault ? Conversion.Identity : conversions[i],
2232 2233 2234 2235
                    GetRefKind(refKindsOpt, i),
                    parameter,
                    parameterType,
                    results[i]);
2236 2237
            }
        }
2238

2239 2240 2241
        /// <summary>
        /// Report warnings for an argument corresponding to a specific parameter.
        /// </summary>
2242
        private void VisitArgumentConversion(
2243
            BoundExpression argument,
2244
            Conversion conversion,
2245 2246 2247
            RefKind refKind,
            ParameterSymbol parameter,
            TypeSymbolWithAnnotations parameterType,
2248
            TypeSymbolWithAnnotations resultType)
2249 2250 2251 2252 2253 2254 2255
        {
            var argumentType = resultType?.TypeSymbol;
            switch (refKind)
            {
                case RefKind.None:
                case RefKind.In:
                    {
2256
                        resultType = ApplyConversion(argument, argument, conversion, parameterType.TypeSymbol, resultType, checkConversion: true, fromExplicitCast: false, out bool canConvertNestedNullability);
2257
                        if (!ReportNullReferenceArgumentIfNecessary(argument, resultType, parameter, parameterType) &&
2258
                            !canConvertNestedNullability)
2259 2260 2261 2262 2263 2264
                        {
                            ReportNullabilityMismatchInArgument(argument, argumentType, parameter, parameterType.TypeSymbol);
                        }
                    }
                    break;
                case RefKind.Out:
2265
                    {
2266 2267
                        bool reportedWarning = false;
                        if (argument is BoundLocal local && local.DeclarationKind == BoundLocalDeclarationKind.WithInferredType)
2268
                        {
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
                            _variableTypes[local.LocalSymbol] = parameterType;
                            resultType = parameterType;
                        }
                        if (argument.Kind != BoundKind.SuppressNullableWarningExpression)
                        {
                            reportedWarning = ReportNullReferenceAssignmentIfNecessary(argument, resultType, parameterType, useLegacyWarnings: UseLegacyWarnings(argument));
                        }
                        if (!reportedWarning)
                        {
                            HashSet<DiagnosticInfo> useSiteDiagnostics = null;
                            if (!_conversions.HasIdentityOrImplicitReferenceConversion(parameterType.TypeSymbol, argumentType, ref useSiteDiagnostics))
                            {
                                ReportNullabilityMismatchInArgument(argument, argumentType, parameter, parameterType.TypeSymbol);
                            }
2283
                        }
2284
                        // Set nullable state of argument to parameter type.
2285
                        TrackNullableStateForAssignment(argument, resultType, MakeSlot(argument), parameterType);
2286
                        break;
2287 2288 2289
                    }
                case RefKind.Ref:
                    {
2290 2291
                        bool reportedWarning = false;
                        if (argument.Kind != BoundKind.SuppressNullableWarningExpression)
2292
                        {
2293 2294
                            reportedWarning = ReportNullReferenceArgumentIfNecessary(argument, resultType, parameter, parameterType) ||
                                ReportNullReferenceAssignmentIfNecessary(argument, resultType, parameterType, useLegacyWarnings: UseLegacyWarnings(argument));
2295
                        }
2296 2297 2298 2299 2300 2301 2302 2303 2304
                        if (!reportedWarning)
                        {
                            if ((object)argumentType != null &&
                                IsNullabilityMismatch(argumentType, parameterType.TypeSymbol))
                            {
                                ReportNullabilityMismatchInArgument(argument, argumentType, parameter, parameterType.TypeSymbol);
                            }
                        }
                        // Set nullable state of argument to parameter type.
2305
                        TrackNullableStateForAssignment(argument, resultType, MakeSlot(argument), parameterType);
2306
                        break;
2307 2308 2309 2310 2311 2312
                    }
                default:
                    throw ExceptionUtilities.UnexpectedValue(refKind);
            }
        }

2313 2314 2315
        private static (ImmutableArray<BoundExpression> Arguments, ImmutableArray<Conversion> Conversions) RemoveArgumentConversions(
            ImmutableArray<BoundExpression> arguments,
            ImmutableArray<RefKind> refKindsOpt)
2316
        {
2317
            int n = arguments.Length;
2318
            var conversions = default(ImmutableArray<Conversion>);
2319
            if (n > 0)
2320
            {
2321
                var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(n);
2322
                var conversionsBuilder = ArrayBuilder<Conversion>.GetInstance(n);
2323 2324 2325 2326 2327
                bool includedConversion = false;
                for (int i = 0; i < n; i++)
                {
                    RefKind refKind = GetRefKind(refKindsOpt, i);
                    var argument = arguments[i];
2328 2329
                    var conversion = Conversion.Identity;
                    // PROTOTYPE(NullableReferenceTypes): Should `RefKind.In` be treated similarly to `RefKind.None`?
2330 2331
                    if (refKind == RefKind.None)
                    {
2332 2333 2334
                        var before = argument;
                        (argument, conversion) = RemoveConversion(argument, includeExplicitConversions: false);
                        if (argument != before)
2335 2336 2337 2338 2339
                        {
                            includedConversion = true;
                        }
                    }
                    argumentsBuilder.Add(argument);
2340
                    conversionsBuilder.Add(conversion);
2341 2342 2343 2344
                }
                if (includedConversion)
                {
                    arguments = argumentsBuilder.ToImmutable();
2345
                    conversions = conversionsBuilder.ToImmutable();
2346 2347
                }
                argumentsBuilder.Free();
2348
                conversionsBuilder.Free();
2349
            }
2350
            return (arguments, conversions);
2351 2352
        }

2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368
        private VariableState GetVariableState()
        {
            // PROTOTYPE(NullableReferenceTypes): To track nullability of captured variables inside and
            // outside a lambda, the lambda should be considered executed at the location the lambda
            // is converted to a delegate.
            return new VariableState(
                _variableSlot.ToImmutableDictionary(),
                ImmutableArray.Create(variableBySlot, start: 0, length: nextVariableSlot),
                _variableTypes.ToImmutableDictionary());
        }

        private UnboundLambda GetUnboundLambda(BoundLambda expr, VariableState variableState)
        {
            return expr.UnboundLambda.WithNullableState(_binder, variableState);
        }

2369 2370 2371 2372 2373
        private static (ParameterSymbol Parameter, TypeSymbolWithAnnotations Type) GetCorrespondingParameter(
            int argumentOrdinal,
            ImmutableArray<ParameterSymbol> parameters,
            ImmutableArray<int> argsToParamsOpt,
            bool expanded)
2374
        {
2375 2376 2377 2378
            if (parameters.IsDefault)
            {
                return (null, null);
            }
2379

2380
            int n = parameters.Length;
2381 2382 2383 2384
            ParameterSymbol parameter;

            if (argsToParamsOpt.IsDefault)
            {
2385
                if (argumentOrdinal < n)
2386
                {
2387
                    parameter = parameters[argumentOrdinal];
2388 2389 2390
                }
                else if (expanded)
                {
2391
                    parameter = parameters[n - 1];
2392 2393 2394 2395
                }
                else
                {
                    parameter = null;
2396 2397 2398 2399
                }
            }
            else
            {
2400 2401
                int parameterOrdinal = argsToParamsOpt[argumentOrdinal];

2402
                if (parameterOrdinal < n)
2403
                {
2404
                    parameter = parameters[parameterOrdinal];
2405 2406 2407 2408 2409 2410 2411 2412
                }
                else
                {
                    parameter = null;
                    expanded = false;
                }
            }

2413
            if (parameter is null)
2414
            {
2415 2416
                Debug.Assert(!expanded);
                return (null, null);
2417
            }
2418

2419 2420 2421 2422 2423 2424 2425
            var type = parameter.Type;
            if (expanded && parameter.Ordinal == n - 1 && parameter.Type.IsSZArray())
            {
                type = ((ArrayTypeSymbol)type.TypeSymbol).ElementType;
            }

            return (parameter, type);
2426 2427
        }

2428
        private MethodSymbol InferMethodTypeArguments(BoundCall node, MethodSymbol method, ImmutableArray<BoundExpression> arguments)
2429
        {
2430 2431 2432 2433 2434 2435 2436 2437 2438
            Debug.Assert(method.IsGenericMethod);
            // PROTOTYPE(NullableReferenceTypes): OverloadResolution.IsMemberApplicableInNormalForm and
            // IsMemberApplicableInExpandedForm use the least overridden method. We need to do the same here.
            var definition = method.ConstructedFrom;
            var refKinds = ArrayBuilder<RefKind>.GetInstance();
            if (node.ArgumentRefKindsOpt != null)
            {
                refKinds.AddRange(node.ArgumentRefKindsOpt);
            }
2439 2440
            // PROTOTYPE(NullableReferenceTypes): Do we really need OverloadResolution.GetEffectiveParameterTypes?
            // Aren't we doing roughly the same calculations in GetCorrespondingParameter?
2441 2442
            OverloadResolution.GetEffectiveParameterTypes(
                definition,
2443
                arguments.Length,
2444 2445
                node.ArgsToParamsOpt,
                refKinds,
C
Charles Stoner 已提交
2446
                isMethodGroupConversion: false,
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
                // PROTOTYPE(NullableReferenceTypes): `allowRefOmittedArguments` should be
                // false for constructors and several other cases (see Binder use). Should we
                // capture the original value in the BoundCall?
                allowRefOmittedArguments: true,
                binder: _binder,
                expanded: node.Expanded,
                parameterTypes: out ImmutableArray<TypeSymbolWithAnnotations> parameterTypes,
                parameterRefKinds: out ImmutableArray<RefKind> parameterRefKinds);
            refKinds.Free();
            HashSet<DiagnosticInfo> useSiteDiagnostics = null;
            var result = MethodTypeInferrer.Infer(
2458 2459
                _binder,
                _conversions,
2460 2461 2462 2463 2464
                definition.TypeParameters,
                definition.ContainingType,
                parameterTypes,
                parameterRefKinds,
                arguments,
2465
                ref useSiteDiagnostics);
2466 2467
            if (result.Success)
            {
2468
                // PROTOTYPE(NullableReferenceTypes): Check constraints
2469 2470 2471 2472
                return definition.Construct(result.InferredTypeArguments);
            }
            return method;
        }
2473

2474
        private ImmutableArray<BoundExpression> GetArgumentsForMethodTypeInference(ImmutableArray<BoundExpression> arguments, ImmutableArray<TypeSymbolWithAnnotations> argumentResults)
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
        {
            // PROTOTYPE(NullableReferenceTypes): MethodTypeInferrer.Infer relies
            // on the BoundExpressions for tuple element types and method groups.
            // By using a generic BoundValuePlaceholder, we're losing inference in those cases.
            // PROTOTYPE(NullableReferenceTypes): Inference should be based on
            // unconverted arguments. Consider cases such as `default`, lambdas, tuples.
            int n = arguments.Length;
            var builder = ArrayBuilder<BoundExpression>.GetInstance(n);
            for (int i = 0; i < n; i++)
            {
                builder.Add(getArgumentForMethodTypeInference(arguments[i], argumentResults[i]));
            }
            return builder.ToImmutableAndFree();

2489
            BoundExpression getArgumentForMethodTypeInference(BoundExpression argument, TypeSymbolWithAnnotations argumentType)
2490
            {
2491 2492 2493 2494 2495 2496 2497
                if (argument.Kind == BoundKind.Lambda)
                {
                    // MethodTypeInferrer must infer nullability for lambdas based on the nullability
                    // from flow analysis rather than the declared nullability. To allow that, we need
                    // to re-bind lambdas in MethodTypeInferrer.
                    return GetUnboundLambda((BoundLambda)argument, GetVariableState());
                }
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
                if (argumentType is null)
                {
                    return argument;
                }
                if (argument is BoundLocal local && local.DeclarationKind == BoundLocalDeclarationKind.WithInferredType)
                {
                    // 'out var' doesn't contribute to inference
                    return new BoundValuePlaceholder(argument.Syntax, isNullable: null, type: null);
                }
                return new BoundValuePlaceholder(argument.Syntax, argumentType.IsNullable, argumentType.TypeSymbol);
2508 2509
            }
        }
2510

2511 2512 2513 2514 2515 2516 2517
        private void ReplayReadsAndWrites(LocalFunctionSymbol localFunc,
                                  SyntaxNode syntax,
                                  bool writes)
        {
            // PROTOTYPE(NullableReferenceTypes): Support field initializers in local functions.
        }

2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
        /// <summary>
        /// Returns the expression without the top-most conversion plus the conversion.
        /// If the expression is not a conversion, returns the original expression plus
        /// the Identity conversion. If `includeExplicitConversions` is true, implicit and
        /// explicit conversions are considered. If `includeExplicitConversions` is false
        /// only implicit conversions are considered and if the expression is an explicit
        /// conversion, the expression is returned as is, with the Identity conversion.
        /// (Currently, the only visit method that passes `includeExplicitConversions: true`
        /// is VisitConversion. All other callers are handling implicit conversions only.)
        /// </summary>
        private static (BoundExpression Expression, Conversion Conversion) RemoveConversion(BoundExpression expr, bool includeExplicitConversions)
2529
        {
2530
            ConversionGroup group = null;
2531 2532 2533 2534 2535 2536 2537
            while (true)
            {
                if (expr.Kind != BoundKind.Conversion)
                {
                    break;
                }
                var conversion = (BoundConversion)expr;
2538
                if (group != conversion.ConversionGroupOpt && group != null)
2539
                {
2540
                    // E.g.: (C)(B)a
2541 2542
                    break;
                }
2543 2544 2545 2546 2547 2548
                group = conversion.ConversionGroupOpt;
                Debug.Assert(group != null || !conversion.ExplicitCastInCode); // Explicit conversions should include a group.
                if (!includeExplicitConversions && group?.IsExplicitConversion == true)
                {
                    return (expr, Conversion.Identity);
                }
2549
                expr = conversion.Operand;
2550 2551 2552 2553 2554 2555 2556 2557 2558
                if (group == null)
                {
                    // Ungrouped conversion should not be followed by another ungrouped
                    // conversion. Otherwise, the conversions should have been grouped.
                    Debug.Assert(expr.Kind != BoundKind.Conversion ||
                        ((BoundConversion)expr).ConversionGroupOpt != null ||
                        ((BoundConversion)expr).ConversionKind == ConversionKind.NoConversion);
                    return (expr, conversion.Conversion);
                }
2559
            }
2560
            return (expr, group?.Conversion ?? Conversion.Identity);
2561
        }
2562

2563 2564
        // See Binder.BindNullCoalescingOperator for initial binding.
        private Conversion GenerateConversionForConditionalOperator(BoundExpression sourceExpression, TypeSymbol sourceType, TypeSymbol destinationType, bool reportMismatch)
2565
        {
2566
            var conversion = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType);
2567 2568
            bool canConvertNestedNullability = conversion.Exists;
            if (!canConvertNestedNullability && reportMismatch)
2569
            {
2570
                ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullabilityMismatchInAssignment, sourceExpression.Syntax, GetTypeAsDiagnosticArgument(sourceType), destinationType);
2571
            }
2572 2573
            return conversion;
        }
2574

2575
        private static Conversion GenerateConversion(Conversions conversions, BoundExpression sourceExpression, TypeSymbol sourceType, TypeSymbol destinationType, bool fromExplicitCast = false)
2576
        {
2577
            HashSet<DiagnosticInfo> useSiteDiagnostics = null;
2578 2579 2580 2581 2582 2583 2584 2585
            return UseExpressionForConversion(sourceExpression) ?
                (fromExplicitCast ?
                    conversions.ClassifyConversionFromExpression(sourceExpression, destinationType, ref useSiteDiagnostics, forCast: true) :
                    conversions.ClassifyImplicitConversionFromExpression(sourceExpression, destinationType, ref useSiteDiagnostics)) :
                (fromExplicitCast ?
                    conversions.ClassifyConversionFromType(sourceType, destinationType, ref useSiteDiagnostics, forCast: true) :
                    conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref useSiteDiagnostics));
        }
2586

2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
        /// <summary>
        /// Returns true if the expression should be used as the source when calculating
        /// a conversion from this expression, rather than using the type (with nullability)
        /// calculated by visiting this expression. Typically, that means expressions that
        /// do not have an explicit type but there are several other cases as well.
        /// (See expressions handled in ClassifyImplicitBuiltInConversionFromExpression.)
        /// </summary>
        private static bool UseExpressionForConversion(BoundExpression value)
        {
            if (value is null)
            {
                return false;
            }
            if (value.Type is null || value.Type.IsDynamic() || value.ConstantValue != null)
            {
                return true;
            }
            switch (value.Kind)
            {
                case BoundKind.InterpolatedString:
                    return true;
                default:
                    return false;
            }
2611 2612
        }

2613 2614 2615
        /// <summary>
        /// Adjust declared type based on inferred nullability at the point of reference.
        /// </summary>
2616
        private TypeSymbolWithAnnotations GetAdjustedResult(TypeSymbolWithAnnotations type, int slot)
2617
        {
2618
            if (slot > 0 && slot < this.State.Capacity)
2619 2620 2621 2622
            {
                bool? isNullable = !this.State[slot];
                if (isNullable != type.IsNullable)
                {
2623
                    return TypeSymbolWithAnnotations.Create(type.TypeSymbol, isNullable);
2624 2625
                }
            }
2626
            return type;
2627
        }
2628

2629 2630
        private Symbol AsMemberOfResultType(Symbol symbol)
        {
2631
            var containingType = _resultType?.TypeSymbol as NamedTypeSymbol;
2632
            if ((object)containingType == null || containingType.IsErrorType())
2633
            {
2634 2635
                return symbol;
            }
2636 2637 2638 2639 2640 2641
            return AsMemberOfType(containingType, symbol);
        }

        private static Symbol AsMemberOfType(NamedTypeSymbol containingType, Symbol symbol)
        {
            if (symbol is null)
2642
            {
2643 2644 2645 2646 2647 2648 2649 2650 2651
                return null;
            }
            if (symbol.Kind == SymbolKind.Method)
            {
                if (((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction)
                {
                    // PROTOTYPE(NullableReferenceTypes): Handle type substitution for local functions.
                    return symbol;
                }
2652
            }
2653 2654 2655 2656 2657 2658
            var symbolDef = symbol.OriginalDefinition;
            var symbolDefContainer = symbolDef.ContainingType;
            while (true)
            {
                if (containingType.OriginalDefinition.Equals(symbolDefContainer, TypeCompareKind.ConsiderEverything))
                {
2659 2660 2661 2662
                    if (symbolDefContainer.IsTupleType)
                    {
                        return AsMemberOfTupleType((TupleTypeSymbol)containingType, symbol);
                    }
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
                    return symbolDef.SymbolAsMember(containingType);
                }
                containingType = containingType.BaseTypeNoUseSiteDiagnostics;
                if ((object)containingType == null)
                {
                    break;
                }
            }
            // PROTOTYPE(NullableReferenceTypes): Handle other cases such as interfaces.
            Debug.Assert(symbolDefContainer.IsInterface);
            return symbol;
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
        private static Symbol AsMemberOfTupleType(TupleTypeSymbol tupleType, Symbol symbol)
        {
            if (symbol.ContainingType.Equals(tupleType, TypeCompareKind.CompareNullableModifiersForReferenceTypes))
            {
                return symbol;
            }
            switch (symbol.Kind)
            {
                case SymbolKind.Field:
                    {
                        var index = ((FieldSymbol)symbol).TupleElementIndex;
                        if (index >= 0)
                        {
                            return tupleType.TupleElements[index];
                        }
                        return tupleType.GetTupleMemberSymbolForUnderlyingMember(((TupleFieldSymbol)symbol).UnderlyingField);
                    }
                case SymbolKind.Property:
                    return tupleType.GetTupleMemberSymbolForUnderlyingMember(((TuplePropertySymbol)symbol).UnderlyingProperty);
                case SymbolKind.Event:
                    return tupleType.GetTupleMemberSymbolForUnderlyingMember(((TupleEventSymbol)symbol).UnderlyingEvent);
                default:
                    throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
            }
        }

2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
        public override BoundNode VisitConversion(BoundConversion node)
        {
            if (node.ConversionKind == ConversionKind.MethodGroup
                && node.SymbolOpt?.MethodKind == MethodKind.LocalFunction)
            {
                var localFunc = (LocalFunctionSymbol)node.SymbolOpt.OriginalDefinition;
                var syntax = node.Syntax;
                ReplayReadsAndWrites(localFunc, syntax, writes: false);
            }

2712 2713 2714
            (BoundExpression operand, Conversion conversion) = RemoveConversion(node, includeExplicitConversions: true);
            Debug.Assert(operand != null);

2715
            Visit(operand);
2716
            TypeSymbolWithAnnotations operandType = _resultType;
2717 2718 2719
            TypeSymbolWithAnnotations explicitType = node.ConversionGroupOpt?.ExplicitType;
            bool fromExplicitCast = (object)explicitType != null;
            TypeSymbolWithAnnotations resultType = ApplyConversion(node, operand, conversion, explicitType?.TypeSymbol ?? node.Type, operandType, checkConversion: !fromExplicitCast, fromExplicitCast: fromExplicitCast, out bool _);
2720

2721
            if (fromExplicitCast && explicitType.IsNullable == false)
2722
            {
2723 2724 2725
                TypeSymbol targetType = explicitType.TypeSymbol;
                bool reportNullable = false;
                if (targetType.IsReferenceType && IsUnconstrainedTypeParameter(resultType?.TypeSymbol))
2726
                {
2727
                    reportNullable = true;
2728
                }
2729 2730
                else if ((targetType.IsReferenceType || IsUnconstrainedTypeParameter(targetType)) &&
                    resultType?.IsNullable == true)
C
Charles Stoner 已提交
2731
                {
2732
                    reportNullable = true;
2733
                }
2734
                if (reportNullable)
2735
                {
2736
                    ReportWWarning(node.Syntax);
C
Charles Stoner 已提交
2737
                }
2738
            }
2739

2740
            _resultType = resultType;
2741
            return null;
2742 2743
        }

2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
        public override BoundNode VisitTupleLiteral(BoundTupleLiteral node)
        {
            VisitTupleExpression(node);
            return null;
        }

        public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node)
        {
            VisitTupleExpression(node);
            return null;
        }

        private void VisitTupleExpression(BoundTupleExpression node)
        {
            var arguments = node.Arguments;
2759
            ImmutableArray<TypeSymbolWithAnnotations> elementTypes = arguments.SelectAsArray((a, w) => w.VisitRvalueWithResult(a), this);
2760
            var tupleOpt = (TupleTypeSymbol)node.Type;
2761
            _resultType = (tupleOpt is null) ?
2762 2763
                null :
                TypeSymbolWithAnnotations.Create(tupleOpt.WithElementTypes(elementTypes));
2764 2765
        }

C
Charles Stoner 已提交
2766 2767 2768 2769 2770 2771 2772
        public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node)
        {
            base.VisitTupleBinaryOperator(node);
            SetResult(node);
            return null;
        }

2773 2774
        private void ReportNullabilityMismatchWithTargetDelegate(SyntaxNode syntax, NamedTypeSymbol delegateType, MethodSymbol method)
        {
2775 2776
            Debug.Assert((object)method != null);
            Debug.Assert(method.MethodKind != MethodKind.LambdaMethod);
2777

2778 2779
            MethodSymbol invoke = delegateType?.DelegateInvokeMethod;
            if (invoke is null)
2780 2781 2782 2783
            {
                return;
            }

2784
            if (IsNullabilityMismatch(method.ReturnType, invoke.ReturnType, requireIdentity: false))
2785 2786
            {
                ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, syntax,
2787
                    new FormattedSymbol(method, SymbolDisplayFormat.MinimallyQualifiedFormat),
2788 2789 2790 2791 2792 2793
                    delegateType);
            }

            int count = Math.Min(invoke.ParameterCount, method.ParameterCount);
            for (int i = 0; i < count; i++)
            {
2794 2795 2796
                var invokeParameter = invoke.Parameters[i];
                var methodParameter = method.Parameters[i];
                if (IsNullabilityMismatch(invokeParameter.Type, methodParameter.Type, requireIdentity: invokeParameter.RefKind != RefKind.None))
2797 2798
                {
                    ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, syntax,
2799
                        new FormattedSymbol(methodParameter, SymbolDisplayFormat.ShortFormat),
2800
                        new FormattedSymbol(method, SymbolDisplayFormat.MinimallyQualifiedFormat),
2801 2802 2803 2804 2805
                        delegateType);
                }
            }
        }

2806 2807 2808 2809 2810 2811 2812 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 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
        private void ReportNullabilityMismatchWithTargetDelegate(SyntaxNode syntax, NamedTypeSymbol delegateType, UnboundLambda unboundLambda)
        {
            if (!unboundLambda.HasExplicitlyTypedParameterList)
            {
                return;
            }

            MethodSymbol invoke = delegateType?.DelegateInvokeMethod;
            if (invoke is null)
            {
                return;
            }

            int count = Math.Min(invoke.ParameterCount, unboundLambda.ParameterCount);
            for (int i = 0; i < count; i++)
            {
                var invokeParameter = invoke.Parameters[i];
                // Parameter nullability is expected to match exactly. This corresponds to the behavior of initial binding.
                //    Action<string> x = (object o) => { }; // error CS1661: Cannot convert lambda expression to delegate type 'Action<string>' because the parameter types do not match the delegate parameter types
                //    Action<object> y = (object? o) => { }; // warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'Action<object>'.
                // PROTOTYPE(NullableReferenceTypes): Consider relaxing and allow implicit conversions of nullability.
                // (Compare with method group conversions which pass `requireIdentity: false`.)
                if (IsNullabilityMismatch(invokeParameter.Type, unboundLambda.ParameterType(i), requireIdentity: true))
                {
                    // PROTOTYPE(NullableReferenceTypes): Consider using location of specific lambda parameter.
                    ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, syntax,
                        unboundLambda.ParameterName(i),
                        unboundLambda.MessageID.Localize(),
                        delegateType);
                }
            }
        }

        private bool IsNullabilityMismatch(TypeSymbolWithAnnotations source, TypeSymbolWithAnnotations destination, bool requireIdentity)
        {
            if (!HasTopLevelNullabilityConversion(source, destination, requireIdentity))
            {
                return true;
            }
            if (requireIdentity)
            {
                return IsNullabilityMismatch(source, destination);
            }
            var sourceType = source.TypeSymbol;
            var destinationType = destination.TypeSymbol;
            HashSet<DiagnosticInfo> useSiteDiagnostics = null;
            return !_conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref useSiteDiagnostics).Exists;
        }

        private static bool HasTopLevelNullabilityConversion(TypeSymbolWithAnnotations source, TypeSymbolWithAnnotations destination, bool requireIdentity)
        {
            return requireIdentity ?
                ConversionsBase.HasTopLevelNullabilityIdentityConversion(source, destination) :
                ConversionsBase.HasTopLevelNullabilityImplicitConversion(source, destination);
        }

2862 2863 2864 2865
        /// <summary>
        /// Re-calculate and apply the conversion to the type of the operand and return the resulting type.
        /// </summary>
        private TypeSymbolWithAnnotations ApplyConversion(BoundExpression operand, Conversion conversion, TypeSymbol targetType, TypeSymbolWithAnnotations operandType)
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
            Debug.Assert(operand != null);
            return ApplyConversion(operand, operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: false, out _);
        }

        /// <summary>
        /// Apply the conversion to the type of the operand and return the resulting type. (If the
        /// operand does not have an explicit type, the operand expression is used for the type.)
        /// If `checkConversion` is set, the incoming conversion is assumed to be from binding and will be
        /// re-calculated, this time considering nullability. (Note that the conversion calculation considers
        /// nested nullability only. The caller is responsible for checking the top-level nullability of
        /// the type returned by this method.) `canConvertNestedNullability` is set if the conversion
        /// considering nested nullability succeeded. `node` is used only for the location of diagnostics.
        /// </summary>
        private TypeSymbolWithAnnotations ApplyConversion(
            BoundNode node,
            BoundExpression operandOpt,
            Conversion conversion,
            TypeSymbol targetType,
            TypeSymbolWithAnnotations operandType,
            bool checkConversion,
            bool fromExplicitCast,
            out bool canConvertNestedNullability)
        {
            Debug.Assert(node != null);
            Debug.Assert(operandOpt != null || (object)operandType != null);
            Debug.Assert((object)targetType != null);

2894
            bool? isNullableIfReferenceType = null;
2895
            canConvertNestedNullability = true;
2896 2897

            switch (conversion.Kind)
2898
            {
2899
                case ConversionKind.MethodGroup:
2900 2901
                    if (!fromExplicitCast)
                    {
2902
                        ReportNullabilityMismatchWithTargetDelegate(node.Syntax, targetType.GetDelegateType(), conversion.Method);
2903 2904 2905 2906
                    }
                    isNullableIfReferenceType = false;
                    break;

2907
                case ConversionKind.AnonymousFunction:
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
                    if (operandOpt.Kind == BoundKind.Lambda)
                    {
                        var lambda = (BoundLambda)operandOpt;
                        var delegateType = targetType.GetDelegateType();
                        var methodSignatureOpt = lambda.UnboundLambda.HasExplicitlyTypedParameterList ? null : delegateType?.DelegateInvokeMethod;
                        var variableState = GetVariableState();
                        Analyze(compilation, lambda, Diagnostics, delegateInvokeMethod: delegateType?.DelegateInvokeMethod, returnTypes: null, initialState: variableState);
                        var unboundLambda = GetUnboundLambda(lambda, variableState);
                        var boundLambda = unboundLambda.Bind(delegateType);
                        if (!fromExplicitCast)
                        {
                            ReportNullabilityMismatchWithTargetDelegate(node.Syntax, delegateType, unboundLambda);
                        }
                        return TypeSymbolWithAnnotations.Create(targetType, isNullableIfReferenceType: false);
                    }
                    break;

2925
                case ConversionKind.InterpolatedString:
2926
                    isNullableIfReferenceType = false;
2927
                    break;
2928

2929 2930
                case ConversionKind.ExplicitUserDefined:
                case ConversionKind.ImplicitUserDefined:
2931
                    // cf. Binder.CreateUserDefinedConversion
2932
                    {
2933
                        if (!conversion.IsValid)
2934 2935 2936
                        {
                            break;
                        }
2937 2938

                        // operand -> conversion "from" type
2939
                        // May be distinct from method parameter type for Nullable<T>.
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
                        operandType = ApplyConversion(
                            node,
                            operandOpt,
                            conversion.UserDefinedFromConversion,
                            conversion.BestUserDefinedConversionAnalysis.FromType,
                            operandType,
                            checkConversion: false,
                            fromExplicitCast: false,
                            out _);

                        // PROTOTYPE(NullableReferenceTypes): Update method based on operandType
                        // (see StaticNullChecking_FlowAnalysis.Conversions_07).
                        var methodOpt = conversion.Method;
                        Debug.Assert((object)methodOpt != null);
                        Debug.Assert(methodOpt.ParameterCount == 1);
                        var parameter = methodOpt.Parameters[0];

                        // conversion "from" type -> method parameter type
                        operandType = ClassifyAndApplyConversion(node, parameter.Type.TypeSymbol, operandType);
                        ReportNullReferenceArgumentIfNecessary(operandOpt, operandType, parameter, parameter.Type);

                        // method parameter type -> method return type
                        operandType = methodOpt.ReturnType;

                        // method return type -> conversion "to" type
2965
                        // May be distinct from method return type for Nullable<T>.
2966 2967 2968 2969 2970
                        operandType = ClassifyAndApplyConversion(node, conversion.BestUserDefinedConversionAnalysis.ToType, operandType);

                        // conversion "to" type -> final type
                        // PROTOTYPE(NullableReferenceTypes): If the original conversion was
                        // explicit, this conversion should not report nested nullability mismatches.
2971
                        // (see NullableReferenceTypesTests.ExplicitCast_UserDefined_02).
2972 2973
                        operandType = ClassifyAndApplyConversion(node, targetType, operandType);
                        return operandType;
2974
                    }
2975

2976 2977
                case ConversionKind.ExplicitDynamic:
                case ConversionKind.ImplicitDynamic:
2978 2979 2980 2981
                    isNullableIfReferenceType = operandType?.IsNullable;
                    break;

                case ConversionKind.Unboxing:
2982 2983
                case ConversionKind.ImplicitThrow:
                    break;
2984

2985 2986 2987 2988 2989
                case ConversionKind.Boxing:
                    if (operandType?.IsValueType == true)
                    {
                        // PROTOTYPE(NullableReferenceTypes): Should we worry about a pathological case of boxing nullable value known to be not null?
                        //       For example, new int?(0)
2990
                        isNullableIfReferenceType = operandType.IsNullableType();
2991
                    }
2992 2993 2994 2995
                    else if (IsUnconstrainedTypeParameter(operandType?.TypeSymbol))
                    {
                        isNullableIfReferenceType = true;
                    }
2996 2997
                    else
                    {
2998 2999 3000 3001
                        Debug.Assert(operandType?.IsReferenceType != true ||
                            operandType.SpecialType == SpecialType.System_ValueType ||
                            operandType.TypeKind == TypeKind.Interface ||
                            operandType.TypeKind == TypeKind.Dynamic);
3002 3003
                    }
                    break;
3004

3005
                case ConversionKind.NoConversion:
3006
                case ConversionKind.DefaultOrNullLiteral:
3007 3008 3009 3010
                    checkConversion = false;
                    goto case ConversionKind.Identity;

                case ConversionKind.Identity:
3011 3012
                case ConversionKind.ImplicitReference:
                case ConversionKind.ExplicitReference:
3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027
                    if (operandType is null && operandOpt.IsLiteralNullOrDefault())
                    {
                        isNullableIfReferenceType = true;
                    }
                    else
                    {
                        // Inherit state from the operand.
                        if (checkConversion)
                        {
                            // PROTOTYPE(NullableReferenceTypes): Assert conversion is similar to original.
                            conversion = GenerateConversion(_conversions, operandOpt, operandType?.TypeSymbol, targetType, fromExplicitCast);
                            canConvertNestedNullability = conversion.Exists;
                        }
                        isNullableIfReferenceType = operandType?.IsNullable;
                    }
3028
                    break;
3029

3030 3031 3032 3033
                case ConversionKind.Deconstruction:
                    // Can reach here, with an error type, when the
                    // Deconstruct method is missing or inaccessible.
                    break;
3034

3035 3036 3037
                case ConversionKind.ExplicitEnumeration:
                    // Can reach here, with an error type.
                    break;
3038

3039
                default:
3040
                    Debug.Assert(targetType.IsReferenceType != true);
3041
                    break;
3042
            }
3043

3044
            return TypeSymbolWithAnnotations.Create(targetType, isNullableIfReferenceType);
3045 3046
        }

3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059
        private TypeSymbolWithAnnotations ClassifyAndApplyConversion(BoundNode node, TypeSymbol targetType, TypeSymbolWithAnnotations operandType)
        {
            HashSet<DiagnosticInfo> useSiteDiagnostics = null;
            var conversion = _conversions.ClassifyStandardConversion(null, operandType.TypeSymbol, targetType, ref useSiteDiagnostics);
            if (!conversion.Exists)
            {
                // PROTOTYPE(NullableReferenceTypes): Not necessarily an assignment
                // (see StaticNullChecking_FlowAnalysis.Conversions_07).
                ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullabilityMismatchInAssignment, node.Syntax, operandType.TypeSymbol, targetType);
            }
            return ApplyConversion(node, operandOpt: null, conversion, targetType, operandType, checkConversion: false, fromExplicitCast: false, out _);
        }

3060 3061 3062 3063 3064 3065 3066 3067 3068
        public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
        {
            if (node.MethodOpt?.MethodKind == MethodKind.LocalFunction)
            {
                var syntax = node.Syntax;
                var localFunc = (LocalFunctionSymbol)node.MethodOpt.OriginalDefinition;
                ReplayReadsAndWrites(localFunc, syntax, writes: false);
            }

3069 3070 3071
            base.VisitDelegateCreationExpression(node);
            SetResult(node);
            return null;
3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084
        }

        public override BoundNode VisitMethodGroup(BoundMethodGroup node)
        {
            Debug.Assert(!IsConditionalState);

            BoundExpression receiverOpt = node.ReceiverOpt;
            if (receiverOpt != null)
            {
                VisitRvalue(receiverOpt);
                CheckPossibleNullReceiver(receiverOpt);
            }

3085
            //if (this.State.Reachable) // PROTOTYPE(NullableReferenceTypes): Consider reachability?
3086
            {
3087
                _resultType = null;
3088 3089 3090 3091 3092 3093 3094
            }

            return null;
        }

        public override BoundNode VisitLambda(BoundLambda node)
        {
3095 3096
            SetResult(node);
            return null;
3097 3098 3099 3100
        }

        public override BoundNode VisitUnboundLambda(UnboundLambda node)
        {
3101 3102 3103 3104
            // The presence of this node suggests an error was detected in an earlier phase.
            // Analyze the body to report any additional warnings.
            var lambda = node.BindForErrorRecovery();
            Analyze(compilation, lambda, Diagnostics, delegateInvokeMethod: null, returnTypes: null, initialState: GetVariableState());
3105
            SetResult(node);
3106 3107 3108
            return null;
        }

3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125
        public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
        {
            var body = node.Body;
            if (body != null)
            {
                Analyze(
                    compilation,
                    node.Symbol,
                    body,
                    Diagnostics,
                    useMethodSignatureReturnType: false,
                    useMethodSignatureParameterTypes: false,
                    methodSignatureOpt: null,
                    returnTypes: null,
                    initialState: GetVariableState(),
                    callbackOpt: _callbackOpt);
            }
3126
            _resultType = _invalidType;
3127 3128 3129
            return null;
        }

3130 3131
        public override BoundNode VisitThisReference(BoundThisReference node)
        {
3132
            VisitThisOrBaseReference(node);
3133 3134 3135
            return null;
        }

3136 3137
        private void VisitThisOrBaseReference(BoundExpression node)
        {
3138
            _resultType = TypeSymbolWithAnnotations.Create(node.Type);
3139 3140
        }

3141 3142
        public override BoundNode VisitParameter(BoundParameter node)
        {
3143 3144 3145 3146
            var parameter = node.ParameterSymbol;
            int slot = GetOrCreateSlot(parameter);
            var type = GetDeclaredParameterResult(parameter);
            _resultType = GetAdjustedResult(type, slot);
3147 3148 3149 3150 3151 3152 3153
            return null;
        }

        public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node)
        {
            Debug.Assert(!IsConditionalState);

3154 3155
            var left = node.Left;
            VisitLvalue(left);
3156
            TypeSymbolWithAnnotations leftType = _resultType;
3157

3158 3159
            (BoundExpression right, Conversion conversion) = RemoveConversion(node.Right, includeExplicitConversions: false);
            VisitRvalue(right);
3160
            TypeSymbolWithAnnotations rightResult = _resultType;
3161

3162
            if (left.Kind == BoundKind.EventAccess && ((BoundEventAccess)left).EventSymbol.IsWindowsRuntimeEvent)
3163 3164 3165 3166 3167 3168 3169
            {
                // Event assignment is a call to an Add method. (Note that assignment
                // of non-field-like events uses BoundEventAssignmentOperator
                // rather than BoundAssignmentOperator.)
                SetResult(node);
            }
            else
3170
            {
3171
                TypeSymbolWithAnnotations rightType = ApplyConversion(right, right, conversion, leftType.TypeSymbol, rightResult, checkConversion: true, fromExplicitCast: false, out bool canConvertNestedNullability);
3172 3173 3174 3175
                // Need to report all warnings that apply since the warnings can be suppressed individually.
                ReportNullReferenceAssignmentIfNecessary(right, leftType, rightType, UseLegacyWarnings(left));
                if (!canConvertNestedNullability)
                {
3176
                    ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullabilityMismatchInAssignment, right.Syntax, GetTypeAsDiagnosticArgument(rightResult?.TypeSymbol), leftType.TypeSymbol);
3177
                }
3178
                TrackNullableStateForAssignment(right, leftType, MakeSlot(left), rightType, MakeSlot(right));
3179
                // PROTOTYPE(NullableReferenceTypes): Check node.Type.IsErrorType() instead?
3180
                _resultType = node.HasErrors ? TypeSymbolWithAnnotations.Create(node.Type) : rightType;
3181 3182 3183 3184 3185
            }

            return null;
        }

3186 3187 3188 3189 3190 3191 3192 3193 3194
        private static bool UseLegacyWarnings(BoundExpression expr)
        {
            switch (expr.Kind)
            {
                case BoundKind.Local:
                case BoundKind.Parameter:
                    // PROTOTYPE(NullableReferenceTypes): Warnings when assigning to `ref`
                    // or `out` parameters should be regular warnings. Warnings assigning to
                    // other parameters should be W warnings.
3195
                    // PROTOTYPE(NullableReferenceTypes): Should parameters be non-W warnings?
3196 3197 3198 3199 3200 3201
                    return true;
                default:
                    return false;
            }
        }

3202 3203
        public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node)
        {
3204
            // PROTOTYPE(NullableReferenceTypes): Assign each of the deconstructed values.
3205 3206 3207
            VisitLvalue(node.Left);
            // PROTOTYPE(NullableReferenceTypes): Handle deconstruction conversion node.Right.
            VisitRvalue(node.Right.Operand);
3208
            SetResult(node);
3209 3210 3211 3212 3213 3214 3215
            return null;
        }

        public override BoundNode VisitIncrementOperator(BoundIncrementOperator node)
        {
            Debug.Assert(!IsConditionalState);

3216
            VisitRvalue(node.Operand);
3217
            var operandType = _resultType;
3218 3219
            bool setResult = false;

3220 3221
            if (this.State.Reachable)
            {
3222
                // PROTOTYPE(NullableReferenceTypes): Update increment method based on operand type.
3223 3224 3225
                MethodSymbol incrementOperator = (node.OperatorKind.IsUserDefined() && (object)node.MethodOpt != null && node.MethodOpt.ParameterCount == 1) ? node.MethodOpt : null;
                TypeSymbol targetTypeOfOperandConversion;

3226
                // PROTOTYPE(NullableReferenceTypes): Update conversion method based on operand type.
3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
                if (node.OperandConversion.IsUserDefined && (object)node.OperandConversion.Method != null && node.OperandConversion.Method.ParameterCount == 1)
                {
                    targetTypeOfOperandConversion = node.OperandConversion.Method.ReturnType.TypeSymbol;
                }
                else if ((object)incrementOperator != null)
                {
                    targetTypeOfOperandConversion = incrementOperator.Parameters[0].Type.TypeSymbol;
                }
                else
                {
                    // Either a built-in increment, or an error case.
                    targetTypeOfOperandConversion = null;
                }

3241
                TypeSymbolWithAnnotations resultOfOperandConversionType;
3242 3243 3244 3245

                if ((object)targetTypeOfOperandConversion != null)
                {
                    // PROTOTYPE(NullableReferenceTypes): Should something special be done for targetTypeOfOperandConversion for lifted case?
3246
                    resultOfOperandConversionType = ApplyConversion(node.Operand, node.OperandConversion, targetTypeOfOperandConversion, operandType);
3247 3248 3249
                }
                else
                {
3250
                    resultOfOperandConversionType = operandType;
3251 3252
                }

3253
                TypeSymbolWithAnnotations resultOfIncrementType;
3254 3255
                if ((object)incrementOperator == null)
                {
3256
                    resultOfIncrementType = resultOfOperandConversionType;
3257
                }
3258
                else
3259
                {
3260
                    ReportArgumentWarnings(node.Operand, resultOfOperandConversionType, incrementOperator.Parameters[0]);
3261

3262
                    resultOfIncrementType = incrementOperator.ReturnType;
3263 3264
                }

3265
                resultOfIncrementType = ApplyConversion(node, node.ResultConversion, node.Type, resultOfIncrementType);
3266

3267 3268
                // PROTOTYPE(NullableReferenceTypes): Check node.Type.IsErrorType() instead?
                if (!node.HasErrors)
3269
                {
3270
                    var op = node.OperatorKind.Operator();
3271
                    _resultType = (op == UnaryOperatorKind.PrefixIncrement || op == UnaryOperatorKind.PrefixDecrement) ? resultOfIncrementType : operandType;
3272 3273
                    setResult = true;

3274 3275
                    ReportAssignmentWarnings(node, operandType, valueType: resultOfIncrementType, useLegacyWarnings: false);
                    TrackNullableStateForAssignment(node, operandType, MakeSlot(node.Operand), valueType: resultOfIncrementType);
3276 3277
                }
            }
3278 3279

            if (!setResult)
3280
            {
3281
                this.SetResult(node);
3282 3283 3284 3285 3286 3287 3288
            }

            return null;
        }

        public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node)
        {
3289
            VisitLvalue(node.Left); // PROTOTYPE(NullableReferenceTypes): Method should be called VisitValue rather than VisitLvalue.
3290
            TypeSymbolWithAnnotations leftType = _resultType;
3291

3292
            TypeSymbolWithAnnotations resultType;
3293 3294
            Debug.Assert(!IsConditionalState);

3295
            //if (this.State.Reachable) // PROTOTYPE(NullableReferenceTypes): Consider reachability?
3296
            {
3297
                TypeSymbolWithAnnotations leftOnRightType = GetAdjustedResult(leftType, MakeSlot(node.Left));
3298

3299
                // PROTOTYPE(NullableReferenceTypes): Update operator based on inferred argument types.
3300 3301
                if ((object)node.Operator.LeftType != null)
                {
3302
                    // PROTOTYPE(NullableReferenceTypes): Ignoring top-level nullability of operator left parameter.
3303
                    leftOnRightType = ApplyConversion(node.Left, node.LeftConversion, node.Operator.LeftType, leftOnRightType);
3304 3305 3306
                }
                else
                {
3307
                    leftOnRightType = null;
3308 3309 3310
                }

                VisitRvalue(node.Right);
3311
                TypeSymbolWithAnnotations rightType = _resultType;
3312 3313 3314 3315

                if ((object)node.Operator.ReturnType != null)
                {
                    if (node.Operator.Kind.IsUserDefined() && (object)node.Operator.Method != null && node.Operator.Method.ParameterCount == 2)
3316
                    {
3317 3318
                        ReportArgumentWarnings(node.Left, leftOnRightType, node.Operator.Method.Parameters[0]);
                        ReportArgumentWarnings(node.Right, rightType, node.Operator.Method.Parameters[1]);
3319 3320
                    }

3321
                    resultType = InferResultNullability(node.Operator.Kind, node.Operator.Method, node.Operator.ReturnType, leftOnRightType, rightType);
3322

3323 3324
                    // PROTOTYPE(NullableReferenceTypes): Ignoring top-level nullability of operator.
                    resultType = ApplyConversion(node, node.FinalConversion, node.Type, resultType);
3325
                    ReportAssignmentWarnings(node, leftType, resultType, useLegacyWarnings: false);
3326 3327 3328
                }
                else
                {
3329
                    resultType = TypeSymbolWithAnnotations.Create(node.Type);
3330 3331
                }

3332 3333
                TrackNullableStateForAssignment(node, leftType, MakeSlot(node.Left), resultType);
                _resultType = resultType;
3334
            }
3335 3336 3337 3338 3339 3340
            //else
            //{
            //    VisitRvalue(node.Right);
            //    AfterRightHasBeenVisited(node);
            //    resultType = null;
            //}
3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352

            return null;
        }

        public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node)
        {
            var initializer = node.Expression;
            if (initializer.Kind == BoundKind.AddressOfOperator)
            {
                initializer = ((BoundAddressOfOperator)initializer).Operand;
            }

3353 3354
            this.VisitRvalue(initializer);
            SetResult(node);
3355 3356 3357 3358 3359
            return null;
        }

        public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node)
        {
3360
            SetResult(node);
3361 3362 3363
            return null;
        }

3364 3365 3366 3367 3368
        /// <summary>
        /// Report warning passing nullable argument to non-nullable parameter
        /// (e.g.: calling `void F(string s)` with `F(maybeNull)`).
        /// </summary>
        private bool ReportNullReferenceArgumentIfNecessary(BoundExpression argument, TypeSymbolWithAnnotations argumentType, ParameterSymbol parameter, TypeSymbolWithAnnotations paramType)
3369
        {
3370
            if (argumentType?.IsNullable == true)
3371
            {
3372
                if (paramType.IsReferenceType && paramType.IsNullable == false)
3373
                {
3374 3375 3376 3377 3378 3379 3380
                    if (!ReportNullAsNonNullableReferenceIfNecessary(argument))
                    {
                        ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullReferenceArgument, argument.Syntax,
                            new FormattedSymbol(parameter, SymbolDisplayFormat.ShortFormat),
                            new FormattedSymbol(parameter.ContainingSymbol, SymbolDisplayFormat.MinimallyQualifiedFormat));
                    }
                    return true;
3381 3382
                }
            }
3383 3384 3385 3386 3387 3388 3389 3390
            return false;
        }

        private void ReportArgumentWarnings(BoundExpression argument, TypeSymbolWithAnnotations argumentType, ParameterSymbol parameter)
        {
            var paramType = parameter.Type;

            ReportNullReferenceArgumentIfNecessary(argument, argumentType, parameter, paramType);
3391

3392
            if ((object)argumentType != null && IsNullabilityMismatch(paramType.TypeSymbol, argumentType.TypeSymbol))
3393
            {
3394
                ReportNullabilityMismatchInArgument(argument, argumentType.TypeSymbol, parameter, paramType.TypeSymbol);
3395 3396 3397
            }
        }

3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408
        /// <summary>
        /// Report warning passing argument where nested nullability does not match
        /// parameter (e.g.: calling `void F(object[] o)` with `F(new[] { maybeNull })`).
        /// </summary>
        private void ReportNullabilityMismatchInArgument(BoundExpression argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType)
        {
            ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullabilityMismatchInArgument, argument.Syntax, argumentType, parameterType,
                new FormattedSymbol(parameter, SymbolDisplayFormat.ShortFormat),
                new FormattedSymbol(parameter.ContainingSymbol, SymbolDisplayFormat.MinimallyQualifiedFormat));
        }

3409
        private TypeSymbolWithAnnotations GetDeclaredLocalResult(LocalSymbol local)
3410
        {
3411 3412 3413
            return _variableTypes.TryGetValue(local, out TypeSymbolWithAnnotations type) ?
                type :
                local.Type;
3414 3415
        }

3416
        private TypeSymbolWithAnnotations GetDeclaredParameterResult(ParameterSymbol parameter)
3417
        {
3418 3419 3420
            return _variableTypes.TryGetValue(parameter, out TypeSymbolWithAnnotations type) ?
                type :
                parameter.Type;
3421 3422
        }

3423
        public override BoundNode VisitBaseReference(BoundBaseReference node)
3424
        {
3425 3426
            VisitThisOrBaseReference(node);
            return null;
3427 3428 3429 3430
        }

        public override BoundNode VisitFieldAccess(BoundFieldAccess node)
        {
3431 3432
            VisitMemberAccess(node.ReceiverOpt, node.FieldSymbol, asLvalue: false);
            return null;
3433 3434 3435 3436
        }

        public override BoundNode VisitPropertyAccess(BoundPropertyAccess node)
        {
3437 3438
            VisitMemberAccess(node.ReceiverOpt, node.PropertySymbol, asLvalue: false);
            return null;
3439 3440 3441 3442
        }

        public override BoundNode VisitIndexerAccess(BoundIndexerAccess node)
        {
3443 3444 3445 3446
            var receiverOpt = node.ReceiverOpt;
            VisitRvalue(receiverOpt);
            CheckPossibleNullReceiver(receiverOpt);

3447 3448
            // PROTOTYPE(NullableReferenceTypes): Update indexer based on inferred receiver type.
            VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, node.Indexer, node.ArgsToParamsOpt, node.Expanded);
3449

3450
            _resultType = node.Indexer.Type;
3451
            return null;
3452 3453 3454 3455
        }

        public override BoundNode VisitEventAccess(BoundEventAccess node)
        {
3456 3457 3458
            VisitMemberAccess(node.ReceiverOpt, node.EventSymbol, asLvalue: false);
            return null;
        }
3459

3460 3461
        private void VisitMemberAccess(BoundExpression receiverOpt, Symbol member, bool asLvalue)
        {
3462
            Debug.Assert(!IsConditionalState);
3463 3464

            //if (this.State.Reachable) // PROTOTYPE(NullableReferenceTypes): Consider reachability?
3465
            {
3466
                VisitRvalue(receiverOpt);
3467

3468 3469 3470 3471 3472 3473 3474 3475 3476 3477
                if (!member.IsStatic)
                {
                    member = AsMemberOfResultType(member);
                    CheckPossibleNullReceiver(receiverOpt);
                }

                var resultType = member.GetTypeOrReturnType();

                if (!asLvalue)
                {
3478 3479
                    // We are supposed to track information for the node. Use whatever we managed to
                    // accumulate so far.
3480
                    if (resultType.IsReferenceType)
3481
                    {
3482 3483 3484
                        int containingSlot = (receiverOpt is null) ? -1 : MakeSlot(receiverOpt);
                        int slot = (containingSlot < 0) ? -1 : GetOrCreateSlot(member, containingSlot);
                        if (slot > 0 && slot < this.State.Capacity)
3485
                        {
3486 3487 3488 3489 3490
                            var isNullable = !this.State[slot];
                            if (isNullable != resultType.IsNullable)
                            {
                                resultType = TypeSymbolWithAnnotations.Create(resultType.TypeSymbol, isNullable);
                            }
3491 3492 3493 3494
                        }
                    }
                }

3495
                _resultType = resultType;
3496
            }
3497 3498 3499 3500 3501 3502 3503
        }

        public override void VisitForEachIterationVariables(BoundForEachStatement node)
        {
            // declare and assign all iteration variables
            foreach (var iterationVariable in node.IterationVariables)
            {
3504 3505 3506 3507 3508 3509 3510 3511
                int slot = GetOrCreateSlot(iterationVariable);
                TypeSymbolWithAnnotations sourceType = node.EnumeratorInfoOpt?.ElementType;
                bool? isNullableIfReferenceType = null;
                if ((object)sourceType != null)
                {
                    TypeSymbolWithAnnotations destinationType = iterationVariable.Type;
                    HashSet<DiagnosticInfo> useSiteDiagnostics = null;
                    Conversion conversion = _conversions.ClassifyImplicitConversionFromType(sourceType.TypeSymbol, destinationType.TypeSymbol, ref useSiteDiagnostics);
3512 3513 3514
                    TypeSymbolWithAnnotations result = ApplyConversion(node.IterationVariableType, operandOpt: null, conversion, destinationType.TypeSymbol, sourceType, checkConversion: false, fromExplicitCast: true, out bool canConvertNestedNullability);
                    if (destinationType.IsReferenceType && destinationType.IsNullable == false && sourceType.IsNullable == true)
                    {
3515
                        ReportWWarning(node.IterationVariableType.Syntax);
3516
                    }
3517 3518 3519
                    isNullableIfReferenceType = result.IsNullable;
                }
                this.State[slot] = !isNullableIfReferenceType;
3520 3521 3522 3523 3524
            }
        }

        public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node)
        {
3525 3526
            // Should be handled by VisitObjectCreationExpression.
            throw ExceptionUtilities.Unreachable;
3527 3528 3529 3530
        }

        public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node)
        {
3531
            SetResult(node);
3532 3533 3534 3535 3536 3537
            return null;
        }

        public override BoundNode VisitBadExpression(BoundBadExpression node)
        {
            var result = base.VisitBadExpression(node);
3538
            _resultType = TypeSymbolWithAnnotations.Create(node.Type, isNullableIfReferenceType: null);
3539 3540 3541 3542 3543 3544
            return result;
        }

        public override BoundNode VisitTypeExpression(BoundTypeExpression node)
        {
            var result = base.VisitTypeExpression(node);
3545
            SetResult(node);
3546 3547 3548 3549 3550 3551
            return result;
        }

        public override BoundNode VisitTypeOrValueExpression(BoundTypeOrValueExpression node)
        {
            var result = base.VisitTypeOrValueExpression(node);
3552
            SetResult(node);
3553 3554 3555 3556 3557 3558 3559 3560
            return result;
        }

        public override BoundNode VisitUnaryOperator(BoundUnaryOperator node)
        {
            Debug.Assert(!IsConditionalState);

            var result = base.VisitUnaryOperator(node);
3561
            TypeSymbolWithAnnotations resultType = null;
3562

3563
            // PROTOTYPE(NullableReferenceTypes): Update method based on inferred operand type.
3564 3565
            if (node.OperatorKind.IsUserDefined())
            {
3566 3567 3568
                if (node.OperatorKind.IsLifted())
                {
                    // PROTOTYPE(NullableReferenceTypes): Conversions: Lifted operator
3569
                }
3570
                else if ((object)node.MethodOpt != null && node.MethodOpt.ParameterCount == 1)
3571
                {
3572
                    ReportArgumentWarnings(node.Operand, _resultType, node.MethodOpt.Parameters[0]);
3573
                    resultType = node.MethodOpt.ReturnType;
3574 3575
                }
            }
3576

3577
            _resultType = resultType ?? TypeSymbolWithAnnotations.Create(node.Type, isNullableIfReferenceType: null);
3578
            return null;
3579 3580 3581 3582 3583
        }

        public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node)
        {
            var result = base.VisitPointerIndirectionOperator(node);
3584
            SetResult(node);
3585 3586 3587 3588 3589 3590
            return result;
        }

        public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node)
        {
            var result = base.VisitPointerElementAccess(node);
3591
            SetResult(node);
3592 3593 3594 3595 3596
            return result;
        }

        public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node)
        {
3597 3598 3599
            VisitRvalue(node.Operand);
            SetResult(node);
            return null;
3600 3601 3602 3603 3604
        }

        public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node)
        {
            var result = base.VisitMakeRefOperator(node);
3605
            SetResult(node);
3606 3607 3608 3609 3610 3611
            return result;
        }

        public override BoundNode VisitRefValueOperator(BoundRefValueOperator node)
        {
            var result = base.VisitRefValueOperator(node);
3612
            SetResult(node);
3613 3614 3615
            return result;
        }

3616
        private TypeSymbolWithAnnotations InferResultNullability(BoundUserDefinedConditionalLogicalOperator node)
3617
        {
3618 3619 3620
            if (node.OperatorKind.IsLifted())
            {
                // PROTOTYPE(NullableReferenceTypes): Conversions: Lifted operator
3621
                return TypeSymbolWithAnnotations.Create(node.Type, isNullableIfReferenceType: null);
3622
            }
3623
            // PROTOTYPE(NullableReferenceTypes): Update method based on inferred operand types.
3624 3625
            if ((object)node.LogicalOperator != null && node.LogicalOperator.ParameterCount == 2)
            {
3626
                return node.LogicalOperator.ReturnType;
3627 3628 3629 3630 3631 3632 3633 3634 3635 3636
            }
            else
            {
                return null;
            }
        }

        protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse)
        {
            Debug.Assert(!IsConditionalState);
3637
            //if (this.State.Reachable) // PROTOTYPE(NullableReferenceTypes): Consider reachability?
3638
            {
3639
                TypeSymbolWithAnnotations leftType = _resultType;
3640
                // PROTOTYPE(NullableReferenceTypes): Update operator methods based on inferred operand types.
3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
                MethodSymbol logicalOperator = null;
                MethodSymbol trueFalseOperator = null;
                BoundExpression left = null;

                switch (node.Kind)
                {
                    case BoundKind.BinaryOperator:
                        Debug.Assert(!((BoundBinaryOperator)node).OperatorKind.IsUserDefined());
                        break;
                    case BoundKind.UserDefinedConditionalLogicalOperator:
                        var binary = (BoundUserDefinedConditionalLogicalOperator)node;
                        if (binary.LogicalOperator != null && binary.LogicalOperator.ParameterCount == 2)
                        {
                            logicalOperator = binary.LogicalOperator;
                            left = binary.Left;
                            trueFalseOperator = isAnd ? binary.FalseOperator : binary.TrueOperator;

                            if ((object)trueFalseOperator != null && trueFalseOperator.ParameterCount != 1)
                            {
                                trueFalseOperator = null;
                            }
                        }
                        break;
                    default:
3665
                        throw ExceptionUtilities.UnexpectedValue(node.Kind);
3666 3667 3668 3669 3670 3671
                }

                Debug.Assert((object)trueFalseOperator == null || ((object)logicalOperator != null && left != null));

                if ((object)trueFalseOperator != null)
                {
3672
                    ReportArgumentWarnings(left, leftType, trueFalseOperator.Parameters[0]);
3673 3674 3675 3676
                }

                if ((object)logicalOperator != null)
                {
3677
                    ReportArgumentWarnings(left, leftType, logicalOperator.Parameters[0]);
3678 3679 3680
                }

                Visit(right);
3681
                TypeSymbolWithAnnotations rightType = _resultType;
3682

3683
                _resultType = InferResultNullabilityOfBinaryLogicalOperator(node, leftType, rightType);
3684 3685 3686

                if ((object)logicalOperator != null)
                {
3687
                    ReportArgumentWarnings(right, rightType, logicalOperator.Parameters[1]);
3688 3689
                }
            }
3690 3691

            AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(node, right, isAnd, isBool, ref leftTrue, ref leftFalse);
3692 3693
        }

3694
        private TypeSymbolWithAnnotations InferResultNullabilityOfBinaryLogicalOperator(BoundExpression node, TypeSymbolWithAnnotations leftType, TypeSymbolWithAnnotations rightType)
3695 3696 3697 3698
        {
            switch (node.Kind)
            {
                case BoundKind.BinaryOperator:
3699
                    return InferResultNullability((BoundBinaryOperator)node, leftType, rightType);
3700 3701 3702
                case BoundKind.UserDefinedConditionalLogicalOperator:
                    return InferResultNullability((BoundUserDefinedConditionalLogicalOperator)node);
                default:
3703
                    throw ExceptionUtilities.UnexpectedValue(node.Kind);
3704 3705 3706 3707 3708 3709
            }
        }

        public override BoundNode VisitAwaitExpression(BoundAwaitExpression node)
        {
            var result = base.VisitAwaitExpression(node);
3710
            if (!node.Type.IsReferenceType || node.HasErrors || (object)node.GetResult == null)
3711
            {
3712 3713 3714 3715 3716
                SetResult(node);
            }
            else
            {
                // PROTOTYPE(NullableReferenceTypes): Update method based on inferred receiver type.
3717
                _resultType = node.GetResult.ReturnType;
3718 3719 3720 3721 3722 3723 3724
            }
            return result;
        }

        public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node)
        {
            var result = base.VisitTypeOfOperator(node);
3725
            SetResult(node);
3726 3727 3728 3729 3730 3731
            return result;
        }

        public override BoundNode VisitMethodInfo(BoundMethodInfo node)
        {
            var result = base.VisitMethodInfo(node);
3732
            SetResult(node);
3733 3734 3735 3736 3737 3738
            return result;
        }

        public override BoundNode VisitFieldInfo(BoundFieldInfo node)
        {
            var result = base.VisitFieldInfo(node);
3739
            SetResult(node);
3740 3741 3742 3743 3744 3745
            return result;
        }

        public override BoundNode VisitDefaultExpression(BoundDefaultExpression node)
        {
            var result = base.VisitDefaultExpression(node);
3746
            _resultType = (object)node.Type == null ?
3747 3748
                null :
                TypeSymbolWithAnnotations.Create(node.Type, isNullableIfReferenceType: true);
3749 3750 3751 3752 3753 3754 3755
            return result;
        }

        public override BoundNode VisitIsOperator(BoundIsOperator node)
        {
            var result = base.VisitIsOperator(node);
            Debug.Assert(node.Type.SpecialType == SpecialType.System_Boolean);
3756
            SetResult(node);
3757 3758 3759 3760 3761 3762 3763
            return result;
        }

        public override BoundNode VisitAsOperator(BoundAsOperator node)
        {
            var result = base.VisitAsOperator(node);

3764
            //if (this.State.Reachable) // PROTOTYPE(NullableReferenceTypes): Consider reachability?
3765
            {
3766
                bool? isNullable = null;
3767 3768 3769 3770 3771 3772 3773
                if (node.Type.IsReferenceType)
                {
                    switch (node.Conversion.Kind)
                    {
                        case ConversionKind.Identity:
                        case ConversionKind.ImplicitReference:
                            // Inherit nullability from the operand
3774
                            isNullable = _resultType?.IsNullable;
3775 3776 3777
                            break;

                        case ConversionKind.Boxing:
3778 3779
                            var operandType = node.Operand.Type;
                            if (operandType?.IsValueType == true)
3780
                            {
3781 3782 3783
                                // PROTOTYPE(NullableReferenceTypes): Should we worry about a pathological case of boxing nullable value known to be not null?
                                //       For example, new int?(0)
                                isNullable = operandType.IsNullableType();
3784 3785 3786
                            }
                            else
                            {
3787 3788
                                Debug.Assert(operandType?.IsReferenceType != true);
                                isNullable = true;
3789 3790 3791 3792
                            }
                            break;

                        default:
3793
                            isNullable = true;
3794 3795 3796
                            break;
                    }
                }
3797
                _resultType = TypeSymbolWithAnnotations.Create(node.Type, isNullableIfReferenceType: isNullable);
3798 3799 3800 3801 3802 3803 3804
            }

            return result;
        }

        public override BoundNode VisitSuppressNullableWarningExpression(BoundSuppressNullableWarningExpression node)
        {
3805
            base.VisitSuppressNullableWarningExpression(node);
3806

3807
            //if (this.State.Reachable) // PROTOTYPE(NullableReferenceTypes): Consider reachability?
3808
            {
3809
                _resultType = _resultType?.WithTopLevelNonNullabilityForReferenceTypes();
3810 3811
            }

3812
            return null;
3813 3814 3815 3816 3817
        }

        public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node)
        {
            var result = base.VisitSizeOfOperator(node);
3818
            SetResult(node);
3819 3820 3821 3822 3823 3824 3825
            return result;
        }

        public override BoundNode VisitArgList(BoundArgList node)
        {
            var result = base.VisitArgList(node);
            Debug.Assert(node.Type.SpecialType == SpecialType.System_RuntimeArgumentHandle);
3826
            SetResult(node);
3827 3828 3829 3830 3831
            return result;
        }

        public override BoundNode VisitArgListOperator(BoundArgListOperator node)
        {
3832
            VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt);
3833
            Debug.Assert((object)node.Type == null);
3834
            SetResult(node);
3835
            return null;
3836 3837 3838 3839 3840 3841 3842
        }

        public override BoundNode VisitLiteral(BoundLiteral node)
        {
            var result = base.VisitLiteral(node);

            Debug.Assert(!IsConditionalState);
3843
            //if (this.State.Reachable) // PROTOTYPE(NullableReferenceTypes): Consider reachability?
3844 3845 3846 3847 3848 3849
            {
                var constant = node.ConstantValue;

                if (constant != null &&
                    ((object)node.Type != null ? node.Type.IsReferenceType : constant.IsNull))
                {
3850
                    _resultType = TypeSymbolWithAnnotations.Create(node.Type, isNullableIfReferenceType: constant.IsNull);
3851 3852 3853
                }
                else
                {
3854
                    SetResult(node);
3855 3856 3857 3858 3859 3860 3861 3862 3863 3864
                }
            }

            return result;
        }

        public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node)
        {
            var result = base.VisitPreviousSubmissionReference(node);
            Debug.Assert(node.WasCompilerGenerated);
3865
            SetResult(node);
3866 3867 3868 3869 3870 3871 3872
            return result;
        }

        public override BoundNode VisitHostObjectMemberReference(BoundHostObjectMemberReference node)
        {
            var result = base.VisitHostObjectMemberReference(node);
            Debug.Assert(node.WasCompilerGenerated);
3873
            SetResult(node);
3874 3875 3876 3877 3878 3879
            return result;
        }

        public override BoundNode VisitPseudoVariable(BoundPseudoVariable node)
        {
            var result = base.VisitPseudoVariable(node);
3880
            SetResult(node);
3881 3882 3883 3884 3885 3886
            return result;
        }

        public override BoundNode VisitRangeVariable(BoundRangeVariable node)
        {
            var result = base.VisitRangeVariable(node);
3887
            SetResult(node); // PROTOTYPE(NullableReferenceTypes)
3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899
            return result;
        }

        public override BoundNode VisitLabel(BoundLabel node)
        {
            var result = base.VisitLabel(node);
            SetUnknownResultNullability();
            return result;
        }

        public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node)
        {
3900 3901 3902
            var receiver = node.Receiver;
            VisitRvalue(receiver);
            CheckPossibleNullReceiver(receiver);
3903 3904

            Debug.Assert(node.Type.IsDynamic());
3905
            _resultType = TypeSymbolWithAnnotations.Create(node.Type, isNullableIfReferenceType: null);
3906
            return null;
3907 3908 3909 3910
        }

        public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node)
        {
3911
            VisitRvalue(node.Expression);
3912
            VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt);
3913 3914

            Debug.Assert(node.Type.IsDynamic());
3915
            Debug.Assert(node.Type.IsReferenceType);
3916

3917 3918
            // PROTOTYPE(NullableReferenceTypes): Update applicable members based on inferred argument types.
            bool? isNullable = InferResultNullabilityFromApplicableCandidates(StaticCast<Symbol>.From(node.ApplicableMethods));
3919
            _resultType = TypeSymbolWithAnnotations.Create(node.Type, isNullableIfReferenceType: isNullable);
3920
            return null;
3921 3922 3923 3924
        }

        public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node)
        {
3925
            VisitRvalue(node.ReceiverOpt);
3926 3927 3928 3929 3930 3931
            Debug.Assert(!IsConditionalState);
            var receiverOpt = node.ReceiverOpt;
            if (!node.Event.IsStatic)
            {
                CheckPossibleNullReceiver(receiverOpt);
            }
3932
            VisitRvalue(node.Argument);
3933
            SetResult(node); // PROTOTYPE(NullableReferenceTypes)
3934
            return null;
3935 3936 3937 3938
        }

        public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node)
        {
3939
            Debug.Assert(!IsConditionalState);
3940
            VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt);
3941 3942
            VisitObjectOrDynamicObjectCreation(node, node.InitializerExpressionOpt);
            return null;
3943 3944 3945 3946
        }

        public override BoundNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node)
        {
3947
            // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression().
3948
            SetResult(node);
3949
            return null;
3950 3951 3952 3953
        }

        public override BoundNode VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node)
        {
3954
            // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression().
3955
            SetResult(node);
3956
            return null;
3957 3958 3959 3960
        }

        public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node)
        {
3961
            // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression().
3962
            SetResult(node);
3963
            return null;
3964 3965 3966 3967 3968
        }

        public override BoundNode VisitImplicitReceiver(BoundImplicitReceiver node)
        {
            var result = base.VisitImplicitReceiver(node);
3969
            SetResult(node);
3970 3971 3972 3973 3974 3975
            return result;
        }

        public override BoundNode VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node)
        {
            var result = base.VisitAnonymousPropertyDeclaration(node);
3976
            SetResult(node);
3977 3978 3979 3980 3981 3982
            return result;
        }

        public override BoundNode VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node)
        {
            var result = base.VisitNoPiaObjectCreationExpression(node);
3983
            SetResult(node);
3984 3985 3986 3987 3988 3989
            return result;
        }

        public override BoundNode VisitNewT(BoundNewT node)
        {
            var result = base.VisitNewT(node);
3990
            SetResult(node);
3991 3992 3993 3994 3995 3996
            return result;
        }

        public override BoundNode VisitArrayInitialization(BoundArrayInitialization node)
        {
            var result = base.VisitArrayInitialization(node);
3997
            SetResult(node);
3998 3999 4000 4001 4002
            return result;
        }

        private void SetUnknownResultNullability()
        {
4003
            _resultType = null;
4004 4005 4006 4007 4008 4009
        }

        public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node)
        {
            var result = base.VisitStackAllocArrayCreation(node);
            Debug.Assert((object)node.Type == null || node.Type.IsPointerType() || node.Type.IsByRefLikeType);
4010
            SetResult(node);
4011 4012 4013 4014 4015
            return result;
        }

        public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node)
        {
4016 4017 4018
            var receiver = node.ReceiverOpt;
            VisitRvalue(receiver);
            CheckPossibleNullReceiver(receiver);
4019
            VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt);
4020 4021 4022

            Debug.Assert(node.Type.IsDynamic());

4023 4024 4025 4026
            // PROTOTYPE(NullableReferenceTypes): Update applicable members based on inferred argument types.
            bool? isNullable = (node.Type?.IsReferenceType == true) ?
                InferResultNullabilityFromApplicableCandidates(StaticCast<Symbol>.From(node.ApplicableIndexers)) :
                null;
4027
            _resultType = TypeSymbolWithAnnotations.Create(node.Type, isNullableIfReferenceType: isNullable);
4028
            return null;
4029 4030 4031 4032
        }

        private void CheckPossibleNullReceiver(BoundExpression receiverOpt, bool checkType = true)
        {
4033
            if (receiverOpt != null && this.State.Reachable)
4034
            {
4035
#if DEBUG
4036
                Debug.Assert(receiverOpt.Type is null || _resultType?.TypeSymbol is null || AreCloseEnough(receiverOpt.Type, _resultType.TypeSymbol));
4037
#endif
4038
                TypeSymbol receiverType = receiverOpt.Type ?? _resultType?.TypeSymbol;
4039 4040
                if ((object)receiverType != null &&
                    (!checkType || receiverType.IsReferenceType || receiverType.IsUnconstrainedTypeParameter()) &&
4041
                    (_resultType?.IsNullable == true || receiverType.IsUnconstrainedTypeParameter()))
4042 4043 4044
                {
                    ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullReferenceReceiver, receiverOpt.Syntax);
                }
4045 4046 4047
            }
        }

4048 4049 4050 4051 4052
        /// <summary>
        /// Report warning converting null literal to non-nullable reference type.
        /// target (e.g.: `object x = null;` or calling `void F(object y)` with `F(null)`).
        /// </summary>
        private bool ReportNullAsNonNullableReferenceIfNecessary(BoundExpression value)
4053
        {
4054
            if (value.ConstantValue?.IsNull != true && !IsDefaultOfUnconstrainedTypeParameter(value))
4055 4056 4057
            {
                return false;
            }
4058
            ReportStaticNullCheckingDiagnostics(ErrorCode.WRN_NullAsNonNullable, value.Syntax);
4059 4060 4061
            return true;
        }

4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079
        private static bool IsDefaultOfUnconstrainedTypeParameter(BoundExpression expr)
        {
            switch (expr.Kind)
            {
                case BoundKind.Conversion:
                    {
                        var conversion = (BoundConversion)expr;
                        // PROTOTYPE(NullableReferenceTypes): Check target type is unconstrained type parameter?
                        return conversion.Conversion.Kind == ConversionKind.DefaultOrNullLiteral &&
                            IsDefaultOfUnconstrainedTypeParameter(conversion.Operand);
                    }
                case BoundKind.DefaultExpression:
                    return IsUnconstrainedTypeParameter(expr.Type);
                default:
                    return false;
            }
        }

4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098
        private static bool IsNullabilityMismatch(TypeSymbolWithAnnotations type1, TypeSymbolWithAnnotations type2)
        {
            return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) &&
                !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes | TypeCompareKind.UnknownNullableModifierMatchesAny);
        }

        private static bool IsNullabilityMismatch(TypeSymbol type1, TypeSymbol type2)
        {
            return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) &&
                !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes | TypeCompareKind.UnknownNullableModifierMatchesAny);
        }

        private bool? InferResultNullabilityFromApplicableCandidates(ImmutableArray<Symbol> applicableMembers)
        {
            if (applicableMembers.IsDefaultOrEmpty)
            {
                return null;
            }

4099
            bool? resultIsNullable = false;
4100 4101 4102 4103 4104 4105 4106

            foreach (Symbol member in applicableMembers)
            {
                TypeSymbolWithAnnotations type = member.GetTypeOrReturnType();

                if (type.IsReferenceType)
                {
4107
                    bool? memberResultIsNullable = type.IsNullable;
4108
                    if (memberResultIsNullable == true)
4109 4110
                    {
                        // At least one candidate can produce null, assume dynamic access can produce null as well
4111
                        resultIsNullable = true;
4112 4113
                        break;
                    }
4114
                    else if (memberResultIsNullable == null)
4115
                    {
4116
                        // At least one candidate can produce result of an unknown nullability.
4117
                        // At best, dynamic access can produce result of an unknown nullability as well.
4118
                        resultIsNullable = null;
4119 4120 4121 4122
                    }
                }
                else if (!type.IsValueType)
                {
4123
                    resultIsNullable = null;
4124 4125 4126
                }
            }

4127
            return resultIsNullable;
4128 4129 4130 4131 4132
        }

        public override BoundNode VisitQueryClause(BoundQueryClause node)
        {
            var result = base.VisitQueryClause(node);
4133
            SetResult(node); // PROTOTYPE(NullableReferenceTypes)
4134 4135 4136 4137 4138 4139
            return result;
        }

        public override BoundNode VisitNameOfOperator(BoundNameOfOperator node)
        {
            var result = base.VisitNameOfOperator(node);
4140
            SetResult(node);
4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153
            return result;
        }

        public override BoundNode VisitNamespaceExpression(BoundNamespaceExpression node)
        {
            var result = base.VisitNamespaceExpression(node);
            SetUnknownResultNullability();
            return result;
        }

        public override BoundNode VisitInterpolatedString(BoundInterpolatedString node)
        {
            var result = base.VisitInterpolatedString(node);
4154
            SetResult(node);
4155 4156 4157 4158 4159 4160 4161 4162 4163 4164
            return result;
        }

        public override BoundNode VisitStringInsert(BoundStringInsert node)
        {
            var result = base.VisitStringInsert(node);
            SetUnknownResultNullability();
            return result;
        }

4165 4166 4167 4168 4169 4170 4171 4172 4173
        public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node)
        {
            var result = base.VisitConvertedStackAllocExpression(node);
            SetResult(node);
            return result;
        }

        public override BoundNode VisitDiscardExpression(BoundDiscardExpression node)
        {
4174
            SetResult(node);
4175 4176 4177
            return null;
        }

4178 4179 4180 4181 4182 4183 4184
        public override BoundNode VisitThrowExpression(BoundThrowExpression node)
        {
            var result = base.VisitThrowExpression(node);
            SetUnknownResultNullability();
            return result;
        }

4185
        #endregion Visitors
4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237

        protected override string Dump(LocalState state)
        {
            return string.Empty;
        }

        protected override void UnionWith(ref LocalState self, ref LocalState other)
        {
            if (self.Capacity != other.Capacity)
            {
                Normalize(ref self);
                Normalize(ref other);
            }

            for (int slot = 1; slot < self.Capacity; slot++)
            {
                bool? selfSlotIsNotNull = self[slot];
                bool? union = selfSlotIsNotNull | other[slot];
                if (selfSlotIsNotNull != union)
                {
                    self[slot] = union;
                }
            }
        }

        protected override bool IntersectWith(ref LocalState self, ref LocalState other)
        {
            if (self.Reachable == other.Reachable)
            {
                bool result = false;

                if (self.Capacity != other.Capacity)
                {
                    Normalize(ref self);
                    Normalize(ref other);
                }

                for (int slot = 1; slot < self.Capacity; slot++)
                {
                    bool? selfSlotIsNotNull = self[slot];
                    bool? intersection = selfSlotIsNotNull & other[slot];
                    if (selfSlotIsNotNull != intersection)
                    {
                        self[slot] = intersection;
                        result = true;
                    }
                }

                return result;
            }
            else if (!self.Reachable)
            {
4238
                self = other.Clone();
4239 4240 4241 4242 4243 4244 4245 4246 4247
                return true;
            }
            else
            {
                Debug.Assert(!other.Reachable);
                return false;
            }
        }

4248
        [DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
4249 4250 4251 4252 4253 4254
#if REFERENCE_STATE
        internal class LocalState : AbstractLocalState
#else
        internal struct LocalState : AbstractLocalState
#endif
        {
4255 4256
            // PROTOTYPE(NullableReferenceTypes): Consider storing nullability rather than non-nullability
            // or perhaps expose as nullability from `this[int]` even if stored differently.
4257 4258 4259
            private BitVector _knownNullState; // No diagnostics should be derived from a variable with a bit set to 0.
            private BitVector _notNull;

4260
            internal LocalState(BitVector knownNullState, BitVector notNull)
4261
            {
4262
                Debug.Assert(!knownNullState.IsNull);
4263
                Debug.Assert(!notNull.IsNull);
4264
                this._knownNullState = knownNullState;
4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294
                this._notNull = notNull;
            }

            internal int Capacity => _knownNullState.Capacity;

            internal void EnsureCapacity(int capacity)
            {
                _knownNullState.EnsureCapacity(capacity);
                _notNull.EnsureCapacity(capacity);
            }

            internal bool? this[int slot]
            {
                get
                {
                    return _knownNullState[slot] ? _notNull[slot] : (bool?)null;
                }
                set
                {
                    _knownNullState[slot] = value.HasValue;
                    _notNull[slot] = value.GetValueOrDefault();
                }
            }

            /// <summary>
            /// Produce a duplicate of this flow analysis state.
            /// </summary>
            /// <returns></returns>
            public LocalState Clone()
            {
4295
                return new LocalState(_knownNullState.Clone(), _notNull.Clone());
4296 4297 4298 4299 4300 4301 4302 4303 4304
            }

            public bool Reachable
            {
                get
                {
                    return _knownNullState.Capacity > 0;
                }
            }
4305

4306
            internal string GetDebuggerDisplay()
4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317
            {
                var pooledBuilder = PooledStringBuilder.GetInstance();
                var builder = pooledBuilder.Builder;
                builder.Append(" ");
                for (int i = this.Capacity - 1; i >= 0; i--)
                {
                    builder.Append(_knownNullState[i] ? (_notNull[i] ? "!" : "?") : "_");
                }

                return pooledBuilder.ToStringAndFree();
            }
4318 4319 4320
        }
    }
}