-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
NullableWalker.cs
10140 lines (8980 loc) · 465 KB
/
NullableWalker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Nullability flow analysis.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
internal sealed partial class NullableWalker
: LocalDataFlowPass<NullableWalker.LocalState, NullableWalker.LocalFunctionState>
{
/// <summary>
/// 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.
/// </summary>
internal sealed class VariableState
{
// Consider referencing the Variables instance directly from the original NullableWalker
// rather than cloning. (Items are added to the collections but never replaced so the
// collections are lazily populated but otherwise immutable. We'd probably want a
// clone when analyzing from speculative semantic model though.)
internal readonly VariablesSnapshot Variables;
// The nullable state of all variables captured at the point where the function or lambda appeared.
internal readonly LocalStateSnapshot VariableNullableStates;
internal VariableState(VariablesSnapshot variables, LocalStateSnapshot variableNullableStates)
{
Variables = variables;
VariableNullableStates = variableNullableStates;
}
}
/// <summary>
/// Data recorded for a particular analysis run.
/// </summary>
internal readonly struct Data
{
/// <summary>
/// Number of entries tracked during analysis.
/// </summary>
internal readonly int TrackedEntries;
/// <summary>
/// True if analysis was required; false if analysis was optional and results dropped.
/// </summary>
internal readonly bool RequiredAnalysis;
internal Data(int trackedEntries, bool requiredAnalysis)
{
TrackedEntries = trackedEntries;
RequiredAnalysis = requiredAnalysis;
}
}
/// <summary>
/// Represents the result of visiting an expression.
/// Contains a result type which tells us whether the expression may be null,
/// and an l-value type which tells us whether we can assign null to the expression.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
private readonly struct VisitResult
{
public readonly TypeWithState RValueType;
public readonly TypeWithAnnotations LValueType;
public VisitResult(TypeWithState rValueType, TypeWithAnnotations lValueType)
{
RValueType = rValueType;
LValueType = lValueType;
// https://github.com/dotnet/roslyn/issues/34993: Doesn't hold true for Tuple_Assignment_10. See if we can make it hold true
//Debug.Assert((RValueType.Type is null && LValueType.TypeSymbol is null) ||
// RValueType.Type.Equals(LValueType.TypeSymbol, TypeCompareKind.ConsiderEverything | TypeCompareKind.AllIgnoreOptions));
}
public VisitResult(TypeSymbol? type, NullableAnnotation annotation, NullableFlowState state)
{
RValueType = TypeWithState.Create(type, state);
LValueType = TypeWithAnnotations.Create(type, annotation);
Debug.Assert(TypeSymbol.Equals(RValueType.Type, LValueType.Type, TypeCompareKind.ConsiderEverything));
}
internal string GetDebuggerDisplay() => $"{{LValue: {LValueType.GetDebuggerDisplay()}, RValue: {RValueType.GetDebuggerDisplay()}}}";
}
/// <summary>
/// Represents the result of visiting an argument expression.
/// In addition to storing the <see cref="VisitResult"/>, also stores the <see cref="LocalState"/>
/// for reanalyzing a lambda.
/// </summary>
[DebuggerDisplay("{VisitResult.GetDebuggerDisplay(), nq}")]
private readonly struct VisitArgumentResult
{
public readonly VisitResult VisitResult;
public readonly Optional<LocalState> StateForLambda;
public TypeWithState RValueType => VisitResult.RValueType;
public TypeWithAnnotations LValueType => VisitResult.LValueType;
public VisitArgumentResult(VisitResult visitResult, Optional<LocalState> stateForLambda)
{
VisitResult = visitResult;
StateForLambda = stateForLambda;
}
}
private Variables _variables;
/// <summary>
/// Binder for symbol being analyzed.
/// </summary>
private readonly Binder _binder;
/// <summary>
/// Conversions with nullability and unknown matching any.
/// </summary>
private readonly Conversions _conversions;
/// <summary>
/// 'true' if non-nullable member warnings should be issued at return points.
/// One situation where this is 'false' is when we are analyzing field initializers and there is a constructor symbol in the type.
/// </summary>
private readonly bool _useConstructorExitWarnings;
/// <summary>
/// If true, the parameter types and nullability from _delegateInvokeMethod is used for
/// initial parameter state. If false, the signature of CurrentSymbol is used instead.
/// </summary>
private bool _useDelegateInvokeParameterTypes;
/// <summary>
/// Method signature used for return or parameter types. Distinct from CurrentSymbol signature
/// when CurrentSymbol is a lambda and type is inferred from MethodTypeInferrer.
/// </summary>
private MethodSymbol? _delegateInvokeMethod;
/// <summary>
/// Return statements and the result types from analyzing the returned expressions. Used when inferring lambda return type in MethodTypeInferrer.
/// </summary>
private ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? _returnTypesOpt;
/// <summary>
/// Invalid type, used only to catch Visit methods that do not set
/// _result.Type. See VisitExpressionWithoutStackGuard.
/// </summary>
private static readonly TypeWithState _invalidType = TypeWithState.Create(ErrorTypeSymbol.UnknownResultType, NullableFlowState.NotNull);
/// <summary>
/// Contains the map of expressions to inferred nullabilities and types used by the optional rewriter phase of the
/// compiler.
/// </summary>
private readonly ImmutableDictionary<BoundExpression, (NullabilityInfo Info, TypeSymbol? Type)>.Builder? _analyzedNullabilityMapOpt;
/// <summary>
/// Manages creating snapshots of the walker as appropriate. Null if we're not taking snapshots of
/// this walker.
/// </summary>
private readonly SnapshotManager.Builder? _snapshotBuilderOpt;
// https://github.com/dotnet/roslyn/issues/35043: remove this when all expression are supported
private bool _disableNullabilityAnalysis;
/// <summary>
/// State of method group receivers, used later when analyzing the conversion to a delegate.
/// (Could be replaced by _analyzedNullabilityMapOpt if that map is always available.)
/// </summary>
private PooledDictionary<BoundExpression, TypeWithState>? _methodGroupReceiverMapOpt;
/// <summary>
/// State of awaitable expressions, for substitution in placeholders within GetAwaiter calls.
/// </summary>
private PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>? _awaitablePlaceholdersOpt;
/// <summary>
/// Variables instances for each lambda or local function defined within the analyzed region.
/// </summary>
private PooledDictionary<MethodSymbol, Variables>? _nestedFunctionVariables;
private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>>? _conditionalInfoForConversionOpt;
/// <summary>
/// Map from a target-typed conditional expression (such as a target-typed conditional or switch) to the nullable state on each branch. This
/// is then used by VisitConversion to properly set the state before each branch when visiting a conversion applied to such a construct. These
/// states will be the state after visiting the underlying arm value, but before visiting the conversion on top of the arm value.
/// </summary>
private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>> ConditionalInfoForConversion
=> _conditionalInfoForConversionOpt ??= PooledDictionary<BoundExpression, ImmutableArray<(LocalState, TypeWithState, bool)>>.GetInstance();
/// <summary>
/// True if we're analyzing speculative code. This turns off some initialization steps
/// that would otherwise be taken.
/// </summary>
private readonly bool _isSpeculative;
/// <summary>
/// True if this walker was created using an initial state.
/// </summary>
private readonly bool _hasInitialState;
#if DEBUG
/// <summary>
/// Contains the expressions that should not be inserted into <see cref="_analyzedNullabilityMapOpt"/>.
/// </summary>
private static readonly ImmutableArray<BoundKind> s_skippedExpressions = ImmutableArray.Create(BoundKind.ArrayInitialization,
BoundKind.ObjectInitializerExpression,
BoundKind.CollectionInitializerExpression,
BoundKind.DynamicCollectionElementInitializer);
#endif
/// <summary>
/// The result and l-value type of the last visited expression.
/// </summary>
private VisitResult _visitResult;
/// <summary>
/// The visit result of the receiver for the current conditional access.
///
/// For example: A conditional invocation uses a placeholder as a receiver. By storing the
/// visit result from the actual receiver ahead of time, we can give this placeholder a correct result.
/// </summary>
private VisitResult _currentConditionalReceiverVisitResult;
/// <summary>
/// The result type represents the state of the last visited expression.
/// </summary>
private TypeWithState ResultType
{
get => _visitResult.RValueType;
}
private void SetResultType(BoundExpression? expression, TypeWithState type, bool updateAnalyzedNullability = true)
{
SetResult(expression, resultType: type, lvalueType: type.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: updateAnalyzedNullability);
}
/// <summary>
/// Force the inference of the LValueResultType from ResultType.
/// </summary>
private void UseRvalueOnly(BoundExpression? expression)
{
SetResult(expression, ResultType, ResultType.ToTypeWithAnnotations(compilation), isLvalue: false);
}
private TypeWithAnnotations LvalueResultType
{
get => _visitResult.LValueType;
}
private void SetLvalueResultType(BoundExpression? expression, TypeWithAnnotations type)
{
SetResult(expression, resultType: type.ToTypeWithState(), lvalueType: type);
}
/// <summary>
/// Force the inference of the ResultType from LValueResultType.
/// </summary>
private void UseLvalueOnly(BoundExpression? expression)
{
SetResult(expression, LvalueResultType.ToTypeWithState(), LvalueResultType, isLvalue: true);
}
private void SetInvalidResult() => SetResult(expression: null, _invalidType, _invalidType.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: false);
private void SetResult(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool updateAnalyzedNullability = true, bool? isLvalue = null)
{
_visitResult = new VisitResult(resultType, lvalueType);
if (updateAnalyzedNullability)
{
SetAnalyzedNullability(expression, _visitResult, isLvalue);
}
}
private bool ShouldMakeNotNullRvalue(BoundExpression node) => node.IsSuppressed || node.HasAnyErrors || !IsReachable();
/// <summary>
/// Sets the analyzed nullability of the expression to be the given result.
/// </summary>
private void SetAnalyzedNullability(BoundExpression? expr, VisitResult result, bool? isLvalue = null)
{
if (expr == null || _disableNullabilityAnalysis) return;
#if DEBUG
// https://github.com/dotnet/roslyn/issues/34993: This assert is essential for ensuring that we aren't
// changing the observable results of GetTypeInfo beyond nullability information.
//Debug.Assert(AreCloseEnough(expr.Type, result.RValueType.Type),
// $"Cannot change the type of {expr} from {expr.Type} to {result.RValueType.Type}");
#endif
if (_analyzedNullabilityMapOpt != null)
{
// https://github.com/dotnet/roslyn/issues/34993: enable and verify these assertions
#if false
if (_analyzedNullabilityMapOpt.TryGetValue(expr, out var existing))
{
if (!(result.RValueType.State == NullableFlowState.NotNull && ShouldMakeNotNullRvalue(expr, State.Reachable)))
{
switch (isLvalue)
{
case true:
Debug.Assert(existing.Info.Annotation == result.LValueType.NullableAnnotation.ToPublicAnnotation(),
$"Tried to update the nullability of {expr} from {existing.Info.Annotation} to {result.LValueType.NullableAnnotation}");
break;
case false:
Debug.Assert(existing.Info.FlowState == result.RValueType.State,
$"Tried to update the nullability of {expr} from {existing.Info.FlowState} to {result.RValueType.State}");
break;
case null:
Debug.Assert(existing.Info.Equals((NullabilityInfo)result),
$"Tried to update the nullability of {expr} from ({existing.Info.Annotation}, {existing.Info.FlowState}) to ({result.LValueType.NullableAnnotation}, {result.RValueType.State})");
break;
}
}
}
#endif
_analyzedNullabilityMapOpt[expr] = (new NullabilityInfo(result.LValueType.ToPublicAnnotation(), result.RValueType.State.ToPublicFlowState()),
// https://github.com/dotnet/roslyn/issues/35046 We're dropping the result if the type doesn't match up completely
// with the existing type
expr.Type?.Equals(result.RValueType.Type, TypeCompareKind.AllIgnoreOptions) == true ? result.RValueType.Type : expr.Type);
}
}
/// <summary>
/// Placeholder locals, e.g. for objects being constructed.
/// </summary>
private PooledDictionary<object, PlaceholderLocal>? _placeholderLocalsOpt;
/// <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;
/// <summary>
/// Whether we are going to read the currently visited expression.
/// </summary>
private bool _expressionIsRead = true;
/// <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;
private bool IsAnalyzingAttribute => methodMainNode.Kind == BoundKind.Attribute;
protected override void Free()
{
_nestedFunctionVariables?.Free();
_awaitablePlaceholdersOpt?.Free();
_methodGroupReceiverMapOpt?.Free();
_placeholderLocalsOpt?.Free();
_variables.Free();
Debug.Assert(_conditionalInfoForConversionOpt is null or { Count: 0 });
_conditionalInfoForConversionOpt?.Free();
base.Free();
}
private NullableWalker(
CSharpCompilation compilation,
Symbol? symbol,
bool useConstructorExitWarnings,
bool useDelegateInvokeParameterTypes,
MethodSymbol? delegateInvokeMethodOpt,
BoundNode node,
Binder binder,
Conversions conversions,
Variables? variables,
ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt,
ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt,
SnapshotManager.Builder? snapshotBuilderOpt,
bool isSpeculative = false)
: base(compilation, symbol, node, EmptyStructTypeCache.CreatePrecise(), trackUnassignments: true)
{
Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethodOpt is object);
_variables = variables ?? Variables.Create(symbol);
_binder = binder;
_conversions = (Conversions)conversions.WithNullability(true);
_useConstructorExitWarnings = useConstructorExitWarnings;
_useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes;
_delegateInvokeMethod = delegateInvokeMethodOpt;
_analyzedNullabilityMapOpt = analyzedNullabilityMapOpt;
_returnTypesOpt = returnTypesOpt;
_snapshotBuilderOpt = snapshotBuilderOpt;
_isSpeculative = isSpeculative;
_hasInitialState = variables is { };
}
public string GetDebuggerDisplay()
{
if (this.IsConditionalState)
{
return $"{{{GetType().Name} WhenTrue:{Dump(StateWhenTrue)} WhenFalse:{Dump(StateWhenFalse)}{"}"}";
}
else
{
return $"{{{GetType().Name} {Dump(State)}{"}"}";
}
}
// For purpose of nullability analysis, awaits create pending branches, so async usings and foreachs do too
public sealed override bool AwaitUsingAndForeachAddsPendingBranch => true;
protected override void EnsureSufficientExecutionStack(int recursionDepth)
{
if (recursionDepth > StackGuard.MaxUncheckedRecursionDepth &&
compilation.NullableAnalysisData is { MaxRecursionDepth: var depth } &&
depth > 0 &&
recursionDepth > depth)
{
throw new InsufficientExecutionStackException();
}
base.EnsureSufficientExecutionStack(recursionDepth);
}
protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()
{
return true;
}
protected override bool TryGetVariable(VariableIdentifier identifier, out int slot)
{
return _variables.TryGetValue(identifier, out slot);
}
protected override int AddVariable(VariableIdentifier identifier)
{
return _variables.Add(identifier);
}
protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion)
{
if (_returnTypesOpt != null)
{
_returnTypesOpt.Clear();
}
this.Diagnostics.Clear();
this.regionPlace = RegionPlace.Before;
if (!_isSpeculative)
{
ParameterSymbol methodThisParameter = MethodThisParameter;
EnterParameters(); // assign parameters
if (methodThisParameter is object)
{
EnterParameter(methodThisParameter, methodThisParameter.TypeWithAnnotations);
}
makeNotNullMembersMaybeNull();
// We need to create a snapshot even of the first node, because we want to have the state of the initial parameters.
_snapshotBuilderOpt?.TakeIncrementalSnapshot(methodMainNode, State);
}
ImmutableArray<PendingBranch> pendingReturns = base.Scan(ref badRegion);
if ((_symbol as MethodSymbol)?.IsConstructor() != true || _useConstructorExitWarnings)
{
EnforceDoesNotReturn(syntaxOpt: null);
enforceMemberNotNull(syntaxOpt: null, this.State);
enforceNotNull(null, this.State);
foreach (var pendingReturn in pendingReturns)
{
enforceMemberNotNull(syntaxOpt: pendingReturn.Branch.Syntax, pendingReturn.State);
if (pendingReturn.Branch is BoundReturnStatement returnStatement)
{
enforceNotNull(returnStatement.Syntax, pendingReturn.State);
enforceNotNullWhenForPendingReturn(pendingReturn, returnStatement);
enforceMemberNotNullWhenForPendingReturn(pendingReturn, returnStatement);
}
}
}
return pendingReturns;
void enforceMemberNotNull(SyntaxNode? syntaxOpt, LocalState state)
{
if (!state.Reachable)
{
return;
}
var method = _symbol as MethodSymbol;
if (method is object)
{
if (method.IsConstructor())
{
Debug.Assert(_useConstructorExitWarnings);
var thisSlot = 0;
if (method.RequiresInstanceReceiver)
{
method.TryGetThisParameter(out var thisParameter);
Debug.Assert(thisParameter is object);
thisSlot = GetOrCreateSlot(thisParameter);
}
// https://github.com/dotnet/roslyn/issues/46718: give diagnostics on return points, not constructor signature
var exitLocation = method.DeclaringSyntaxReferences.IsEmpty ? null : method.Locations.FirstOrDefault();
foreach (var member in method.ContainingType.GetMembersUnordered())
{
checkMemberStateOnConstructorExit(method, member, state, thisSlot, exitLocation);
}
}
else
{
do
{
foreach (var memberName in method.NotNullMembers)
{
enforceMemberNotNullOnMember(syntaxOpt, state, method, memberName);
}
method = method.OverriddenMethod;
}
while (method != null);
}
}
}
void checkMemberStateOnConstructorExit(MethodSymbol constructor, Symbol member, LocalState state, int thisSlot, Location? exitLocation)
{
var isStatic = !constructor.RequiresInstanceReceiver();
if (member.IsStatic != isStatic)
{
return;
}
// This is not required for correctness, but in the case where the member has
// an initializer, we know we've assigned to the member and
// have given any applicable warnings about a bad value going in.
// Therefore we skip this check when the member has an initializer to reduce noise.
if (HasInitializer(member))
{
return;
}
TypeWithAnnotations fieldType;
FieldSymbol? field;
Symbol symbol;
switch (member)
{
case FieldSymbol f:
fieldType = f.TypeWithAnnotations;
field = f;
symbol = (Symbol?)(f.AssociatedSymbol as PropertySymbol) ?? f;
break;
case EventSymbol e:
fieldType = e.TypeWithAnnotations;
field = e.AssociatedField;
symbol = e;
if (field is null)
{
return;
}
break;
default:
return;
}
if (field.IsConst)
{
return;
}
if (fieldType.Type.IsValueType || fieldType.Type.IsErrorType())
{
return;
}
var annotations = symbol.GetFlowAnalysisAnnotations();
if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0)
{
// We assume that if a member has AllowNull then the user
// does not care that we exit at a point where the member might be null.
return;
}
fieldType = ApplyUnconditionalAnnotations(fieldType, annotations);
if (!fieldType.NullableAnnotation.IsNotAnnotated())
{
return;
}
var slot = GetOrCreateSlot(symbol, thisSlot);
if (slot < 0)
{
return;
}
var memberState = state[slot];
var badState = fieldType.Type.IsPossiblyNullableReferenceTypeTypeParameter() && (annotations & FlowAnalysisAnnotations.NotNull) == 0
? NullableFlowState.MaybeDefault
: NullableFlowState.MaybeNull;
if (memberState >= badState) // is 'memberState' as bad as or worse than 'badState'?
{
Diagnostics.Add(ErrorCode.WRN_UninitializedNonNullableField, exitLocation ?? symbol.Locations.FirstOrNone(), symbol.Kind.Localize(), symbol.Name);
}
}
void enforceMemberNotNullOnMember(SyntaxNode? syntaxOpt, LocalState state, MethodSymbol method, string memberName)
{
foreach (var member in method.ContainingType.GetMembers(memberName))
{
if (memberHasBadState(member, state))
{
// Member '{name}' must have a non-null value when exiting.
Diagnostics.Add(ErrorCode.WRN_MemberNotNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name);
}
}
}
void enforceMemberNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement)
{
if (pendingReturn.IsConditionalState)
{
if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } })
{
enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State);
return;
}
if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable)
{
return;
}
if (_symbol is MethodSymbol method)
{
foreach (var memberName in method.NotNullWhenTrueMembers)
{
enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: true, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenTrue, pendingReturn.StateWhenFalse);
}
foreach (var memberName in method.NotNullWhenFalseMembers)
{
enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: false, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenFalse, pendingReturn.StateWhenTrue);
}
}
}
else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } })
{
enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State);
}
}
void enforceMemberNotNullWhenIfAffected(SyntaxNode? syntaxOpt, bool sense, ImmutableArray<Symbol> members, LocalState state, LocalState otherState)
{
foreach (var member in members)
{
// For non-constant values, only complain if we were able to analyze a difference for this member between two branches
if (memberHasBadState(member, state) != memberHasBadState(member, otherState))
{
reportMemberIfBadConditionalState(syntaxOpt, sense, member, state);
}
}
}
void enforceMemberNotNullWhen(SyntaxNode? syntaxOpt, bool sense, LocalState state)
{
if (_symbol is MethodSymbol method)
{
var notNullMembers = sense ? method.NotNullWhenTrueMembers : method.NotNullWhenFalseMembers;
foreach (var memberName in notNullMembers)
{
foreach (var member in method.ContainingType.GetMembers(memberName))
{
reportMemberIfBadConditionalState(syntaxOpt, sense, member, state);
}
}
}
}
void reportMemberIfBadConditionalState(SyntaxNode? syntaxOpt, bool sense, Symbol member, LocalState state)
{
if (memberHasBadState(member, state))
{
// Member '{name}' must have a non-null value when exiting with '{sense}'.
Diagnostics.Add(ErrorCode.WRN_MemberNotNullWhen, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name, sense ? "true" : "false");
}
}
bool memberHasBadState(Symbol member, LocalState state)
{
switch (member.Kind)
{
case SymbolKind.Field:
case SymbolKind.Property:
if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot &&
memberSlot > 0)
{
var parameterState = state[memberSlot];
return !parameterState.IsNotNull();
}
else
{
return false;
}
case SymbolKind.Event:
case SymbolKind.Method:
break;
}
return false;
}
void makeNotNullMembersMaybeNull()
{
if (_symbol is MethodSymbol method)
{
if (method.IsConstructor())
{
if (needsDefaultInitialStateForMembers())
{
foreach (var member in method.ContainingType.GetMembersUnordered())
{
if (member.IsStatic != method.IsStatic)
{
continue;
}
var memberToInitialize = member;
switch (member)
{
case PropertySymbol:
// skip any manually implemented properties.
continue;
case FieldSymbol { IsConst: true }:
continue;
case FieldSymbol { AssociatedSymbol: PropertySymbol prop }:
// this is a property where assigning 'default' causes us to simply update
// the state to the output state of the property
// thus we skip setting an initial state for it here
if (IsPropertyOutputMoreStrictThanInput(prop))
{
continue;
}
// We want to initialize auto-property state to the default state, but not computed properties.
memberToInitialize = prop;
break;
default:
break;
}
var memberSlot = getSlotForFieldOrPropertyOrEvent(memberToInitialize);
if (memberSlot > 0)
{
var type = memberToInitialize.GetTypeOrReturnType();
if (!type.NullableAnnotation.IsOblivious())
{
this.State[memberSlot] = type.Type.IsPossiblyNullableReferenceTypeTypeParameter() ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull;
}
}
}
}
}
else
{
do
{
makeMembersMaybeNull(method, method.NotNullMembers);
makeMembersMaybeNull(method, method.NotNullWhenTrueMembers);
makeMembersMaybeNull(method, method.NotNullWhenFalseMembers);
method = method.OverriddenMethod;
}
while (method != null);
}
}
bool needsDefaultInitialStateForMembers()
{
if (_hasInitialState)
{
return false;
}
// We don't use a default initial state for value type instance constructors without `: this()` because
// any usages of uninitialized fields will get definite assignment errors anyway.
if (!method.HasThisConstructorInitializer() && (!method.ContainingType.IsValueType || method.IsStatic))
{
return true;
}
return methodMainNode is BoundConstructorMethodBody ctorBody
&& ctorBody.Initializer?.Expression.ExpressionSymbol is MethodSymbol delegatedCtor
&& delegatedCtor.IsDefaultValueTypeConstructor();
}
}
void makeMembersMaybeNull(MethodSymbol method, ImmutableArray<string> members)
{
foreach (var memberName in members)
{
makeMemberMaybeNull(method, memberName);
}
}
void makeMemberMaybeNull(MethodSymbol method, string memberName)
{
var type = method.ContainingType;
foreach (var member in type.GetMembers(memberName))
{
if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot &&
memberSlot > 0)
{
this.State[memberSlot] = NullableFlowState.MaybeNull;
}
}
}
void enforceNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement)
{
var parameters = this.MethodParameters;
if (!parameters.IsEmpty)
{
if (pendingReturn.IsConditionalState)
{
if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } })
{
enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State);
return;
}
if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable)
{
return;
}
foreach (var parameter in parameters)
{
// For non-constant values, only complain if we were able to analyze a difference for this parameter between two branches
if (GetOrCreateSlot(parameter) is > 0 and var slot && pendingReturn.StateWhenTrue[slot] != pendingReturn.StateWhenFalse[slot])
{
reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: true, stateWhen: pendingReturn.StateWhenTrue);
reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: false, stateWhen: pendingReturn.StateWhenFalse);
}
}
}
else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } })
{
// example: return (bool)true;
enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State);
return;
}
}
}
void reportParameterIfBadConditionalState(SyntaxNode syntax, ParameterSymbol parameter, bool sense, LocalState stateWhen)
{
if (parameterHasBadConditionalState(parameter, sense, stateWhen))
{
// Parameter '{name}' must have a non-null value when exiting with '{sense}'.
Diagnostics.Add(ErrorCode.WRN_ParameterConditionallyDisallowsNull, syntax.Location, parameter.Name, sense ? "true" : "false");
}
}
void enforceNotNull(SyntaxNode? syntaxOpt, LocalState state)
{
if (!state.Reachable)
{
return;
}
foreach (var parameter in this.MethodParameters)
{
var slot = GetOrCreateSlot(parameter);
if (slot <= 0)
{
continue;
}
var annotations = parameter.FlowAnalysisAnnotations;
var hasNotNull = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull;
var parameterState = state[slot];
if (hasNotNull && parameterState.MayBeNull())
{
// Parameter '{name}' must have a non-null value when exiting.
Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), parameter.Name);
}
else
{
EnforceNotNullIfNotNull(syntaxOpt, state, this.MethodParameters, parameter.NotNullIfParameterNotNull, parameterState, parameter);
}
}
}
void enforceParameterNotNullWhen(SyntaxNode syntax, ImmutableArray<ParameterSymbol> parameters, bool sense, LocalState stateWhen)
{
if (!stateWhen.Reachable)
{
return;
}
foreach (var parameter in parameters)
{
reportParameterIfBadConditionalState(syntax, parameter, sense, stateWhen);
}
}
bool parameterHasBadConditionalState(ParameterSymbol parameter, bool sense, LocalState stateWhen)
{
var refKind = parameter.RefKind;
if (refKind != RefKind.Out && refKind != RefKind.Ref)
{
return false;
}
var slot = GetOrCreateSlot(parameter);
if (slot > 0)
{
var parameterState = stateWhen[slot];
// On a parameter marked with MaybeNullWhen, we would have not reported an assignment warning.
// We should only check if an assignment warning would have been warranted ignoring the MaybeNullWhen.
FlowAnalysisAnnotations annotations = parameter.FlowAnalysisAnnotations;
if (sense)
{
bool hasNotNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenTrue;
bool hasMaybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenFalse;
return (hasNotNullWhenTrue && parameterState.MayBeNull()) ||
(hasMaybeNullWhenFalse && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState));
}
else
{
bool hasNotNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenFalse;
bool hasMaybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenTrue;
return (hasNotNullWhenFalse && parameterState.MayBeNull()) ||
(hasMaybeNullWhenTrue && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState));
}
}
return false;
}
int getSlotForFieldOrPropertyOrEvent(Symbol member)
{
if (member.Kind != SymbolKind.Field &&
member.Kind != SymbolKind.Property &&
member.Kind != SymbolKind.Event)
{
return -1;
}
int containingSlot = 0;
if (!member.IsStatic)
{
if (MethodThisParameter is null)
{
return -1;
}
containingSlot = GetOrCreateSlot(MethodThisParameter);
if (containingSlot < 0)
{
return -1;
}
Debug.Assert(containingSlot > 0);
}
return GetOrCreateSlot(member, containingSlot);
}
}
private void EnforceNotNullIfNotNull(SyntaxNode? syntaxOpt, LocalState state, ImmutableArray<ParameterSymbol> parameters, ImmutableHashSet<string> inputParamNames, NullableFlowState outputState, ParameterSymbol? outputParam)
{
if (inputParamNames.IsEmpty || outputState.IsNotNull())
{
return;
}
foreach (var inputParam in parameters)
{
if (inputParamNames.Contains(inputParam.Name)
&& GetOrCreateSlot(inputParam) is > 0 and int inputSlot
&& state[inputSlot].IsNotNull())
{
var location = syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation();
if (outputParam is object)
{
// Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null.
Diagnostics.Add(ErrorCode.WRN_ParameterNotNullIfNotNull, location, outputParam.Name, inputParam.Name);
}
else if (CurrentSymbol is MethodSymbol { IsAsync: false })
{
// Return value must be non-null because parameter '{0}' is non-null.
Diagnostics.Add(ErrorCode.WRN_ReturnNotNullIfNotNull, location, inputParam.Name);
}