-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathBinder.ValueChecks.cs
More file actions
3532 lines (3000 loc) · 161 KB
/
Binder.ValueChecks.cs
File metadata and controls
3532 lines (3000 loc) · 161 KB
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 Microsoft.CodeAnalysis.CSharp.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
/// <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.
/// The 0 and 1 are special scopes -
/// 0 is the "external" or "return" 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 or can be returned.
/// 1 is the "parameter" or "top" 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>
internal const uint ExternalScope = 0;
internal const uint TopLevelScope = 1;
// 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
/// </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, DiagnosticBag 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, DiagnosticBag 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 == BindValueKind.Assignable || valueKind == BindValueKind.RefOrOut || diagnostics.HasAnyResolvedErrors());
return expr;
case BoundKind.IndexerAccess:
expr = BindIndexerDefaultArguments((BoundIndexerAccess)expr, valueKind, diagnostics);
break;
case BoundKind.UnconvertedObjectCreationExpression:
if (valueKind == BindValueKind.RValue)
{
return expr;
}
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;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteDiagnostics: ref useSiteDiagnostics);
diagnostics.Add(expr.Syntax, useSiteDiagnostics);
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, DiagnosticBag 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:
return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = ((BoundIndexOrRangePatternIndexerAccess)expr);
if (patternIndexer.PatternSymbol.Kind == SymbolKind.Property)
{
// If this is an Index indexer, PatternSymbol should be a property, pointing to the
// pattern indexer. If it's a Range access, it will be a method, pointing to a Slice method
// and it's handled below as part of invocations.
return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics);
}
Debug.Assert(patternIndexer.PatternSymbol.Kind == SymbolKind.Method);
break;
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.ConstantValue != 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;
Error(diagnostics, GetRangeLvalueError(valueKind), 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:
{
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
var boundAccess = (BoundArrayAccess)expr;
if (boundAccess.Indices.Length == 1 &&
TypeSymbol.Equals(
boundAccess.Indices[0].Type,
Compilation.GetWellKnownType(WellKnownType.System_Range),
TypeCompareKind.ConsiderEverything))
{
// Range indexer is an rvalue
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
return true;
}
// 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:
{
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))
{
Error(diagnostics, GetThisLvalueError(valueKind, isValueType), node, node);
return false;
}
return true;
case BoundKind.ImplicitReceiver:
case BoundKind.ObjectOrCollectionValuePlaceholder:
Debug.Assert(!RequiresRefAssignableVariable(valueKind));
return true;
case BoundKind.Call:
var call = (BoundCall)expr;
return CheckCallValueKind(call, node, valueKind, checkingReceiver, diagnostics);
case BoundKind.FunctionPointerInvocation:
return CheckMethodReturnValueKind(((BoundFunctionPointerInvocation)expr).FunctionPointer.Signature,
expr.Syntax,
node,
valueKind,
checkingReceiver,
diagnostics);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr;
// If we got here this should be a pattern indexer taking a Range,
// meaning that the pattern symbol must be a method (either Slice or Substring)
return CheckMethodReturnValueKind(
(MethodSymbol)patternIndexer.PatternSymbol,
patternIndexer.Syntax,
node,
valueKind,
checkingReceiver,
diagnostics);
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);
}
// 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;
}
private static bool CheckNotNamespaceOrType(BoundExpression expr, DiagnosticBag 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, DiagnosticBag diagnostics)
{
// 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, localSymbol);
return false;
}
else if (!localSymbol.IsWritableVariable)
{
ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics);
return false;
}
}
return true;
}
private static bool CheckLocalRefEscape(SyntaxNode node, BoundLocal local, uint escapeTo, bool checkingReceiver, DiagnosticBag 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 (localSymbol.RefEscapeScope <= escapeTo)
{
return true;
}
if (escapeTo == Binder.ExternalScope)
{
if (localSymbol.RefKind == RefKind.None)
{
if (checkingReceiver)
{
Error(diagnostics, ErrorCode.ERR_RefReturnLocal2, local.Syntax, localSymbol);
}
else
{
Error(diagnostics, ErrorCode.ERR_RefReturnLocal, node, localSymbol);
}
return false;
}
if (checkingReceiver)
{
Error(diagnostics, ErrorCode.ERR_RefReturnNonreturnableLocal2, local.Syntax, localSymbol);
}
else
{
Error(diagnostics, ErrorCode.ERR_RefReturnNonreturnableLocal, node, localSymbol);
}
return false;
}
Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, localSymbol);
return false;
}
private bool CheckParameterValueKind(SyntaxNode node, BoundParameter parameter, BindValueKind valueKind, bool checkingReceiver, DiagnosticBag diagnostics)
{
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;
}
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;
}
private static bool CheckParameterRefEscape(SyntaxNode node, BoundParameter parameter, uint escapeTo, bool checkingReceiver, DiagnosticBag diagnostics)
{
ParameterSymbol parameterSymbol = parameter.ParameterSymbol;
// byval parameters can escape to method's top level. Others can escape further.
// NOTE: "method" here means nearest containing method, lambda or local function.
if (escapeTo == Binder.ExternalScope && parameterSymbol.RefKind == RefKind.None)
{
if (checkingReceiver)
{
Error(diagnostics, ErrorCode.ERR_RefReturnParameter2, parameter.Syntax, parameterSymbol.Name);
}
else
{
Error(diagnostics, ErrorCode.ERR_RefReturnParameter, node, parameterSymbol.Name);
}
return false;
}
// can ref-escape to any scope otherwise
return true;
}
private bool CheckFieldValueKind(SyntaxNode node, BoundFieldAccess fieldAccess, BindValueKind valueKind, bool checkingReceiver, DiagnosticBag diagnostics)
{
var fieldSymbol = fieldAccess.FieldSymbol;
var fieldIsStatic = fieldSymbol.IsStatic;
if (RequiresAssignableVariable(valueKind))
{
// A field is writeable unless
// (1) it is readonly and we are not in a constructor or field initializer
// (2) the receiver of the field is of value type and is not a variable or object creation expression.
// For example, if you have a class C with readonly field f of type S, and
// S has a mutable field x, then c.f.x is not a variable because c.f is not
// writable.
if (fieldSymbol.IsReadOnly)
{
var canModifyReadonly = false;
Symbol containing = this.ContainingMemberOrLambda;
if ((object)containing != null &&
fieldIsStatic == containing.IsStatic &&
(fieldIsStatic || fieldAccess.ReceiverOpt.Kind == BoundKind.ThisReference) &&
(Compilation.FeatureStrictEnabled
? TypeSymbol.Equals(fieldSymbol.ContainingType, containing.ContainingType, TypeCompareKind.ConsiderEverything2)
// We duplicate a bug in the native compiler for compatibility in non-strict mode
: TypeSymbol.Equals(fieldSymbol.ContainingType.OriginalDefinition, containing.ContainingType.OriginalDefinition, TypeCompareKind.ConsiderEverything2)))
{
if (containing.Kind == SymbolKind.Method)
{
MethodSymbol containingMethod = (MethodSymbol)containing;
MethodKind desiredMethodKind = fieldIsStatic ? MethodKind.StaticConstructor : MethodKind.Constructor;
canModifyReadonly = (containingMethod.MethodKind == desiredMethodKind) ||
isAssignedFromInitOnlySetterOnThis(fieldAccess.ReceiverOpt);
}
else if (containing.Kind == SymbolKind.Field)
{
canModifyReadonly = true;
}
}
if (!canModifyReadonly)
{
ReportReadOnlyFieldError(fieldSymbol, node, valueKind, checkingReceiver, diagnostics);
return false;
}
}
if (fieldSymbol.IsFixedSizeBuffer)
{
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
}
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
// r/w fields that are static or belong to reference types are writeable and returnable
if (fieldIsStatic || fieldSymbol.ContainingType.IsReferenceType)
{
return true;
}
// for other fields defer to the receiver.
return CheckIsValidReceiverForVariable(node, fieldAccess.ReceiverOpt, valueKind, diagnostics);
bool isAssignedFromInitOnlySetterOnThis(BoundExpression receiver)
{
// bad: other.readonlyField = ...
// bad: base.readonlyField = ...
if (!(receiver is BoundThisReference))
{
return false;
}
if (!(ContainingMemberOrLambda is MethodSymbol method))
{
return false;
}
return method.IsInitOnly;
}
}
private bool CheckSimpleAssignmentValueKind(SyntaxNode node, BoundAssignmentOperator assignment, BindValueKind valueKind, DiagnosticBag diagnostics)
{
// Only ref-assigns produce LValues
if (assignment.IsRef)
{
return CheckValueKind(node, assignment.Left, valueKind, checkingReceiver: false, diagnostics);
}
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
private static bool CheckFieldRefEscape(SyntaxNode node, BoundFieldAccess fieldAccess, uint escapeFrom, uint escapeTo, DiagnosticBag diagnostics)
{
var fieldSymbol = fieldAccess.FieldSymbol;
// fields that are static or belong to reference types can ref escape anywhere
if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType)
{
return true;
}
// for other fields defer to the receiver.
return CheckRefEscape(node, fieldAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics: diagnostics);
}
private static bool CheckFieldLikeEventRefEscape(SyntaxNode node, BoundEventAccess eventAccess, uint escapeFrom, uint escapeTo, DiagnosticBag diagnostics)
{
var eventSymbol = eventAccess.EventSymbol;
// field-like events that are static or belong to reference types can ref escape anywhere
if (eventSymbol.IsStatic || eventSymbol.ContainingType.IsReferenceType)
{
return true;
}
// for other events defer to the receiver.
return CheckRefEscape(node, eventAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics: diagnostics);
}
private bool CheckEventValueKind(BoundEventAccess boundEvent, BindValueKind valueKind, DiagnosticBag diagnostics)
{
// Compound assignment (actually "event assignment") is allowed "everywhere", subject to the restrictions of
// accessibility, use site errors, and receiver variable-ness (for structs).
// Other operations are allowed only for field-like events and only where the backing field is accessible
// (i.e. in the declaring type) - subject to use site errors and receiver variable-ness.
BoundExpression receiver = boundEvent.ReceiverOpt;
SyntaxNode eventSyntax = GetEventName(boundEvent); //does not include receiver
EventSymbol eventSymbol = boundEvent.EventSymbol;
if (valueKind == BindValueKind.CompoundAssignment)
{
// NOTE: accessibility has already been checked by lookup.
// NOTE: availability of well-known members is checked in BindEventAssignment because
// we don't have the context to determine whether addition or subtraction is being performed.
if (ReportUseSiteDiagnostics(eventSymbol, diagnostics, eventSyntax))
{
// NOTE: BindEventAssignment checks use site errors on the specific accessor
// (since we don't know which is being used).
return false;
}
Debug.Assert(!RequiresVariableReceiver(receiver, eventSymbol));
return true;
}
else
{
if (!boundEvent.IsUsableAsField)
{
// Dev10 reports this in addition to ERR_BadAccess, but we won't even reach this point if the event isn't accessible (caught by lookup).
Error(diagnostics, GetBadEventUsageDiagnosticInfo(eventSymbol), eventSyntax);
return false;
}
else if (ReportUseSiteDiagnostics(eventSymbol, diagnostics, eventSyntax))
{
if (!CheckIsValidReceiverForVariable(eventSyntax, receiver, BindValueKind.Assignable, diagnostics))
{
return false;
}
}
else if (RequiresVariable(valueKind))
{
if (eventSymbol.IsWindowsRuntimeEvent && valueKind != BindValueKind.Assignable)
{
// NOTE: Dev11 reports ERR_RefProperty, as if this were a property access (since that's how it will be lowered).
// Roslyn reports a new, more specific, error code.
ErrorCode errorCode = valueKind == BindValueKind.RefOrOut ? ErrorCode.ERR_WinRtEventPassedByRef : GetStandardLvalueError(valueKind);
Error(diagnostics, errorCode, eventSyntax, eventSymbol);
return false;
}
else if (RequiresVariableReceiver(receiver, eventSymbol.AssociatedField) && // NOTE: using field, not event
!CheckIsValidReceiverForVariable(eventSyntax, receiver, valueKind, diagnostics))
{
return false;
}
}
return true;
}
}
private bool CheckIsValidReceiverForVariable(SyntaxNode node, BoundExpression receiver, BindValueKind kind, DiagnosticBag diagnostics)
{
Debug.Assert(receiver != null);
return Flags.Includes(BinderFlags.ObjectInitializerMember) && receiver.Kind == BoundKind.ObjectOrCollectionValuePlaceholder ||
CheckValueKind(node, receiver, kind, true, diagnostics);
}
/// <summary>
/// SPEC: When a property or indexer declared in a struct-type is the target of an
/// SPEC: assignment, the instance expression associated with the property or indexer
/// SPEC: access must be classified as a variable. If the instance expression is
/// SPEC: classified as a value, a compile-time error occurs. Because of 7.6.4,
/// SPEC: the same rule also applies to fields.
/// </summary>
/// <remarks>
/// NOTE: The spec fails to impose the restriction that the event receiver must be classified
/// as a variable (unlike for properties - 7.17.1). This seems like a bug, but we have
/// production code that won't build with the restriction in place (see DevDiv #15674).
/// </remarks>
private static bool RequiresVariableReceiver(BoundExpression receiver, Symbol symbol)
{
return symbol.RequiresInstanceReceiver()
&& symbol.Kind != SymbolKind.Event
&& receiver?.Type?.IsValueType == true;
}
private bool CheckCallValueKind(BoundCall call, SyntaxNode node, BindValueKind valueKind, bool checkingReceiver, DiagnosticBag diagnostics)
=> CheckMethodReturnValueKind(call.Method, call.Syntax, node, valueKind, checkingReceiver, diagnostics);
protected bool CheckMethodReturnValueKind(
MethodSymbol methodSymbol,
SyntaxNode callSyntaxOpt,
SyntaxNode node,
BindValueKind valueKind,
bool checkingReceiver,
DiagnosticBag diagnostics)
{
// A call can only be a variable if it returns by reference. If this is the case,
// whether or not it is a valid variable depends on whether or not the call is the
// RHS of a return or an assign by reference:
// - If call is used in a context demanding ref-returnable reference all of its ref
// inputs must be ref-returnable
if (RequiresVariable(valueKind) && methodSymbol.RefKind == RefKind.None)
{