-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathBinder.ValueChecks.cs
4841 lines (4147 loc) · 221 KB
/
Binder.ValueChecks.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
#nullable enable
internal partial class RefSafetyAnalysis
{
private enum EscapeLevel : uint
{
CallingMethod = CallingMethodScope,
ReturnOnly = ReturnOnlyScope,
}
/// <summary>
/// The destination in a method arguments must match (MAMM) check. This is
/// created primarily for ref and out arguments of a ref struct. It also applies
/// to function pointer this and arglist arguments.
/// </summary>
private readonly struct MixableDestination
{
internal BoundExpression Argument { get; }
/// <summary>
/// In the case this is the argument for a ref / out parameter this will refer
/// to the corresponding parameter. This will be null in cases like arguments
/// passed to an arglist.
/// </summary>
internal ParameterSymbol? Parameter { get; }
/// <summary>
/// This destination can only be written to by arguments that have an equal or
/// wider escape level. An destination that is <see cref="EscapeLevel.CallingMethod"/>
/// can never be written to by an argument that has a level of <see cref="EscapeLevel.ReturnOnly"/>.
/// </summary>
internal EscapeLevel EscapeLevel { get; }
internal MixableDestination(ParameterSymbol parameter, BoundExpression argument)
{
Debug.Assert(parameter.RefKind.IsWritableReference() && parameter.Type.IsRefLikeType);
Debug.Assert(GetParameterValEscapeLevel(parameter).HasValue);
Argument = argument;
Parameter = parameter;
EscapeLevel = GetParameterValEscapeLevel(parameter)!.Value;
}
internal MixableDestination(BoundExpression argument, EscapeLevel escapeLevel)
{
Argument = argument;
Parameter = null;
EscapeLevel = escapeLevel;
}
internal bool IsAssignableFrom(EscapeLevel level) => EscapeLevel switch
{
EscapeLevel.CallingMethod => level == EscapeLevel.CallingMethod,
EscapeLevel.ReturnOnly => true,
_ => throw ExceptionUtilities.UnexpectedValue(EscapeLevel)
};
public override string? ToString() => (Parameter, Argument, EscapeLevel).ToString();
}
/// <summary>
/// Represents an argument being analyzed for escape analysis purposes. This represents the
/// argument as written. For example a `ref x` will only be represented by a single
/// <see cref="EscapeArgument"/>.
/// </summary>
private readonly struct EscapeArgument
{
/// <summary>
/// This will be null in cases like arglist or a function pointer receiver.
/// </summary>
internal ParameterSymbol? Parameter { get; }
internal BoundExpression Argument { get; }
internal RefKind RefKind { get; }
internal EscapeArgument(ParameterSymbol? parameter, BoundExpression argument, RefKind refKind, bool isArgList = false)
{
Debug.Assert(!isArgList || parameter is null);
Argument = argument;
Parameter = parameter;
RefKind = refKind;
}
public void Deconstruct(out ParameterSymbol? parameter, out BoundExpression argument, out RefKind refKind)
{
parameter = Parameter;
argument = Argument;
refKind = RefKind;
}
public override string? ToString() => Parameter is { } p
? p.ToString()
: Argument.ToString();
}
/// <summary>
/// Represents a value being analyzed for escape analysis purposes. This represents the value
/// as it contributes to escape analysis which means arguments can show up multiple times. For
/// example `ref x` will be represented as both a val and ref escape.
/// </summary>
private readonly struct EscapeValue
{
/// <summary>
/// This will be null in cases like arglist or a function pointer receiver.
/// </summary>
internal ParameterSymbol? Parameter { get; }
internal BoundExpression Argument { get; }
/// <summary>
/// This is _only_ useful when calculating MAMM as it dictates to what level the value
/// escaped to. That allows it to be filtered against the parameters it could possibly
/// write to.
/// </summary>
internal EscapeLevel EscapeLevel { get; }
internal bool IsRefEscape { get; }
internal EscapeValue(ParameterSymbol? parameter, BoundExpression argument, EscapeLevel escapeLevel, bool isRefEscape)
{
Argument = argument;
Parameter = parameter;
EscapeLevel = escapeLevel;
IsRefEscape = isRefEscape;
}
public void Deconstruct(out ParameterSymbol? parameter, out BoundExpression argument, out EscapeLevel escapeLevel, out bool isRefEscape)
{
parameter = Parameter;
argument = Argument;
escapeLevel = EscapeLevel;
isRefEscape = IsRefEscape;
}
public override string? ToString() => Parameter is { } p
? p.ToString()
: Argument.ToString();
}
/// <summary>
/// For the purpose of escape verification we operate with the depth of local scopes.
/// The depth is a uint, with smaller number representing shallower/wider scopes.
/// 0, 1 and 2 are special scopes -
/// 0 is the "calling method" scope that is outside of the containing method/lambda.
/// If something can escape to scope 0, it can escape to any scope in a given method through a ref parameter or return.
/// 1 is the "return-only" scope that is outside of the containing method/lambda.
/// If something can escape to scope 1, it can escape to any scope in a given method or can be returned, but it can't escape through a ref parameter.
/// 2 is the "current method" scope that is just inside the containing method/lambda.
/// If something can escape to scope 1, it can escape to any scope in a given method, but cannot be returned.
/// n + 1 corresponds to scopes immediately inside a scope of depth n.
/// Since sibling scopes do not intersect and a value cannot escape from one to another without
/// escaping to a wider scope, we can use simple depth numbering without ambiguity.
/// </summary>
private const uint CallingMethodScope = 0;
private const uint ReturnOnlyScope = 1;
private const uint CurrentMethodScope = 2;
}
#nullable disable
internal partial class Binder
{
// Some value kinds are semantically the same and the only distinction is how errors are reported
// for those purposes we reserve lowest 2 bits
private const int ValueKindInsignificantBits = 2;
private const BindValueKind ValueKindSignificantBitsMask = unchecked((BindValueKind)~((1 << ValueKindInsignificantBits) - 1));
/// <summary>
/// Expression capabilities and requirements.
/// </summary>
[Flags]
internal enum BindValueKind : ushort
{
///////////////////
// All expressions can be classified according to the following 4 capabilities:
//
/// <summary>
/// Expression can be an RHS of an assignment operation.
/// </summary>
/// <remarks>
/// The following are rvalues: values, variables, null literals, properties
/// and indexers with getters, events.
///
/// The following are not rvalues:
/// namespaces, types, method groups, anonymous functions.
/// </remarks>
RValue = 1 << ValueKindInsignificantBits,
/// <summary>
/// Expression can be the LHS of a simple assignment operation.
/// Example:
/// property with a setter
/// </summary>
Assignable = 2 << ValueKindInsignificantBits,
/// <summary>
/// Expression represents a location. Often referred as a "variable"
/// Examples:
/// local variable, parameter, field
/// </summary>
RefersToLocation = 4 << ValueKindInsignificantBits,
/// <summary>
/// Expression can be the LHS of a ref-assign operation.
/// Example:
/// ref local, ref parameter, out parameter, ref field
/// </summary>
RefAssignable = 8 << ValueKindInsignificantBits,
///////////////////
// The rest are just combinations of the above.
//
/// <summary>
/// Expression is the RHS of an assignment operation
/// and may be a method group.
/// Basically an RValue, but could be treated differently for the purpose of error reporting
/// </summary>
RValueOrMethodGroup = RValue + 1,
/// <summary>
/// Expression can be an LHS of a compound assignment
/// operation (such as +=).
/// </summary>
CompoundAssignment = RValue | Assignable,
/// <summary>
/// Expression can be the operand of an increment or decrement operation.
/// Same as CompoundAssignment, the distinction is really just for error reporting.
/// </summary>
IncrementDecrement = CompoundAssignment + 1,
/// <summary>
/// Expression is a r/o reference.
/// </summary>
ReadonlyRef = RefersToLocation | RValue,
/// <summary>
/// Expression can be the operand of an address-of operation (&).
/// Same as ReadonlyRef. The difference is just for error reporting.
/// </summary>
AddressOf = ReadonlyRef + 1,
/// <summary>
/// Expression is the receiver of a fixed buffer field access
/// Same as ReadonlyRef. The difference is just for error reporting.
/// </summary>
FixedReceiver = ReadonlyRef + 2,
/// <summary>
/// Expression is passed as a ref or out parameter or assigned to a byref variable.
/// </summary>
RefOrOut = RefersToLocation | RValue | Assignable,
/// <summary>
/// Expression is returned by an ordinary r/w reference.
/// Same as RefOrOut. The difference is just for error reporting.
/// </summary>
RefReturn = RefOrOut + 1,
}
private static bool RequiresRValueOnly(BindValueKind kind)
{
return (kind & ValueKindSignificantBitsMask) == BindValueKind.RValue;
}
private static bool RequiresAssignmentOnly(BindValueKind kind)
{
return (kind & ValueKindSignificantBitsMask) == BindValueKind.Assignable;
}
private static bool RequiresVariable(BindValueKind kind)
{
return !RequiresRValueOnly(kind);
}
private static bool RequiresReferenceToLocation(BindValueKind kind)
{
return (kind & BindValueKind.RefersToLocation) != 0;
}
private static bool RequiresAssignableVariable(BindValueKind kind)
{
return (kind & BindValueKind.Assignable) != 0;
}
private static bool RequiresRefAssignableVariable(BindValueKind kind)
{
return (kind & BindValueKind.RefAssignable) != 0;
}
private static bool RequiresRefOrOut(BindValueKind kind)
{
return (kind & BindValueKind.RefOrOut) == BindValueKind.RefOrOut;
}
#nullable enable
private BoundIndexerAccess BindIndexerDefaultArguments(BoundIndexerAccess indexerAccess, BindValueKind valueKind, BindingDiagnosticBag diagnostics)
{
var useSetAccessor = valueKind == BindValueKind.Assignable && !indexerAccess.Indexer.ReturnsByRef;
var accessorForDefaultArguments = useSetAccessor
? indexerAccess.Indexer.GetOwnOrInheritedSetMethod()
: indexerAccess.Indexer.GetOwnOrInheritedGetMethod();
if (accessorForDefaultArguments is not null)
{
var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(accessorForDefaultArguments.ParameterCount);
argumentsBuilder.AddRange(indexerAccess.Arguments);
ArrayBuilder<RefKind>? refKindsBuilderOpt;
if (!indexerAccess.ArgumentRefKindsOpt.IsDefaultOrEmpty)
{
refKindsBuilderOpt = ArrayBuilder<RefKind>.GetInstance(accessorForDefaultArguments.ParameterCount);
refKindsBuilderOpt.AddRange(indexerAccess.ArgumentRefKindsOpt);
}
else
{
refKindsBuilderOpt = null;
}
var argsToParams = indexerAccess.ArgsToParamsOpt;
// It is possible for the indexer 'value' parameter from metadata to have a default value, but the compiler will not use it.
// However, we may still use any default values from the preceding parameters.
var parameters = accessorForDefaultArguments.Parameters;
if (useSetAccessor)
{
parameters = parameters.RemoveAt(parameters.Length - 1);
}
BitVector defaultArguments = default;
Debug.Assert(parameters.Length == indexerAccess.Indexer.Parameters.Length);
// If OriginalIndexersOpt is set, there was an overload resolution failure, and we don't want to make guesses about the default
// arguments that will end up being reflected in the SemanticModel/IOperation
if (indexerAccess.OriginalIndexersOpt.IsDefault)
{
BindDefaultArguments(indexerAccess.Syntax, parameters, argumentsBuilder, refKindsBuilderOpt, ref argsToParams, out defaultArguments, indexerAccess.Expanded, enableCallerInfo: true, diagnostics);
}
indexerAccess = indexerAccess.Update(
indexerAccess.ReceiverOpt,
indexerAccess.Indexer,
argumentsBuilder.ToImmutableAndFree(),
indexerAccess.ArgumentNamesOpt,
refKindsBuilderOpt?.ToImmutableOrNull() ?? default,
indexerAccess.Expanded,
argsToParams,
defaultArguments,
indexerAccess.Type);
refKindsBuilderOpt?.Free();
}
return indexerAccess;
}
#nullable disable
/// <summary>
/// Check the expression is of the required lvalue and rvalue specified by valueKind.
/// The method returns the original expression if the expression is of the required
/// type. Otherwise, an appropriate error is added to the diagnostics bag and the
/// method returns a BoundBadExpression node. The method returns the original
/// expression without generating any error if the expression has errors.
/// </summary>
private BoundExpression CheckValue(BoundExpression expr, BindValueKind valueKind, BindingDiagnosticBag diagnostics)
{
switch (expr.Kind)
{
case BoundKind.PropertyGroup:
expr = BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics: diagnostics);
if (expr is BoundIndexerAccess indexerAccess)
{
expr = BindIndexerDefaultArguments(indexerAccess, valueKind, diagnostics);
}
break;
case BoundKind.Local:
Debug.Assert(expr.Syntax.Kind() != SyntaxKind.Argument || valueKind == BindValueKind.RefOrOut);
break;
case BoundKind.OutVariablePendingInference:
case BoundKind.OutDeconstructVarPendingInference:
Debug.Assert(valueKind == BindValueKind.RefOrOut);
return expr;
case BoundKind.DiscardExpression:
Debug.Assert(valueKind is (BindValueKind.Assignable or BindValueKind.RefOrOut or BindValueKind.RefAssignable) || diagnostics.DiagnosticBag is null || diagnostics.HasAnyResolvedErrors());
return expr;
case BoundKind.IndexerAccess:
expr = BindIndexerDefaultArguments((BoundIndexerAccess)expr, valueKind, diagnostics);
break;
case BoundKind.UnconvertedObjectCreationExpression:
if (valueKind == BindValueKind.RValue)
{
return expr;
}
break;
case BoundKind.PointerIndirectionOperator:
if ((valueKind & BindValueKind.RefersToLocation) == BindValueKind.RefersToLocation)
{
var pointerIndirection = (BoundPointerIndirectionOperator)expr;
expr = pointerIndirection.Update(pointerIndirection.Operand, refersToLocation: true, pointerIndirection.Type);
}
break;
case BoundKind.PointerElementAccess:
if ((valueKind & BindValueKind.RefersToLocation) == BindValueKind.RefersToLocation)
{
var elementAccess = (BoundPointerElementAccess)expr;
expr = elementAccess.Update(elementAccess.Expression, elementAccess.Index, elementAccess.Checked, refersToLocation: true, elementAccess.Type);
}
break;
}
bool hasResolutionErrors = false;
// If this a MethodGroup where an rvalue is not expected or where the caller will not explicitly handle
// (and resolve) MethodGroups (in short, cases where valueKind != BindValueKind.RValueOrMethodGroup),
// resolve the MethodGroup here to generate the appropriate errors, otherwise resolution errors (such as
// "member is inaccessible") will be dropped.
if (expr.Kind == BoundKind.MethodGroup && valueKind != BindValueKind.RValueOrMethodGroup)
{
var methodGroup = (BoundMethodGroup)expr;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo);
diagnostics.Add(expr.Syntax, useSiteInfo);
Symbol otherSymbol = null;
bool resolvedToMethodGroup = resolution.MethodGroup != null;
if (!expr.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading.
hasResolutionErrors = resolution.HasAnyErrors;
if (hasResolutionErrors)
{
otherSymbol = resolution.OtherSymbol;
}
resolution.Free();
// It's possible the method group is not a method group at all, but simply a
// delayed lookup that resolved to a non-method member (perhaps an inaccessible
// field or property), or nothing at all. In those cases, the member should not be exposed as a
// method group, not even within a BoundBadExpression. Instead, the
// BoundBadExpression simply refers to the receiver and the resolved symbol (if any).
if (!resolvedToMethodGroup)
{
Debug.Assert(methodGroup.ResultKind != LookupResultKind.Viable);
var receiver = methodGroup.ReceiverOpt;
if ((object)otherSymbol != null && receiver?.Kind == BoundKind.TypeOrValueExpression)
{
// Since we're not accessing a method, this can't be a Color Color case, so TypeOrValueExpression should not have been used.
// CAVEAT: otherSymbol could be invalid in some way (e.g. inaccessible), in which case we would have fallen back on a
// method group lookup (to allow for extension methods), which would have required a TypeOrValueExpression.
Debug.Assert(methodGroup.LookupError != null);
// Since we have a concrete member in hand, we can resolve the receiver.
var typeOrValue = (BoundTypeOrValueExpression)receiver;
receiver = otherSymbol.RequiresInstanceReceiver()
? typeOrValue.Data.ValueExpression
: null; // no receiver required
}
return new BoundBadExpression(
expr.Syntax,
methodGroup.ResultKind,
(object)otherSymbol == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(otherSymbol),
receiver == null ? ImmutableArray<BoundExpression>.Empty : ImmutableArray.Create(receiver),
GetNonMethodMemberType(otherSymbol));
}
}
if (!hasResolutionErrors && CheckValueKind(expr.Syntax, expr, valueKind, checkingReceiver: false, diagnostics: diagnostics) ||
expr.HasAnyErrors && valueKind == BindValueKind.RValueOrMethodGroup)
{
return expr;
}
var resultKind = (valueKind == BindValueKind.RValue || valueKind == BindValueKind.RValueOrMethodGroup) ?
LookupResultKind.NotAValue :
LookupResultKind.NotAVariable;
return ToBadExpression(expr, resultKind);
}
internal static bool IsTypeOrValueExpression(BoundExpression expression)
{
switch (expression?.Kind)
{
case BoundKind.TypeOrValueExpression:
case BoundKind.QueryClause when ((BoundQueryClause)expression).Value.Kind == BoundKind.TypeOrValueExpression:
return true;
default:
return false;
}
}
/// <summary>
/// The purpose of this method is to determine if the expression satisfies desired capabilities.
/// If it is not then this code gives an appropriate error message.
///
/// To determine the appropriate error message we need to know two things:
///
/// (1) What capabilities we need - increment it, assign, return as a readonly reference, . . . ?
///
/// (2) Are we trying to determine if the left hand side of a dot is a variable in order
/// to determine if the field or property on the right hand side of a dot is assignable?
///
/// (3) The syntax of the expression that started the analysis. (for error reporting purposes).
/// </summary>
internal bool CheckValueKind(SyntaxNode node, BoundExpression expr, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter());
if (expr.HasAnyErrors)
{
return false;
}
switch (expr.Kind)
{
// we need to handle properties and event in a special way even in an RValue case because of getters
case BoundKind.PropertyAccess:
case BoundKind.IndexerAccess:
case BoundKind.ImplicitIndexerAccess when ((BoundImplicitIndexerAccess)expr).IndexerOrSliceAccess.Kind == BoundKind.IndexerAccess:
return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics);
case BoundKind.EventAccess:
return CheckEventValueKind((BoundEventAccess)expr, valueKind, diagnostics);
}
// easy out for a very common RValue case.
if (RequiresRValueOnly(valueKind))
{
return CheckNotNamespaceOrType(expr, diagnostics);
}
// constants/literals are strictly RValues
// void is not even an RValue
if ((expr.ConstantValueOpt != null) || (expr.Type.GetSpecialTypeSafe() == SpecialType.System_Void))
{
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
switch (expr.Kind)
{
case BoundKind.NamespaceExpression:
var ns = (BoundNamespaceExpression)expr;
Error(diagnostics, ErrorCode.ERR_BadSKknown, node, ns.NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize());
return false;
case BoundKind.TypeExpression:
var type = (BoundTypeExpression)expr;
Error(diagnostics, ErrorCode.ERR_BadSKknown, node, type.Type, MessageID.IDS_SK_TYPE.Localize(), MessageID.IDS_SK_VARIABLE.Localize());
return false;
case BoundKind.Lambda:
case BoundKind.UnboundLambda:
// lambdas can only be used as RValues
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
case BoundKind.UnconvertedAddressOfOperator:
var unconvertedAddressOf = (BoundUnconvertedAddressOfOperator)expr;
Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), node, unconvertedAddressOf.Operand.Name, MessageID.IDS_AddressOfMethodGroup.Localize());
return false;
case BoundKind.MethodGroup when valueKind == BindValueKind.AddressOf:
// If the addressof operator is used not as an rvalue, that will get flagged when CheckValue
// is called on the parent BoundUnconvertedAddressOf node.
return true;
case BoundKind.MethodGroup:
// method groups can only be used as RValues except when taking the address of one
var methodGroup = (BoundMethodGroup)expr;
Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), node, methodGroup.Name, MessageID.IDS_MethodGroup.Localize());
return false;
case BoundKind.RangeVariable:
{
// range variables can only be used as RValues
var queryref = (BoundRangeVariable)expr;
var errorCode = GetRangeLvalueError(valueKind);
if (errorCode is ErrorCode.ERR_InvalidAddrOp or ErrorCode.ERR_RefLocalOrParamExpected)
{
Error(diagnostics, errorCode, node);
}
else
{
Error(diagnostics, errorCode, node, queryref.RangeVariableSymbol.Name);
}
return false;
}
case BoundKind.Conversion:
var conversion = (BoundConversion)expr;
// conversions are strict RValues, but unboxing has a specific error
if (conversion.ConversionKind == ConversionKind.Unboxing)
{
Error(diagnostics, ErrorCode.ERR_UnboxNotLValue, node);
return false;
}
break;
// array access is readwrite variable if the indexing expression is not System.Range
case BoundKind.ArrayAccess:
return checkArrayAccessValueKind(node, valueKind, ((BoundArrayAccess)expr).Indices, diagnostics);
// pointer dereferencing is a readwrite variable
case BoundKind.PointerIndirectionOperator:
// The undocumented __refvalue(tr, T) expression results in a variable of type T.
case BoundKind.RefValueOperator:
// dynamic expressions are readwrite, and can even be passed by ref (which is implemented via a temp)
case BoundKind.DynamicMemberAccess:
case BoundKind.DynamicIndexerAccess:
case BoundKind.DynamicObjectInitializerMember:
{
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
// These are readwrite variables
return true;
}
case BoundKind.PointerElementAccess:
{
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
var receiver = ((BoundPointerElementAccess)expr).Expression;
if (receiver is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer)
{
return CheckValueKind(node, fieldAccess.ReceiverOpt, valueKind, checkingReceiver: true, diagnostics);
}
return true;
}
case BoundKind.Parameter:
var parameter = (BoundParameter)expr;
return CheckParameterValueKind(node, parameter, valueKind, checkingReceiver, diagnostics);
case BoundKind.Local:
var local = (BoundLocal)expr;
return CheckLocalValueKind(node, local, valueKind, checkingReceiver, diagnostics);
case BoundKind.ThisReference:
// `this` is never ref assignable
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
// We will already have given an error for "this" used outside of a constructor,
// instance method, or instance accessor. Assume that "this" is a variable if it is in a struct.
// SPEC: when this is used in a primary-expression within an instance constructor of a struct,
// SPEC: it is classified as a variable.
// SPEC: When this is used in a primary-expression within an instance method or instance accessor
// SPEC: of a struct, it is classified as a variable.
// Note: RValueOnly is checked at the beginning of this method. Since we are here we need more than readable.
// "this" is readonly in members marked "readonly" and in members of readonly structs, unless we are in a constructor.
var isValueType = ((BoundThisReference)expr).Type.IsValueType;
if (!isValueType || (RequiresAssignableVariable(valueKind) && (this.ContainingMemberOrLambda as MethodSymbol)?.IsEffectivelyReadOnly == true))
{
ReportThisLvalueError(node, valueKind, isValueType, isPrimaryConstructorParameter: false, diagnostics);
return false;
}
return true;
case BoundKind.ImplicitReceiver:
case BoundKind.ObjectOrCollectionValuePlaceholder:
Debug.Assert(!RequiresRefAssignableVariable(valueKind));
return true;
case BoundKind.Call:
var call = (BoundCall)expr;
return CheckMethodReturnValueKind(call.Method, call.Syntax, node, valueKind, checkingReceiver, diagnostics);
case BoundKind.FunctionPointerInvocation:
return CheckMethodReturnValueKind(((BoundFunctionPointerInvocation)expr).FunctionPointer.Signature,
expr.Syntax,
node,
valueKind,
checkingReceiver,
diagnostics);
case BoundKind.ImplicitIndexerAccess:
var implicitIndexer = (BoundImplicitIndexerAccess)expr;
switch (implicitIndexer.IndexerOrSliceAccess)
{
case BoundArrayAccess arrayAccess:
return checkArrayAccessValueKind(node, valueKind, arrayAccess.Indices, diagnostics);
case BoundCall sliceAccess:
return CheckMethodReturnValueKind(sliceAccess.Method, sliceAccess.Syntax, node, valueKind, checkingReceiver, diagnostics);
default:
throw ExceptionUtilities.UnexpectedValue(implicitIndexer.IndexerOrSliceAccess.Kind);
}
case BoundKind.ImplicitIndexerReceiverPlaceholder:
break;
case BoundKind.DeconstructValuePlaceholder:
break;
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expr;
// byref conditional defers to its operands
if (conditional.IsRef &&
(CheckValueKind(conditional.Consequence.Syntax, conditional.Consequence, valueKind, checkingReceiver: false, diagnostics: diagnostics) &
CheckValueKind(conditional.Alternative.Syntax, conditional.Alternative, valueKind, checkingReceiver: false, diagnostics: diagnostics)))
{
return true;
}
// report standard lvalue error
break;
case BoundKind.FieldAccess:
{
var fieldAccess = (BoundFieldAccess)expr;
return CheckFieldValueKind(node, fieldAccess, valueKind, checkingReceiver, diagnostics);
}
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expr;
return CheckSimpleAssignmentValueKind(node, assignment, valueKind, diagnostics);
default:
Debug.Assert(expr is not BoundValuePlaceholderBase, $"Placeholder kind {expr.Kind} should be explicitly handled");
break;
}
// At this point we should have covered all the possible cases for anything that is not a strict RValue.
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
bool checkArrayAccessValueKind(SyntaxNode node, BindValueKind valueKind, ImmutableArray<BoundExpression> indices, BindingDiagnosticBag diagnostics)
{
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
if (indices.Length == 1 &&
TypeSymbol.Equals(
indices[0].Type,
Compilation.GetWellKnownType(WellKnownType.System_Range),
TypeCompareKind.ConsiderEverything))
{
// Range indexer is an rvalue
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
return true;
}
}
private static void ReportThisLvalueError(SyntaxNode node, BindValueKind valueKind, bool isValueType, bool isPrimaryConstructorParameter, BindingDiagnosticBag diagnostics)
{
var errorCode = GetThisLvalueError(valueKind, isValueType, isPrimaryConstructorParameter);
if (errorCode is ErrorCode.ERR_InvalidAddrOp or ErrorCode.ERR_IncrementLvalueExpected or ErrorCode.ERR_RefReturnThis or ErrorCode.ERR_RefLocalOrParamExpected or ErrorCode.ERR_RefLvalueExpected)
{
Error(diagnostics, errorCode, node);
}
else
{
Error(diagnostics, errorCode, node, node);
}
}
private static bool CheckNotNamespaceOrType(BoundExpression expr, BindingDiagnosticBag diagnostics)
{
switch (expr.Kind)
{
case BoundKind.NamespaceExpression:
Error(diagnostics, ErrorCode.ERR_BadSKknown, expr.Syntax, ((BoundNamespaceExpression)expr).NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize());
return false;
case BoundKind.TypeExpression:
Error(diagnostics, ErrorCode.ERR_BadSKunknown, expr.Syntax, expr.Type, MessageID.IDS_SK_TYPE.Localize());
return false;
default:
return true;
}
}
private bool CheckLocalValueKind(SyntaxNode node, BoundLocal local, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
if (valueKind == BindValueKind.AddressOf && this.IsInAsyncMethod())
{
Error(diagnostics, ErrorCode.WRN_AddressOfInAsync, node);
}
// Local constants are never variables. Local variables are sometimes
// not to be treated as variables, if they are fixed, declared in a using,
// or declared in a foreach.
LocalSymbol localSymbol = local.LocalSymbol;
if (RequiresAssignableVariable(valueKind))
{
if (this.LockedOrDisposedVariables.Contains(localSymbol))
{
diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, local.Syntax.Location, localSymbol);
}
// IsWritable means the variable is writable. If this is a ref variable, IsWritable
// does not imply anything about the storage location
if (localSymbol.RefKind == RefKind.RefReadOnly ||
(localSymbol.RefKind == RefKind.None && !localSymbol.IsWritableVariable))
{
ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics);
return false;
}
}
else if (RequiresRefAssignableVariable(valueKind))
{
if (localSymbol.RefKind == RefKind.None)
{
diagnostics.Add(ErrorCode.ERR_RefLocalOrParamExpected, node.Location);
return false;
}
else if (!localSymbol.IsWritableVariable)
{
ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics);
return false;
}
}
return true;
}
}
internal partial class RefSafetyAnalysis
{
private bool CheckLocalRefEscape(SyntaxNode node, BoundLocal local, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
LocalSymbol localSymbol = local.LocalSymbol;
// if local symbol can escape to the same or wider/shallower scope then escapeTo
// then it is all ok, otherwise it is an error.
if (GetLocalScopes(localSymbol).RefEscapeScope <= escapeTo)
{
return true;
}
var inUnsafeRegion = _inUnsafeRegion;
if (escapeTo is CallingMethodScope or ReturnOnlyScope)
{
if (localSymbol.RefKind == RefKind.None)
{
if (checkingReceiver)
{
Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_RefReturnLocal2 : ErrorCode.ERR_RefReturnLocal2, local.Syntax, localSymbol);
}
else
{
Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_RefReturnLocal : ErrorCode.ERR_RefReturnLocal, node, localSymbol);
}
return inUnsafeRegion;
}
if (checkingReceiver)
{
Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_RefReturnNonreturnableLocal2 : ErrorCode.ERR_RefReturnNonreturnableLocal2, local.Syntax, localSymbol);
}
else
{
Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_RefReturnNonreturnableLocal : ErrorCode.ERR_RefReturnNonreturnableLocal, node, localSymbol);
}
return inUnsafeRegion;
}
Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_EscapeVariable : ErrorCode.ERR_EscapeVariable, node, localSymbol);
return inUnsafeRegion;
}
}
internal partial class Binder
{
private bool CheckParameterValueKind(SyntaxNode node, BoundParameter parameter, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!RequiresAssignableVariable(BindValueKind.AddressOf));
if (valueKind == BindValueKind.AddressOf && this.IsInAsyncMethod())
{
Error(diagnostics, ErrorCode.WRN_AddressOfInAsync, node);
}
ParameterSymbol parameterSymbol = parameter.ParameterSymbol;
// all parameters can be passed by ref/out or assigned to
// except "in" parameters, which are readonly
if (parameterSymbol.RefKind == RefKind.In && RequiresAssignableVariable(valueKind))
{
ReportReadOnlyError(parameterSymbol, node, valueKind, checkingReceiver, diagnostics);
return false;
}
else if (parameterSymbol.RefKind == RefKind.None && RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
Debug.Assert(parameterSymbol.RefKind != RefKind.None || !RequiresRefAssignableVariable(valueKind));
// It is an error to capture 'in', 'ref' or 'out' parameters.
// Skipping them to simplify the logic.
if (parameterSymbol.RefKind == RefKind.None &&
parameterSymbol.ContainingSymbol is SynthesizedPrimaryConstructor primaryConstructor &&
primaryConstructor.GetCapturedParameters().TryGetValue(parameterSymbol, out FieldSymbol backingField))
{
Debug.Assert(backingField.RefKind == RefKind.None);
Debug.Assert(!RequiresRefAssignableVariable(valueKind));
if (backingField.IsReadOnly)
{
Debug.Assert(backingField.RefKind == RefKind.None);
if (RequiresAssignableVariable(valueKind) &&
!CanModifyReadonlyField(receiverIsThis: true, backingField))
{
reportReadOnlyParameterError(parameterSymbol, node, valueKind, checkingReceiver, diagnostics);
return false;
}
}
if (RequiresAssignableVariable(valueKind) && !backingField.ContainingType.IsReferenceType && (this.ContainingMemberOrLambda as MethodSymbol)?.IsEffectivelyReadOnly == true)
{
ReportThisLvalueError(node, valueKind, isValueType: true, isPrimaryConstructorParameter: true, diagnostics);
return false;
}
}
if (this.LockedOrDisposedVariables.Contains(parameterSymbol))
{
// Consider: It would be more conventional to pass "symbol" rather than "symbol.Name".
// The issue is that the error SymbolDisplayFormat doesn't display parameter
// names - only their types - which works great in signatures, but not at all
// at the top level.
diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, parameter.Syntax.Location, parameterSymbol.Name);
}
return true;
}
static void reportReadOnlyParameterError(ParameterSymbol parameterSymbol, SyntaxNode node, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
// It's clearer to say that the address can't be taken than to say that the field can't be modified
// (even though the latter message gives more explanation of why).
Debug.Assert(valueKind != BindValueKind.AddressOf); // If this assert fails, we probably should report ErrorCode.ERR_InvalidAddrOp
if (checkingReceiver)
{
ErrorCode errorCode;
if (valueKind == BindValueKind.RefReturn)
{
errorCode = ErrorCode.ERR_RefReturnReadonlyPrimaryConstructorParameter2;
}
else if (RequiresRefOrOut(valueKind))
{
errorCode = ErrorCode.ERR_RefReadonlyPrimaryConstructorParameter2;
}
else
{
errorCode = ErrorCode.ERR_AssgReadonlyPrimaryConstructorParameter2;
}
Error(diagnostics, errorCode, node, parameterSymbol);
}