-
Notifications
You must be signed in to change notification settings - Fork 4k
/
NullableWalker_Patterns.cs
697 lines (636 loc) · 36 KB
/
NullableWalker_Patterns.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class NullableWalker
{
/// <summary>
/// Learn something about the input from a test of a given expression against a given pattern. The given
/// state is updated to note that any slots that are tested against `null` may be null.
/// </summary>
/// <returns>true if there is a top-level explicit null check</returns>
private void LearnFromAnyNullPatterns(
BoundExpression expression,
BoundPattern pattern)
{
int slot = MakeSlot(expression);
LearnFromAnyNullPatterns(slot, expression.Type, pattern);
}
private void VisitPatternForRewriting(BoundPattern pattern)
{
// Don't let anything under the pattern actually affect current state,
// as we're only visiting for nullable information.
Debug.Assert(!IsConditionalState);
var currentState = State;
VisitWithoutDiagnostics(pattern);
SetState(currentState);
}
public override BoundNode VisitSubpattern(BoundSubpattern node)
{
Visit(node.Pattern);
return null;
}
public override BoundNode VisitRecursivePattern(BoundRecursivePattern node)
{
Visit(node.DeclaredType);
VisitAndUnsplitAll(node.Deconstruction);
VisitAndUnsplitAll(node.Properties);
Visit(node.VariableAccess);
return null;
}
public override BoundNode VisitConstantPattern(BoundConstantPattern node)
{
Visit(node.Value);
return null;
}
public override BoundNode VisitDeclarationPattern(BoundDeclarationPattern node)
{
Visit(node.VariableAccess);
Visit(node.DeclaredType);
return null;
}
public override BoundNode VisitDiscardPattern(BoundDiscardPattern node)
{
return null;
}
public override BoundNode VisitTypePattern(BoundTypePattern node)
{
Visit(node.DeclaredType);
return null;
}
public override BoundNode VisitRelationalPattern(BoundRelationalPattern node)
{
Visit(node.Value);
return null;
}
public override BoundNode VisitNegatedPattern(BoundNegatedPattern node)
{
Visit(node.Negated);
return null;
}
public override BoundNode VisitBinaryPattern(BoundBinaryPattern node)
{
Visit(node.Left);
Visit(node.Right);
return null;
}
public override BoundNode VisitITuplePattern(BoundITuplePattern node)
{
VisitAndUnsplitAll(node.Subpatterns);
return null;
}
/// <summary>
/// Learn from any constant null patterns appearing in the pattern.
/// </summary>
/// <param name="inputType">Type type of the input expression (before nullable analysis).
/// Used to determine which types can contain null.</param>
private void LearnFromAnyNullPatterns(
int inputSlot,
TypeSymbol inputType,
BoundPattern pattern)
{
if (inputSlot <= 0)
return;
// https://github.com/dotnet/roslyn/issues/35041 We only need to do this when we're rewriting, so we
// can get information for any nodes in the pattern.
VisitPatternForRewriting(pattern);
switch (pattern)
{
case BoundConstantPattern cp:
bool isExplicitNullCheck = cp.Value.ConstantValue == ConstantValue.Null;
if (isExplicitNullCheck)
{
// Since we're not branching on this null test here, we just infer the top level
// nullability. We'll branch on it later.
LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
}
break;
case BoundDeclarationPattern _:
case BoundDiscardPattern _:
case BoundITuplePattern _:
case BoundRelationalPattern _:
break; // nothing to learn
case BoundTypePattern tp:
if (tp.IsExplicitNotNullTest)
{
LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
}
break;
case BoundRecursivePattern rp:
{
if (rp.IsExplicitNotNullTest)
{
LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
}
// for positional part: we only learn from tuples (not Deconstruct)
if (rp.DeconstructMethod is null && !rp.Deconstruction.IsDefault)
{
var elements = inputType.TupleElements;
for (int i = 0, n = Math.Min(rp.Deconstruction.Length, elements.IsDefault ? 0 : elements.Length); i < n; i++)
{
BoundSubpattern item = rp.Deconstruction[i];
FieldSymbol element = elements[i];
LearnFromAnyNullPatterns(GetOrCreateSlot(element, inputSlot), element.Type, item.Pattern);
}
}
// for property part
if (!rp.Properties.IsDefault)
{
for (int i = 0, n = rp.Properties.Length; i < n; i++)
{
BoundSubpattern item = rp.Properties[i];
Symbol symbol = item.Symbol;
if (symbol?.ContainingType.Equals(inputType, TypeCompareKind.AllIgnoreOptions) == true)
{
LearnFromAnyNullPatterns(GetOrCreateSlot(symbol, inputSlot), symbol.GetTypeOrReturnType().Type, item.Pattern);
}
}
}
}
break;
case BoundNegatedPattern p:
LearnFromAnyNullPatterns(inputSlot, inputType, p.Negated);
break;
case BoundBinaryPattern p:
LearnFromAnyNullPatterns(inputSlot, inputType, p.Left);
LearnFromAnyNullPatterns(inputSlot, inputType, p.Right);
break;
default:
throw ExceptionUtilities.UnexpectedValue(pattern);
}
}
protected override (LocalState initialState, LocalState afterSwitchState) VisitSwitchStatementDispatch(BoundSwitchStatement node)
{
// first, learn from any null tests in the patterns
int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression);
if (slot > 0)
{
var originalInputType = node.Expression.Type;
foreach (var section in node.SwitchSections)
{
foreach (var label in section.SwitchLabels)
{
LearnFromAnyNullPatterns(slot, originalInputType, label.Pattern);
}
}
}
// visit switch header
var expressionState = VisitRvalueWithState(node.Expression);
LocalState initialState = this.State.Clone();
DeclareLocals(node.InnerLocals);
foreach (var section in node.SwitchSections)
{
// locals can be alive across jumps in the switch sections, so we declare them early.
DeclareLocals(section.Locals);
}
var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, ref initialState);
foreach (var section in node.SwitchSections)
{
foreach (var label in section.SwitchLabels)
{
var labelResult = labelStateMap.TryGetValue(label.Label, out var s1) ? s1 : (state: UnreachableState(), believedReachable: false);
SetState(labelResult.state);
PendingBranches.Add(new PendingBranch(label, this.State, label.Label));
}
}
var afterSwitchState = labelStateMap.TryGetValue(node.BreakLabel, out var stateAndReachable) ? stateAndReachable.state : UnreachableState();
labelStateMap.Free();
return (initialState, afterSwitchState);
}
protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection)
{
TakeIncrementalSnapshot(node);
SetState(UnreachableState());
foreach (var label in node.SwitchLabels)
{
TakeIncrementalSnapshot(label);
VisitPatternForRewriting(label.Pattern);
VisitLabel(label.Label, node);
}
VisitStatementList(node);
}
private PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)>
LearnFromDecisionDag(
SyntaxNode node,
BoundDecisionDag decisionDag,
BoundExpression expression,
TypeWithState expressionType,
ref LocalState initialState)
{
// We reuse the slot at the beginning of a switch (or is-pattern expression), pretending that we are
// not copying the input to evaluate the patterns. In this way we infer non-nullability of the original
// variable's parts based on matched pattern parts. Mutations in `when` clauses can show the inaccuracy
// of analysis based on this choice.
var rootTemp = BoundDagTemp.ForOriginalInput(expression);
int originalInputSlot = MakeSlot(expression);
if (originalInputSlot <= 0)
{
originalInputSlot = makeDagTempSlot(expressionType.ToTypeWithAnnotations(compilation), rootTemp);
initialState[originalInputSlot] = expressionType.State;
}
var tempMap = PooledDictionary<BoundDagTemp, (int slot, TypeSymbol type)>.GetInstance();
Debug.Assert(originalInputSlot > 0);
Debug.Assert(isDerivedType(NominalSlotType(originalInputSlot), expressionType.Type));
tempMap.Add(rootTemp, (originalInputSlot, expressionType.Type));
var nodeStateMap = PooledDictionary<BoundDecisionDagNode, (LocalState state, bool believedReachable)>.GetInstance();
nodeStateMap.Add(decisionDag.RootNode, (state: initialState.Clone(), believedReachable: true));
var labelStateMap = PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)>.GetInstance();
foreach (var dagNode in decisionDag.TopologicallySortedNodes)
{
bool found = nodeStateMap.TryGetValue(dagNode, out var nodeStateAndBelievedReachable);
Debug.Assert(found); // the topologically sorted nodes should contain only reachable nodes
(LocalState nodeState, bool nodeBelievedReachable) = nodeStateAndBelievedReachable;
SetState(nodeState);
switch (dagNode)
{
case BoundEvaluationDecisionDagNode p:
{
var evaluation = p.Evaluation;
(int inputSlot, TypeSymbol inputType) = tempMap.TryGetValue(evaluation.Input, out var slotAndType) ? slotAndType : throw ExceptionUtilities.Unreachable;
Debug.Assert(inputSlot > 0);
var inputState = this.State[inputSlot];
switch (evaluation)
{
case BoundDagDeconstructEvaluation e:
{
// https://github.com/dotnet/roslyn/issues/34232
// We may need to recompute the Deconstruct method for a deconstruction if
// the receiver type has changed (e.g. its nested nullability).
var method = e.DeconstructMethod;
int extensionExtra = method.RequiresInstanceReceiver ? 0 : 1;
for (int i = 0; i < method.ParameterCount - extensionExtra; i++)
{
var parameterType = method.Parameters[i + extensionExtra].TypeWithAnnotations;
var output = new BoundDagTemp(e.Syntax, parameterType.Type, e, i);
int outputSlot = makeDagTempSlot(parameterType, output);
Debug.Assert(outputSlot > 0);
addToTempMap(output, outputSlot, parameterType.Type);
}
break;
}
case BoundDagTypeEvaluation e:
{
var output = new BoundDagTemp(e.Syntax, e.Type, e);
HashSet<DiagnosticInfo> discardedDiagnostics = null;
int outputSlot;
switch (_conversions.WithNullability(false).ClassifyConversionFromType(inputType, e.Type, ref discardedDiagnostics).Kind)
{
case ConversionKind.Identity:
case ConversionKind.ImplicitReference:
outputSlot = inputSlot;
break;
case ConversionKind.ExplicitNullable when AreNullableAndUnderlyingTypes(inputType, e.Type, out _):
outputSlot = GetNullableOfTValueSlot(inputType, inputSlot, out _, forceSlotEvenIfEmpty: true);
if (outputSlot < 0)
goto default;
break;
default:
outputSlot = makeDagTempSlot(TypeWithAnnotations.Create(e.Type, NullableAnnotation.NotAnnotated), output);
break;
}
State[outputSlot] = NullableFlowState.NotNull;
addToTempMap(output, outputSlot, e.Type);
break;
}
case BoundDagFieldEvaluation e:
{
Debug.Assert(inputSlot > 0);
var field = (FieldSymbol)AsMemberOfType(inputType, e.Field);
int outputSlot = GetOrCreateSlot(field, inputSlot, forceSlotEvenIfEmpty: true);
Debug.Assert(outputSlot > 0);
var type = field.Type;
var output = new BoundDagTemp(e.Syntax, type, e);
addToTempMap(output, outputSlot, type);
break;
}
case BoundDagPropertyEvaluation e:
{
Debug.Assert(inputSlot > 0);
var property = (PropertySymbol)AsMemberOfType(inputType, e.Property);
var type = property.TypeWithAnnotations;
var output = new BoundDagTemp(e.Syntax, type.Type, e);
int outputSlot = GetOrCreateSlot(property, inputSlot, forceSlotEvenIfEmpty: true);
if (outputSlot <= 0)
{
// This is needed due to https://github.com/dotnet/roslyn/issues/29619
outputSlot = makeDagTempSlot(type, output);
}
Debug.Assert(outputSlot > 0);
addToTempMap(output, outputSlot, type.Type);
break;
}
case BoundDagIndexEvaluation e:
{
var type = TypeWithAnnotations.Create(e.Property.Type, NullableAnnotation.Annotated);
var output = new BoundDagTemp(e.Syntax, type.Type, e);
int outputSlot = makeDagTempSlot(type, output);
Debug.Assert(outputSlot > 0);
addToTempMap(output, outputSlot, type.Type);
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(p.Evaluation.Kind);
}
gotoNode(p.Next, this.State, nodeBelievedReachable);
break;
}
case BoundTestDecisionDagNode p:
{
var test = p.Test;
bool foundTemp = tempMap.TryGetValue(test.Input, out var slotAndType);
Debug.Assert(foundTemp);
(int inputSlot, TypeSymbol inputType) = slotAndType;
var inputState = this.State[inputSlot];
Split();
switch (test)
{
case BoundDagTypeTest t:
if (inputSlot > 0)
{
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
break;
case BoundDagNonNullTest t:
if (inputSlot > 0)
{
MarkDependentSlotsNotNull(inputSlot, inputType, ref this.StateWhenFalse);
if (t.IsExplicitTest)
{
LearnFromNullTest(inputSlot, inputType, ref this.StateWhenFalse, markDependentSlotsNotNull: false);
}
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable & inputState.MayBeNull());
break;
case BoundDagExplicitNullTest _:
if (inputSlot > 0)
{
LearnFromNullTest(inputSlot, inputType, ref this.StateWhenTrue, markDependentSlotsNotNull: true);
learnFromNonNullTest(inputSlot, ref this.StateWhenFalse);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
break;
case BoundDagValueTest t:
Debug.Assert(t.Value != ConstantValue.Null);
if (inputSlot > 0)
{
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
break;
case BoundDagRelationalTest _:
if (inputSlot > 0)
{
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
break;
default:
throw ExceptionUtilities.UnexpectedValue(test.Kind);
}
break;
}
case BoundLeafDecisionDagNode d:
// We have one leaf decision dag node per reachable label
labelStateMap.Add(d.Label, (this.State, nodeBelievedReachable));
break;
case BoundWhenDecisionDagNode w:
// bind the pattern variables, inferring their types as well
foreach (var binding in w.Bindings)
{
var variableAccess = binding.VariableAccess;
var tempSource = binding.TempContainingValue;
var foundTemp = tempMap.TryGetValue(tempSource, out var tempSlotAndType);
if (foundTemp) // in erroneous programs, we might not have seen a temp defined.
{
var (tempSlot, tempType) = tempSlotAndType;
var tempState = this.State[tempSlot];
if (variableAccess is BoundLocal { LocalSymbol: SourceLocalSymbol local } boundLocal)
{
var value = TypeWithState.Create(tempType, tempState);
var inferredType = value.ToTypeWithAnnotations(compilation, asAnnotatedType: boundLocal.DeclarationKind == BoundLocalDeclarationKind.WithInferredType);
if (_variables.TryGetType(local, out var existingType))
{
// merge inferred nullable annotation from different branches of the decision tree
inferredType = TypeWithAnnotations.Create(inferredType.Type, existingType.NullableAnnotation.Join(inferredType.NullableAnnotation));
}
_variables.SetType(local, inferredType);
int localSlot = GetOrCreateSlot(local, forceSlotEvenIfEmpty: true);
if (localSlot > 0)
{
this.State[localSlot] = tempState;
}
}
else
{
// https://github.com/dotnet/roslyn/issues/34144 perform inference for top-level var-declared fields in scripts
}
}
}
if (w.WhenExpression != null && w.WhenExpression.ConstantValue != ConstantValue.True)
{
VisitCondition(w.WhenExpression);
Debug.Assert(this.IsConditionalState);
gotoNode(w.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(w.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
}
else
{
Debug.Assert(w.WhenFalse is null);
gotoNode(w.WhenTrue, this.State, nodeBelievedReachable);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(dagNode.Kind);
}
}
SetUnreachable(); // the decision dag is always complete (no fall-through)
tempMap.Free();
nodeStateMap.Free();
return labelStateMap;
void learnFromNonNullTest(int inputSlot, ref LocalState state)
{
LearnFromNonNullTest(inputSlot, ref state);
if (inputSlot == originalInputSlot)
LearnFromNonNullTest(expression, ref state);
}
void addToTempMap(BoundDagTemp output, int slot, TypeSymbol type)
{
// We need to track all dag temps, so there should be a slot
Debug.Assert(slot > 0);
if (tempMap.TryGetValue(output, out var outputSlotAndType))
{
// The dag temp has already been allocated on another branch of the dag
Debug.Assert(outputSlotAndType.slot == slot);
Debug.Assert(isDerivedType(outputSlotAndType.type, type));
}
else
{
Debug.Assert(NominalSlotType(slot) is var slotType && (slotType.IsErrorType() || isDerivedType(slotType, type)));
tempMap.Add(output, (slot, type));
}
}
bool isDerivedType(TypeSymbol derivedType, TypeSymbol baseType)
{
HashSet<DiagnosticInfo> discardedDiagnostics = null;
if (derivedType.IsErrorType() || baseType.IsErrorType())
return true;
return _conversions.WithNullability(false).ClassifyConversionFromType(derivedType, baseType, ref discardedDiagnostics).Kind switch
{
ConversionKind.Identity => true,
ConversionKind.ImplicitReference => true,
ConversionKind.Boxing => true,
_ => false,
};
}
void gotoNode(BoundDecisionDagNode node, LocalState state, bool believedReachable)
{
if (nodeStateMap.TryGetValue(node, out var stateAndReachable))
{
Join(ref state, ref stateAndReachable.state);
believedReachable |= stateAndReachable.believedReachable;
}
nodeStateMap[node] = (state, believedReachable);
}
int makeDagTempSlot(TypeWithAnnotations type, BoundDagTemp temp)
{
object slotKey = (node, temp);
return GetOrCreatePlaceholderSlot(slotKey, type);
}
}
public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node)
{
bool inferType = !node.WasTargetTyped;
VisitSwitchExpressionCore(node, inferType);
return null;
}
public override BoundNode VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node)
{
// This method is only involved in method inference with unbound lambdas.
VisitSwitchExpressionCore(node, inferType: true);
return null;
}
private void VisitSwitchExpressionCore(BoundSwitchExpression node, bool inferType)
{
// first, learn from any null tests in the patterns
int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression);
if (slot > 0)
{
var originalInputType = node.Expression.Type;
foreach (var arm in node.SwitchArms)
{
LearnFromAnyNullPatterns(slot, originalInputType, arm.Pattern);
}
}
var expressionState = VisitRvalueWithState(node.Expression);
var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, ref this.State);
var endState = UnreachableState();
if (!node.ReportedNotExhaustive && node.DefaultLabel != null &&
labelStateMap.TryGetValue(node.DefaultLabel, out var defaultLabelState) && defaultLabelState.believedReachable)
{
SetState(defaultLabelState.state);
var nodes = node.DecisionDag.TopologicallySortedNodes;
var leaf = nodes.Where(n => n is BoundLeafDecisionDagNode leaf && leaf.Label == node.DefaultLabel).First();
var samplePattern = PatternExplainer.SamplePatternForPathToDagNode(
BoundDagTemp.ForOriginalInput(node.Expression), nodes, leaf, nullPaths: true, out bool requiresFalseWhenClause, out _);
ErrorCode warningCode = requiresFalseWhenClause ? ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen : ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull;
ReportDiagnostic(
warningCode,
((SwitchExpressionSyntax)node.Syntax).SwitchKeyword.GetLocation(),
samplePattern);
}
// collect expressions, conversions and result types
int numSwitchArms = node.SwitchArms.Length;
var conversions = ArrayBuilder<Conversion>.GetInstance(numSwitchArms);
var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(numSwitchArms);
var expressions = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms);
var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms);
foreach (var arm in node.SwitchArms)
{
SetState(!arm.Pattern.HasErrors && labelStateMap.TryGetValue(arm.Label, out var labelState) ? labelState.state : UnreachableState());
// https://github.com/dotnet/roslyn/issues/35836 Is this where we want to take the snapshot?
TakeIncrementalSnapshot(arm);
VisitPatternForRewriting(arm.Pattern);
(BoundExpression expression, Conversion conversion) = RemoveConversion(arm.Value, includeExplicitConversions: false);
SnapshotWalkerThroughConversionGroup(arm.Value, expression);
expressions.Add(expression);
conversions.Add(conversion);
var armType = VisitRvalueWithState(expression);
resultTypes.Add(armType);
Join(ref endState, ref this.State);
// Build placeholders for inference in order to preserve annotations.
placeholderBuilder.Add(CreatePlaceholderIfNecessary(expression, armType.ToTypeWithAnnotations(compilation)));
}
var placeholders = placeholderBuilder.ToImmutableAndFree();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
TypeSymbol inferredType =
(inferType ? BestTypeInferrer.InferBestType(placeholders, _conversions, ref useSiteDiagnostics) : null)
?? node.Type?.SetUnknownNullabilityForReferenceTypes();
var inferredTypeWithAnnotations = TypeWithAnnotations.Create(inferredType);
// Convert elements to best type to determine element top-level nullability and to report nested nullability warnings
if (inferredType is not null)
{
for (int i = 0; i < numSwitchArms; i++)
{
var expression = expressions[i];
resultTypes[i] = VisitConversion(conversionOpt: null, expression, conversions[i], inferredTypeWithAnnotations, resultTypes[i], checkConversion: true,
fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: true, reportTopLevelWarnings: false);
}
}
var inferredState = BestTypeInferrer.GetNullableState(resultTypes);
var resultType = TypeWithState.Create(inferredType, inferredState);
if (inferredType is not null)
{
inferredTypeWithAnnotations = resultType.ToTypeWithAnnotations(compilation);
if (resultType.State == NullableFlowState.MaybeDefault)
{
inferredTypeWithAnnotations = inferredTypeWithAnnotations.AsAnnotated();
}
for (int i = 0; i < numSwitchArms; i++)
{
var nodeForSyntax = expressions[i];
var conversionOpt = node.SwitchArms[i].Value switch { BoundConversion c when c != nodeForSyntax => c, _ => null };
// Report top-level warnings
_ = VisitConversion(conversionOpt, conversionOperand: nodeForSyntax, conversions[i], targetTypeWithNullability: inferredTypeWithAnnotations, operandType: resultTypes[i],
checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: false, reportTopLevelWarnings: true);
}
}
conversions.Free();
resultTypes.Free();
expressions.Free();
labelStateMap.Free();
SetState(endState);
SetResult(node, resultType, inferredTypeWithAnnotations);
}
public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node)
{
Debug.Assert(!IsConditionalState);
LearnFromAnyNullPatterns(node.Expression, node.Pattern);
VisitPatternForRewriting(node.Pattern);
var expressionState = VisitRvalueWithState(node.Expression);
var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, ref this.State);
var trueState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenFalseLabel : node.WhenTrueLabel, out var s1) ? s1.state : UnreachableState();
var falseState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenTrueLabel : node.WhenFalseLabel, out var s2) ? s2.state : UnreachableState();
labelStateMap.Free();
SetConditionalState(trueState, falseState);
SetNotNullResult(node);
return null;
}
}
}