-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathBinder_Expressions.cs
9358 lines (8113 loc) · 459 KB
/
Binder_Expressions.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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>.
/// </summary>
internal partial class Binder
{
/// <summary>
/// Determines whether "this" reference is available within the current context.
/// </summary>
/// <param name="isExplicit">The reference was explicitly specified in syntax.</param>
/// <param name="inStaticContext">True if "this" is not available due to the current method/property/field initializer being static.</param>
/// <returns>True if a reference to "this" is available.</returns>
internal bool HasThis(bool isExplicit, out bool inStaticContext)
{
var memberOpt = this.ContainingMemberOrLambda?.ContainingNonLambdaMember();
if (memberOpt?.IsStatic == true)
{
inStaticContext = memberOpt.Kind == SymbolKind.Field || memberOpt.Kind == SymbolKind.Method || memberOpt.Kind == SymbolKind.Property;
return false;
}
inStaticContext = false;
if (InConstructorInitializer || InAttributeArgument)
{
return false;
}
var containingType = memberOpt?.ContainingType;
bool inTopLevelScriptMember = (object)containingType != null && containingType.IsScriptClass;
// "this" is not allowed in field initializers (that are not script variable initializers):
if (InFieldInitializer && !inTopLevelScriptMember)
{
return false;
}
// top-level script code only allows implicit "this" reference:
return !inTopLevelScriptMember || !isExplicit;
}
internal bool InFieldInitializer
{
get { return this.Flags.Includes(BinderFlags.FieldInitializer); }
}
internal bool InParameterDefaultValue
{
get { return this.Flags.Includes(BinderFlags.ParameterDefaultValue); }
}
protected bool InConstructorInitializer
{
get { return this.Flags.Includes(BinderFlags.ConstructorInitializer); }
}
internal bool InAttributeArgument
{
get { return this.Flags.Includes(BinderFlags.AttributeArgument); }
}
internal bool InCref
{
get { return this.Flags.Includes(BinderFlags.Cref); }
}
protected bool InCrefButNotParameterOrReturnType
{
get { return InCref && !this.Flags.Includes(BinderFlags.CrefParameterOrReturnType); }
}
/// <summary>
/// Returns true if the node is in a position where an unbound type
/// such as (C<,>) is allowed.
/// </summary>
protected virtual bool IsUnboundTypeAllowed(GenericNameSyntax syntax)
{
return Next.IsUnboundTypeAllowed(syntax);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax)
{
return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound child.
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax, BoundExpression childNode)
{
return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNode);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound children.
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax, ImmutableArray<BoundExpression> childNodes)
{
return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNodes);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind.
/// </summary>
protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind)
{
return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind and the given bound child.
/// </summary>
protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind, BoundExpression childNode)
{
return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty, childNode);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API.
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols)
{
return new BoundBadExpression(syntax,
resultKind,
symbols,
ImmutableArray<BoundExpression>.Empty,
CreateErrorType());
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API,
/// and the given bound child.
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, BoundExpression childNode)
{
return new BoundBadExpression(syntax,
resultKind,
symbols,
ImmutableArray.Create(BindToTypeForErrorRecovery(childNode)),
CreateErrorType());
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API,
/// and the given bound children.
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, ImmutableArray<BoundExpression> childNodes, bool wasCompilerGenerated = false)
{
return new BoundBadExpression(syntax,
resultKind,
symbols,
childNodes.SelectAsArray((e, self) => self.BindToTypeForErrorRecovery(e), this),
CreateErrorType())
{ WasCompilerGenerated = wasCompilerGenerated };
}
/// <summary>
/// Helper method to generate a bound expression with HasErrors set to true.
/// Returned bound expression is guaranteed to have a non-null type, except when <paramref name="expr"/> is an unbound lambda.
/// If <paramref name="expr"/> already has errors and meets the above type requirements, then it is returned unchanged.
/// Otherwise, if <paramref name="expr"/> is a BoundBadExpression, then it is updated with the <paramref name="resultKind"/> and non-null type.
/// Otherwise, a new <see cref="BoundBadExpression"/> wrapping <paramref name="expr"/> is returned.
/// </summary>
/// <remarks>
/// Returned expression need not be a <see cref="BoundBadExpression"/>, but is guaranteed to have HasErrors set to true.
/// </remarks>
private BoundExpression ToBadExpression(BoundExpression expr, LookupResultKind resultKind = LookupResultKind.Empty)
{
Debug.Assert(expr != null);
Debug.Assert(resultKind != LookupResultKind.Viable);
TypeSymbol resultType = expr.Type;
BoundKind exprKind = expr.Kind;
if (expr.HasAnyErrors && ((object)resultType != null || exprKind == BoundKind.UnboundLambda || exprKind == BoundKind.DefaultLiteral))
{
return expr;
}
if (exprKind == BoundKind.BadExpression)
{
var badExpression = (BoundBadExpression)expr;
return badExpression.Update(resultKind, badExpression.Symbols, badExpression.ChildBoundNodes, resultType);
}
else
{
ArrayBuilder<Symbol> symbols = ArrayBuilder<Symbol>.GetInstance();
expr.GetExpressionSymbols(symbols, parent: null, binder: this);
return new BoundBadExpression(
expr.Syntax,
resultKind,
symbols.ToImmutableAndFree(),
ImmutableArray.Create(BindToTypeForErrorRecovery(expr)),
resultType ?? CreateErrorType());
}
}
internal NamedTypeSymbol CreateErrorType(string name = "")
{
return new ExtendedErrorTypeSymbol(this.Compilation, name, arity: 0, errorInfo: null, unreported: false);
}
/// <summary>
/// Bind the expression and verify the expression matches the combination of lvalue and
/// rvalue requirements given by valueKind. If the expression was bound successfully, but
/// did not meet the requirements, the return value will be a <see cref="BoundBadExpression"/> that
/// (typically) wraps the subexpression.
/// </summary>
internal BoundExpression BindValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind)
{
var result = this.BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false);
return CheckValue(result, valueKind, diagnostics);
}
internal BoundExpression BindRValueWithoutTargetType(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true)
{
return BindToNaturalType(BindValue(node, diagnostics, BindValueKind.RValue), diagnostics, reportNoTargetType);
}
/// <summary>
/// When binding a switch case's expression, it is possible that it resolves to a type (technically, a type pattern).
/// This implementation permits either an rvalue or a BoundTypeExpression.
/// </summary>
internal BoundExpression BindTypeOrRValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
var valueOrType = BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false);
if (valueOrType.Kind == BoundKind.TypeExpression)
{
// In the Color Color case (Kind == BoundKind.TypeOrValueExpression), we treat it as a value
// by not entering this if statement
return valueOrType;
}
return CheckValue(valueOrType, BindValueKind.RValue, diagnostics);
}
internal BoundExpression BindToTypeForErrorRecovery(BoundExpression expression, TypeSymbol type = null)
{
if (expression is null)
return null;
var result =
!expression.NeedsToBeConverted() ? expression :
type is null ? BindToNaturalType(expression, BindingDiagnosticBag.Discarded, reportNoTargetType: false) :
GenerateConversionForAssignment(type, expression, BindingDiagnosticBag.Discarded);
return result;
}
/// <summary>
/// Bind an rvalue expression to its natural type. For example, a switch expression that has not been
/// converted to another type has to be converted to its own natural type by applying a conversion to
/// that type to each of the arms of the switch expression. This method is a bottleneck for ensuring
/// that such a conversion occurs when needed. It also handles tuple expressions which need to be
/// converted to their own natural type because they may contain switch expressions.
/// </summary>
internal BoundExpression BindToNaturalType(BoundExpression expression, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true)
{
if (!expression.NeedsToBeConverted())
return expression;
BoundExpression result;
switch (expression)
{
case BoundUnconvertedSwitchExpression expr:
{
var commonType = expr.Type;
var exprSyntax = (SwitchExpressionSyntax)expr.Syntax;
bool hasErrors = expression.HasErrors;
if (commonType is null)
{
diagnostics.Add(ErrorCode.ERR_SwitchExpressionNoBestType, exprSyntax.SwitchKeyword.GetLocation());
commonType = CreateErrorType();
hasErrors = true;
}
result = ConvertSwitchExpression(expr, commonType, conversionIfTargetTyped: null, diagnostics, hasErrors);
}
break;
case BoundUnconvertedConditionalOperator op:
{
TypeSymbol type = op.Type;
bool hasErrors = op.HasErrors;
if (type is null)
{
Debug.Assert(op.NoCommonTypeError != 0);
type = CreateErrorType();
hasErrors = true;
object trueArg = op.Consequence.Display;
object falseArg = op.Alternative.Display;
if (op.NoCommonTypeError == ErrorCode.ERR_InvalidQM && trueArg is Symbol trueSymbol && falseArg is Symbol falseSymbol)
{
// ERR_InvalidQM is an error that there is no conversion between the two types. They might be the same
// type name from different assemblies, so we disambiguate the display.
SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, trueSymbol, falseSymbol);
trueArg = distinguisher.First;
falseArg = distinguisher.Second;
}
diagnostics.Add(op.NoCommonTypeError, op.Syntax.Location, trueArg, falseArg);
}
result = ConvertConditionalExpression(op, type, conversionIfTargetTyped: null, diagnostics, hasErrors);
}
break;
case BoundTupleLiteral sourceTuple:
{
var boundArgs = ArrayBuilder<BoundExpression>.GetInstance(sourceTuple.Arguments.Length);
foreach (var arg in sourceTuple.Arguments)
{
boundArgs.Add(BindToNaturalType(arg, diagnostics, reportNoTargetType));
}
result = new BoundConvertedTupleLiteral(
sourceTuple.Syntax,
sourceTuple,
wasTargetTyped: false,
boundArgs.ToImmutableAndFree(),
sourceTuple.ArgumentNamesOpt,
sourceTuple.InferredNamesOpt,
sourceTuple.Type, // same type to keep original element names
sourceTuple.HasErrors).WithSuppression(sourceTuple.IsSuppressed);
}
break;
case BoundDefaultLiteral defaultExpr:
{
if (reportNoTargetType)
{
// In some cases, we let the caller report the error
diagnostics.Add(ErrorCode.ERR_DefaultLiteralNoTargetType, defaultExpr.Syntax.GetLocation());
}
result = new BoundDefaultExpression(
defaultExpr.Syntax,
targetType: null,
defaultExpr.ConstantValue,
CreateErrorType(),
hasErrors: true).WithSuppression(defaultExpr.IsSuppressed);
}
break;
case BoundStackAllocArrayCreation { Type: null } boundStackAlloc:
{
// This is a context in which the stackalloc could be either a pointer
// or a span. For backward compatibility we treat it as a pointer.
var type = new PointerTypeSymbol(TypeWithAnnotations.Create(boundStackAlloc.ElementType));
result = GenerateConversionForAssignment(type, boundStackAlloc, diagnostics);
}
break;
case BoundUnconvertedObjectCreationExpression expr:
{
if (reportNoTargetType && !expr.HasAnyErrors)
{
diagnostics.Add(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, expr.Syntax.GetLocation(), expr.Display);
}
result = BindObjectCreationForErrorRecovery(expr, diagnostics);
}
break;
case BoundUnconvertedInterpolatedString unconvertedInterpolatedString:
{
result = BindUnconvertedInterpolatedStringToString(unconvertedInterpolatedString, diagnostics);
}
break;
case BoundBinaryOperator unconvertedBinaryOperator:
{
result = RebindSimpleBinaryOperatorAsConverted(unconvertedBinaryOperator, diagnostics);
}
break;
default:
result = expression;
break;
}
return result?.WithWasConverted();
}
private BoundExpression BindToInferredDelegateType(BoundExpression expr, BindingDiagnosticBag diagnostics)
{
Debug.Assert(expr.Kind is BoundKind.UnboundLambda or BoundKind.MethodGroup);
var syntax = expr.Syntax;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var delegateType = expr.GetInferredDelegateType(ref useSiteInfo);
diagnostics.Add(syntax, useSiteInfo);
if (delegateType is null)
{
if (CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInferredDelegateType, diagnostics))
{
diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation());
}
delegateType = CreateErrorType();
}
return GenerateConversionForAssignment(delegateType, expr, diagnostics);
}
internal BoundExpression BindValueAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind)
{
var result = this.BindExpressionAllowArgList(node, diagnostics: diagnostics);
return CheckValue(result, valueKind, diagnostics);
}
internal BoundFieldEqualsValue BindFieldInitializer(
FieldSymbol field,
EqualsValueClauseSyntax initializerOpt,
BindingDiagnosticBag diagnostics)
{
Debug.Assert((object)this.ContainingMemberOrLambda == field);
if (initializerOpt == null)
{
return null;
}
Binder initializerBinder = this.GetBinder(initializerOpt);
Debug.Assert(initializerBinder != null);
BoundExpression result = initializerBinder.BindVariableOrAutoPropInitializerValue(initializerOpt, field.RefKind,
field.GetFieldType(initializerBinder.FieldsBeingBound).Type, diagnostics);
return new BoundFieldEqualsValue(initializerOpt, field, initializerBinder.GetDeclaredLocalsForScope(initializerOpt), result);
}
internal BoundExpression BindVariableOrAutoPropInitializerValue(
EqualsValueClauseSyntax initializerOpt,
RefKind refKind,
TypeSymbol varType,
BindingDiagnosticBag diagnostics)
{
if (initializerOpt == null)
{
return null;
}
BindValueKind valueKind;
ExpressionSyntax value;
IsInitializerRefKindValid(initializerOpt, initializerOpt, refKind, diagnostics, out valueKind, out value);
BoundExpression initializer = BindPossibleArrayInitializer(value, varType, valueKind, diagnostics);
initializer = GenerateConversionForAssignment(varType, initializer, diagnostics);
return initializer;
}
internal Binder CreateBinderForParameterDefaultValue(
ParameterSymbol parameter,
EqualsValueClauseSyntax defaultValueSyntax)
{
var binder = new LocalScopeBinder(this.WithContainingMemberOrLambda(parameter.ContainingSymbol).WithAdditionalFlags(BinderFlags.ParameterDefaultValue));
return new ExecutableCodeBinder(defaultValueSyntax,
parameter.ContainingSymbol,
binder);
}
internal BoundParameterEqualsValue BindParameterDefaultValue(
EqualsValueClauseSyntax defaultValueSyntax,
ParameterSymbol parameter,
BindingDiagnosticBag diagnostics,
out BoundExpression valueBeforeConversion)
{
Debug.Assert(this.InParameterDefaultValue);
Debug.Assert(this.ContainingMemberOrLambda.Kind == SymbolKind.Method || this.ContainingMemberOrLambda.Kind == SymbolKind.Property);
// UNDONE: The binding and conversion has to be executed in a checked context.
Binder defaultValueBinder = this.GetBinder(defaultValueSyntax);
Debug.Assert(defaultValueBinder != null);
valueBeforeConversion = defaultValueBinder.BindValue(defaultValueSyntax.Value, diagnostics, BindValueKind.RValue);
// Always generate the conversion, even if the expression is not convertible to the given type.
// We want the erroneous conversion in the tree.
var result = new BoundParameterEqualsValue(defaultValueSyntax, parameter, defaultValueBinder.GetDeclaredLocalsForScope(defaultValueSyntax),
defaultValueBinder.GenerateConversionForAssignment(parameter.Type, valueBeforeConversion, diagnostics, ConversionForAssignmentFlags.DefaultParameter));
return result;
}
internal BoundFieldEqualsValue BindEnumConstantInitializer(
SourceEnumConstantSymbol symbol,
EqualsValueClauseSyntax equalsValueSyntax,
BindingDiagnosticBag diagnostics)
{
Binder initializerBinder = this.GetBinder(equalsValueSyntax);
Debug.Assert(initializerBinder != null);
var initializer = initializerBinder.BindValue(equalsValueSyntax.Value, diagnostics, BindValueKind.RValue);
initializer = initializerBinder.GenerateConversionForAssignment(symbol.ContainingType.EnumUnderlyingType, initializer, diagnostics);
return new BoundFieldEqualsValue(equalsValueSyntax, symbol, initializerBinder.GetDeclaredLocalsForScope(equalsValueSyntax), initializer);
}
public BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
return BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false);
}
protected BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed)
{
BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked, indexed);
VerifyUnchecked(node, diagnostics, expr);
if (expr.Kind == BoundKind.ArgListOperator)
{
// CS0226: An __arglist expression may only appear inside of a call or new expression
Error(diagnostics, ErrorCode.ERR_IllegalArglist, node);
expr = ToBadExpression(expr);
}
return expr;
}
// PERF: allowArgList is not a parameter because it is fairly uncommon case where arglists are allowed
// so we do not want to pass that argument to every BindExpression which is often recursive
// and extra arguments contribute to the stack size.
protected BoundExpression BindExpressionAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked: false, indexed: false);
VerifyUnchecked(node, diagnostics, expr);
return expr;
}
private void VerifyUnchecked(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression expr)
{
if (!expr.HasAnyErrors && !IsInsideNameof)
{
TypeSymbol exprType = expr.Type;
if ((object)exprType != null && exprType.IsUnsafe())
{
ReportUnsafeIfNotAllowed(node, diagnostics);
//CONSIDER: Return a bad expression so that HasErrors is true?
}
}
}
private BoundExpression BindExpressionInternal(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed)
{
if (IsEarlyAttributeBinder && !EarlyWellKnownAttributeBinder.CanBeValidAttributeArgument(node))
{
return BadExpression(node, LookupResultKind.NotAValue);
}
Debug.Assert(node != null);
switch (node.Kind())
{
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
return BindAnonymousFunction((AnonymousFunctionExpressionSyntax)node, diagnostics);
case SyntaxKind.ThisExpression:
return BindThis((ThisExpressionSyntax)node, diagnostics);
case SyntaxKind.BaseExpression:
return BindBase((BaseExpressionSyntax)node, diagnostics);
case SyntaxKind.InvocationExpression:
return BindInvocationExpression((InvocationExpressionSyntax)node, diagnostics);
case SyntaxKind.ArrayInitializerExpression:
return BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitInBadPlace);
case SyntaxKind.ArrayCreationExpression:
return BindArrayCreationExpression((ArrayCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.ImplicitArrayCreationExpression:
return BindImplicitArrayCreationExpression((ImplicitArrayCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.StackAllocArrayCreationExpression:
return BindStackAllocArrayCreationExpression((StackAllocArrayCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.ImplicitStackAllocArrayCreationExpression:
return BindImplicitStackAllocArrayCreationExpression((ImplicitStackAllocArrayCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.ObjectCreationExpression:
return BindObjectCreationExpression((ObjectCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.ImplicitObjectCreationExpression:
return BindImplicitObjectCreationExpression((ImplicitObjectCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics);
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics: diagnostics);
case SyntaxKind.SimpleAssignmentExpression:
return BindAssignment((AssignmentExpressionSyntax)node, diagnostics);
case SyntaxKind.CastExpression:
return BindCast((CastExpressionSyntax)node, diagnostics);
case SyntaxKind.ElementAccessExpression:
return BindElementAccess((ElementAccessExpressionSyntax)node, diagnostics);
case SyntaxKind.AddExpression:
case SyntaxKind.MultiplyExpression:
case SyntaxKind.SubtractExpression:
case SyntaxKind.DivideExpression:
case SyntaxKind.ModuloExpression:
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.LessThanExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.BitwiseAndExpression:
case SyntaxKind.BitwiseOrExpression:
case SyntaxKind.ExclusiveOrExpression:
case SyntaxKind.LeftShiftExpression:
case SyntaxKind.RightShiftExpression:
case SyntaxKind.UnsignedRightShiftExpression:
return BindSimpleBinaryOperator((BinaryExpressionSyntax)node, diagnostics);
case SyntaxKind.LogicalAndExpression:
case SyntaxKind.LogicalOrExpression:
return BindConditionalLogicalOperator((BinaryExpressionSyntax)node, diagnostics);
case SyntaxKind.CoalesceExpression:
return BindNullCoalescingOperator((BinaryExpressionSyntax)node, diagnostics);
case SyntaxKind.ConditionalAccessExpression:
return BindConditionalAccessExpression((ConditionalAccessExpressionSyntax)node, diagnostics);
case SyntaxKind.MemberBindingExpression:
return BindMemberBindingExpression((MemberBindingExpressionSyntax)node, invoked, indexed, diagnostics);
case SyntaxKind.ElementBindingExpression:
return BindElementBindingExpression((ElementBindingExpressionSyntax)node, diagnostics);
case SyntaxKind.IsExpression:
return BindIsOperator((BinaryExpressionSyntax)node, diagnostics);
case SyntaxKind.AsExpression:
return BindAsOperator((BinaryExpressionSyntax)node, diagnostics);
case SyntaxKind.UnaryPlusExpression:
case SyntaxKind.UnaryMinusExpression:
case SyntaxKind.LogicalNotExpression:
case SyntaxKind.BitwiseNotExpression:
return BindUnaryOperator((PrefixUnaryExpressionSyntax)node, diagnostics);
case SyntaxKind.IndexExpression:
return BindFromEndIndexExpression((PrefixUnaryExpressionSyntax)node, diagnostics);
case SyntaxKind.RangeExpression:
return BindRangeExpression((RangeExpressionSyntax)node, diagnostics);
case SyntaxKind.AddressOfExpression:
return BindAddressOfExpression((PrefixUnaryExpressionSyntax)node, diagnostics);
case SyntaxKind.PointerIndirectionExpression:
return BindPointerIndirectionExpression((PrefixUnaryExpressionSyntax)node, diagnostics);
case SyntaxKind.PostIncrementExpression:
case SyntaxKind.PostDecrementExpression:
return BindIncrementOperator(node, ((PostfixUnaryExpressionSyntax)node).Operand, ((PostfixUnaryExpressionSyntax)node).OperatorToken, diagnostics);
case SyntaxKind.PreIncrementExpression:
case SyntaxKind.PreDecrementExpression:
return BindIncrementOperator(node, ((PrefixUnaryExpressionSyntax)node).Operand, ((PrefixUnaryExpressionSyntax)node).OperatorToken, diagnostics);
case SyntaxKind.ConditionalExpression:
return BindConditionalOperator((ConditionalExpressionSyntax)node, diagnostics);
case SyntaxKind.SwitchExpression:
return BindSwitchExpression((SwitchExpressionSyntax)node, diagnostics);
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.NullLiteralExpression:
return BindLiteralConstant((LiteralExpressionSyntax)node, diagnostics);
case SyntaxKind.Utf8StringLiteralExpression:
return BindUtf8StringLiteral((LiteralExpressionSyntax)node, diagnostics);
case SyntaxKind.DefaultLiteralExpression:
MessageID.IDS_FeatureDefaultLiteral.CheckFeatureAvailability(diagnostics, node);
return new BoundDefaultLiteral(node);
case SyntaxKind.ParenthesizedExpression:
// Parenthesis tokens are ignored, and operand is bound in the context of parent
// expression.
return BindParenthesizedExpression(((ParenthesizedExpressionSyntax)node).Expression, diagnostics);
case SyntaxKind.UncheckedExpression:
case SyntaxKind.CheckedExpression:
return BindCheckedExpression((CheckedExpressionSyntax)node, diagnostics);
case SyntaxKind.DefaultExpression:
return BindDefaultExpression((DefaultExpressionSyntax)node, diagnostics);
case SyntaxKind.TypeOfExpression:
return BindTypeOf((TypeOfExpressionSyntax)node, diagnostics);
case SyntaxKind.SizeOfExpression:
return BindSizeOf((SizeOfExpressionSyntax)node, diagnostics);
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.UnsignedRightShiftAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
return BindCompoundAssignment((AssignmentExpressionSyntax)node, diagnostics);
case SyntaxKind.CoalesceAssignmentExpression:
return BindNullCoalescingAssignmentOperator((AssignmentExpressionSyntax)node, diagnostics);
case SyntaxKind.AliasQualifiedName:
case SyntaxKind.PredefinedType:
return this.BindNamespaceOrType(node, diagnostics);
case SyntaxKind.QueryExpression:
return this.BindQuery((QueryExpressionSyntax)node, diagnostics);
case SyntaxKind.AnonymousObjectCreationExpression:
return BindAnonymousObjectCreation((AnonymousObjectCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.QualifiedName:
return BindQualifiedName((QualifiedNameSyntax)node, diagnostics);
case SyntaxKind.ComplexElementInitializerExpression:
return BindUnexpectedComplexElementInitializer((InitializerExpressionSyntax)node, diagnostics);
case SyntaxKind.ArgListExpression:
return BindArgList(node, diagnostics);
case SyntaxKind.RefTypeExpression:
return BindRefType((RefTypeExpressionSyntax)node, diagnostics);
case SyntaxKind.MakeRefExpression:
return BindMakeRef((MakeRefExpressionSyntax)node, diagnostics);
case SyntaxKind.RefValueExpression:
return BindRefValue((RefValueExpressionSyntax)node, diagnostics);
case SyntaxKind.AwaitExpression:
return BindAwait((AwaitExpressionSyntax)node, diagnostics);
case SyntaxKind.OmittedArraySizeExpression:
case SyntaxKind.OmittedTypeArgument:
case SyntaxKind.ObjectInitializerExpression:
// Not reachable during method body binding, but
// may be used by SemanticModel for error cases.
return BadExpression(node);
case SyntaxKind.NullableType:
// Not reachable during method body binding, but
// may be used by SemanticModel for error cases.
// NOTE: This happens when there's a problem with the Nullable<T> type (e.g. it's missing).
// There is no corresponding problem for array or pointer types (which seem analogous), since
// they are not constructed types; the element type can be an error type, but the array/pointer
// type cannot.
return BadExpression(node);
case SyntaxKind.InterpolatedStringExpression:
return BindInterpolatedString((InterpolatedStringExpressionSyntax)node, diagnostics);
case SyntaxKind.IsPatternExpression:
return BindIsPatternExpression((IsPatternExpressionSyntax)node, diagnostics);
case SyntaxKind.TupleExpression:
return BindTupleExpression((TupleExpressionSyntax)node, diagnostics);
case SyntaxKind.ThrowExpression:
return BindThrowExpression((ThrowExpressionSyntax)node, diagnostics);
case SyntaxKind.RefType:
return BindRefType(node, diagnostics);
case SyntaxKind.ScopedType:
return BindScopedType(node, diagnostics);
case SyntaxKind.RefExpression:
return BindRefExpression(node, diagnostics);
case SyntaxKind.DeclarationExpression:
return BindDeclarationExpressionAsError((DeclarationExpressionSyntax)node, diagnostics);
case SyntaxKind.SuppressNullableWarningExpression:
return BindSuppressNullableWarningExpression((PostfixUnaryExpressionSyntax)node, diagnostics);
case SyntaxKind.WithExpression:
return BindWithExpression((WithExpressionSyntax)node, diagnostics);
default:
// NOTE: We could probably throw an exception here, but it's conceivable
// that a non-parser syntax tree could reach this point with an unexpected
// SyntaxKind and we don't want to throw if that occurs.
Debug.Assert(false, "Unexpected SyntaxKind " + node.Kind());
diagnostics.Add(ErrorCode.ERR_InternalError, node.Location);
return BadExpression(node);
}
}
#nullable enable
internal virtual BoundSwitchExpressionArm BindSwitchExpressionArm(SwitchExpressionArmSyntax node, TypeSymbol switchGoverningType, BindingDiagnosticBag diagnostics)
{
return this.NextRequired.BindSwitchExpressionArm(node, switchGoverningType, diagnostics);
}
#nullable disable
private BoundExpression BindRefExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
var firstToken = node.GetFirstToken();
diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText);
return new BoundBadExpression(
node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray<BoundExpression>.Empty,
CreateErrorType("ref"));
}
private BoundExpression BindRefType(ExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
var firstToken = node.GetFirstToken();
diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText);
return new BoundTypeExpression(node, null, CreateErrorType("ref"));
}
private BoundExpression BindScopedType(ExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
var firstToken = node.GetFirstToken();
diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText);
return new BoundTypeExpression(node, null, CreateErrorType("scoped"));
}
private BoundExpression BindThrowExpression(ThrowExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
MessageID.IDS_FeatureThrowExpression.CheckFeatureAvailability(diagnostics, node, node.ThrowKeyword.GetLocation());
bool hasErrors = node.HasErrors;
if (!IsThrowExpressionInProperContext(node))
{
diagnostics.Add(ErrorCode.ERR_ThrowMisplaced, node.ThrowKeyword.GetLocation());
hasErrors = true;
}
var thrownExpression = BindThrownExpression(node.Expression, diagnostics, ref hasErrors);
return new BoundThrowExpression(node, thrownExpression, null, hasErrors);
}
private static bool IsThrowExpressionInProperContext(ThrowExpressionSyntax node)
{
var parent = node.Parent;
if (parent == null || node.HasErrors)
{
return true;
}
switch (parent.Kind())
{
case SyntaxKind.ConditionalExpression: // ?:
{
var conditionalParent = (ConditionalExpressionSyntax)parent;
return node == conditionalParent.WhenTrue || node == conditionalParent.WhenFalse;
}
case SyntaxKind.CoalesceExpression: // ??
{
var binaryParent = (BinaryExpressionSyntax)parent;
return node == binaryParent.Right;
}
case SyntaxKind.SwitchExpressionArm:
case SyntaxKind.ArrowExpressionClause:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
return true;
// We do not support && and || because
// 1. The precedence would not syntactically allow it
// 2. It isn't clear what the semantics should be
// 3. It isn't clear what use cases would motivate us to change the precedence to support it
default:
return false;
}
}
// Bind a declaration expression where it isn't permitted.
private BoundExpression BindDeclarationExpressionAsError(DeclarationExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
// This is an error, as declaration expressions are handled specially in every context in which
// they are permitted. So we have a context in which they are *not* permitted. Nevertheless, we
// bind it and then give one nice message.
bool isVar;
bool isConst = false;
AliasSymbol alias;
var declType = BindVariableTypeWithAnnotations(node.Designation, diagnostics, node.Type.SkipScoped(out _).SkipRef(), ref isConst, out isVar, out alias);
Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, node);
return BindDeclarationVariablesForErrorRecovery(declType, node.Designation, node, diagnostics);
}
/// <summary>
/// Bind a declaration variable where it isn't permitted. The caller is expected to produce a diagnostic.
/// </summary>
private BoundExpression BindDeclarationVariablesForErrorRecovery(TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics)
{
declTypeWithAnnotations = declTypeWithAnnotations.HasType ? declTypeWithAnnotations : TypeWithAnnotations.Create(CreateErrorType("var"));
switch (node.Kind())
{
case SyntaxKind.SingleVariableDesignation:
{
var single = (SingleVariableDesignationSyntax)node;
var result = BindDeconstructionVariable(declTypeWithAnnotations, single, syntax, diagnostics);
return BindToTypeForErrorRecovery(result);
}
case SyntaxKind.DiscardDesignation:
{
return BindDiscardExpression(syntax, declTypeWithAnnotations);
}
case SyntaxKind.ParenthesizedVariableDesignation:
{
var tuple = (ParenthesizedVariableDesignationSyntax)node;
int count = tuple.Variables.Count;
var builder = ArrayBuilder<BoundExpression>.GetInstance(count);
var namesBuilder = ArrayBuilder<string>.GetInstance(count);
foreach (var n in tuple.Variables)
{
builder.Add(BindDeclarationVariablesForErrorRecovery(declTypeWithAnnotations, n, n, diagnostics));
namesBuilder.Add(InferTupleElementName(n));
}
ImmutableArray<BoundExpression> subExpressions = builder.ToImmutableAndFree();
var uniqueFieldNames = PooledHashSet<string>.GetInstance();
RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref namesBuilder, uniqueFieldNames);
uniqueFieldNames.Free();
ImmutableArray<string> tupleNames = namesBuilder is null ? default : namesBuilder.ToImmutableAndFree();
ImmutableArray<bool> inferredPositions = tupleNames.IsDefault ? default : tupleNames.SelectAsArray(n => n != null);
bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames();
// We will not check constraints at this point as this code path
// is failure-only and the caller is expected to produce a diagnostic.
var tupleType = NamedTypeSymbol.CreateTuple(
locationOpt: null,
subExpressions.SelectAsArray(e => TypeWithAnnotations.Create(e.Type)),
elementLocations: default,
tupleNames,
Compilation,
shouldCheckConstraints: false,
includeNullability: false,
errorPositions: disallowInferredNames ? inferredPositions : default);
return new BoundConvertedTupleLiteral(syntax, sourceTuple: null, wasTargetTyped: true, subExpressions, tupleNames, inferredPositions, tupleType);
}
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
private BoundExpression BindTupleExpression(TupleExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
MessageID.IDS_FeatureTuples.CheckFeatureAvailability(diagnostics, node);
SeparatedSyntaxList<ArgumentSyntax> arguments = node.Arguments;
int numElements = arguments.Count;
if (numElements < 2)
{
// this should be a parse error already.
var args = numElements == 1 ?
ImmutableArray.Create(BindValue(arguments[0].Expression, diagnostics, BindValueKind.RValue)) :
ImmutableArray<BoundExpression>.Empty;
return BadExpression(node, args);
}
bool hasNaturalType = true;
var boundArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Count);
var elementTypesWithAnnotations = ArrayBuilder<TypeWithAnnotations>.GetInstance(arguments.Count);
var elementLocations = ArrayBuilder<Location>.GetInstance(arguments.Count);
// prepare names
var (elementNames, inferredPositions, hasErrors) = ExtractTupleElementNames(arguments, diagnostics);
// prepare types and locations
for (int i = 0; i < numElements; i++)
{
ArgumentSyntax argumentSyntax = arguments[i];
IdentifierNameSyntax nameSyntax = argumentSyntax.NameColon?.Name;
if (nameSyntax != null)
{
elementLocations.Add(nameSyntax.Location);
}
else
{
elementLocations.Add(argumentSyntax.Location);
}
BoundExpression boundArgument = BindValue(argumentSyntax.Expression, diagnostics, BindValueKind.RValue);