-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathForEachLoopBinder.cs
1939 lines (1663 loc) · 99.9 KB
/
ForEachLoopBinder.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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A loop binder that (1) knows how to bind foreach loops and (2) has the foreach iteration variable in scope.
/// </summary>
/// <remarks>
/// This binder produces BoundForEachStatements. The lowering described in the spec is performed in ControlFlowRewriter.
/// </remarks>
internal sealed class ForEachLoopBinder : LoopBinder
{
private readonly CommonForEachStatementSyntax _syntax;
private SourceLocalSymbol IterationVariable
{
get
{
return (_syntax.Kind() == SyntaxKind.ForEachStatement) ? (SourceLocalSymbol)this.Locals[0] : null;
}
}
private bool IsAsync
=> _syntax.AwaitKeyword != default;
public ForEachLoopBinder(Binder enclosing, CommonForEachStatementSyntax syntax)
: base(enclosing)
{
Debug.Assert(syntax != null);
_syntax = syntax;
}
internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator)
{
if (_syntax == scopeDesignator)
{
return this.Locals;
}
throw ExceptionUtilities.Unreachable();
}
internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator)
{
throw ExceptionUtilities.Unreachable();
}
internal override SyntaxNode ScopeDesignator
{
get
{
return _syntax;
}
}
protected override ImmutableArray<LocalSymbol> BuildLocals()
{
switch (_syntax.Kind())
{
case SyntaxKind.ForEachVariableStatement:
{
var syntax = (ForEachVariableStatementSyntax)_syntax;
var locals = ArrayBuilder<LocalSymbol>.GetInstance();
CollectLocalsFromDeconstruction(
syntax.Variable,
LocalDeclarationKind.ForEachIterationVariable,
locals,
syntax);
return locals.ToImmutableAndFree();
}
case SyntaxKind.ForEachStatement:
{
var syntax = (ForEachStatementSyntax)_syntax;
var iterationVariable = SourceLocalSymbol.MakeForeachLocal(
(MethodSymbol)this.ContainingMemberOrLambda,
this,
syntax.Type,
syntax.Identifier,
syntax.Expression);
return ImmutableArray.Create<LocalSymbol>(iterationVariable);
}
default:
throw ExceptionUtilities.UnexpectedValue(_syntax.Kind());
}
}
internal void CollectLocalsFromDeconstruction(
ExpressionSyntax declaration,
LocalDeclarationKind kind,
ArrayBuilder<LocalSymbol> locals,
SyntaxNode deconstructionStatement,
Binder enclosingBinderOpt = null)
{
switch (declaration.Kind())
{
case SyntaxKind.TupleExpression:
{
var tuple = (TupleExpressionSyntax)declaration;
foreach (var arg in tuple.Arguments)
{
CollectLocalsFromDeconstruction(arg.Expression, kind, locals, deconstructionStatement, enclosingBinderOpt);
}
break;
}
case SyntaxKind.DeclarationExpression:
{
var declarationExpression = (DeclarationExpressionSyntax)declaration;
CollectLocalsFromDeconstruction(
declarationExpression.Designation, declarationExpression.Type,
kind, locals, deconstructionStatement, enclosingBinderOpt);
break;
}
case SyntaxKind.IdentifierName:
break;
default:
// In broken code, we can have an arbitrary expression here. Collect its expression variables.
ExpressionVariableFinder.FindExpressionVariables(this, locals, declaration);
break;
}
}
internal void CollectLocalsFromDeconstruction(
VariableDesignationSyntax designation,
TypeSyntax closestTypeSyntax,
LocalDeclarationKind kind,
ArrayBuilder<LocalSymbol> locals,
SyntaxNode deconstructionStatement,
Binder enclosingBinderOpt)
{
switch (designation.Kind())
{
case SyntaxKind.SingleVariableDesignation:
{
var single = (SingleVariableDesignationSyntax)designation;
SourceLocalSymbol localSymbol = SourceLocalSymbol.MakeDeconstructionLocal(
this.ContainingMemberOrLambda,
this,
enclosingBinderOpt ?? this,
closestTypeSyntax,
single.Identifier,
kind,
deconstructionStatement);
locals.Add(localSymbol);
break;
}
case SyntaxKind.ParenthesizedVariableDesignation:
{
var tuple = (ParenthesizedVariableDesignationSyntax)designation;
foreach (var d in tuple.Variables)
{
CollectLocalsFromDeconstruction(d, closestTypeSyntax, kind, locals, deconstructionStatement, enclosingBinderOpt);
}
break;
}
case SyntaxKind.DiscardDesignation:
break;
default:
throw ExceptionUtilities.UnexpectedValue(designation.Kind());
}
}
/// <summary>
/// Bind the ForEachStatementSyntax at the root of this binder.
/// </summary>
internal override BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder)
{
BoundForEachStatement result = BindForEachPartsWorker(diagnostics, originalBinder);
return result;
}
/// <summary>
/// Like BindForEachParts, but only bind the deconstruction part of the foreach, for purpose of inferring the types of the declared locals.
/// </summary>
internal override BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder)
{
// Use the right binder to avoid seeing iteration variable
BoundExpression collectionExpr = originalBinder.GetBinder(_syntax.Expression).BindRValueWithoutTargetType(_syntax.Expression, diagnostics);
TypeWithAnnotations inferredType;
bool hasErrors = !GetEnumeratorInfoAndInferCollectionElementType(_syntax, _syntax.Expression, ref collectionExpr, isAsync: IsAsync, isSpread: false, diagnostics, out inferredType, builder: out _);
ExpressionSyntax variables = ((ForEachVariableStatementSyntax)_syntax).Variable;
// Tracking narrowest safe-to-escape scope by default, the proper val escape will be set when doing full binding of the foreach statement
var valuePlaceholder = new BoundDeconstructValuePlaceholder(_syntax.Expression, variableSymbol: null, isDiscardExpression: false, inferredType.Type ?? CreateErrorType("var"));
DeclarationExpressionSyntax declaration = null;
ExpressionSyntax expression = null;
BoundDeconstructionAssignmentOperator deconstruction = BindDeconstruction(
variables,
variables,
right: _syntax.Expression,
diagnostics: diagnostics,
rightPlaceholder: valuePlaceholder,
declaration: ref declaration,
expression: ref expression);
return new BoundExpressionStatement(_syntax, deconstruction);
}
private BoundForEachStatement BindForEachPartsWorker(BindingDiagnosticBag diagnostics, Binder originalBinder)
{
if (IsAsync)
{
CheckFeatureAvailability(_syntax.AwaitKeyword, MessageID.IDS_FeatureAsyncStreams, diagnostics);
}
// Use the right binder to avoid seeing iteration variable
BoundExpression collectionExpr = originalBinder.GetBinder(_syntax.Expression).BindRValueWithoutTargetType(_syntax.Expression, diagnostics);
ForEachEnumeratorInfo.Builder builder;
TypeWithAnnotations inferredType;
bool hasErrors = !GetEnumeratorInfoAndInferCollectionElementType(_syntax, _syntax.Expression, ref collectionExpr, isAsync: IsAsync, isSpread: false, diagnostics, out inferredType, out builder);
// These occur when special types are missing or malformed, or the patterns are incompletely implemented.
hasErrors |= builder.IsIncomplete;
BoundAwaitableInfo awaitInfo = null;
MethodSymbol getEnumeratorMethod = builder.GetEnumeratorInfo?.Method;
if (getEnumeratorMethod != null)
{
originalBinder.CheckImplicitThisCopyInReadOnlyMember(collectionExpr, getEnumeratorMethod, diagnostics);
if (getEnumeratorMethod.IsExtensionMethod && !hasErrors)
{
var messageId = IsAsync ? MessageID.IDS_FeatureExtensionGetAsyncEnumerator : MessageID.IDS_FeatureExtensionGetEnumerator;
messageId.CheckFeatureAvailability(diagnostics, Compilation, collectionExpr.Syntax.Location);
if (getEnumeratorMethod.ParameterRefKinds is { IsDefault: false } refKinds && refKinds[0] == RefKind.Ref)
{
Error(diagnostics, ErrorCode.ERR_RefLvalueExpected, collectionExpr.Syntax);
hasErrors = true;
}
}
}
if (IsAsync)
{
var expr = _syntax.Expression;
ReportBadAwaitDiagnostics(_syntax.AwaitKeyword, diagnostics, ref hasErrors);
var placeholder = new BoundAwaitableValuePlaceholder(expr, builder.MoveNextInfo?.Method.ReturnType ?? CreateErrorType());
awaitInfo = BindAwaitInfo(placeholder, expr, diagnostics, ref hasErrors);
if (!hasErrors && awaitInfo.GetResult?.ReturnType.SpecialType != SpecialType.System_Boolean)
{
diagnostics.Add(ErrorCode.ERR_BadGetAsyncEnumerator, expr.Location, getEnumeratorMethod.ReturnTypeWithAnnotations, getEnumeratorMethod);
hasErrors = true;
}
}
TypeWithAnnotations iterationVariableType;
BoundTypeExpression boundIterationVariableType;
bool hasNameConflicts = false;
BoundForEachDeconstructStep deconstructStep = null;
BoundExpression iterationErrorExpression = null;
switch (_syntax.Kind())
{
case SyntaxKind.ForEachStatement:
{
var node = (ForEachStatementSyntax)_syntax;
// Check for local variable conflicts in the *enclosing* binder; obviously the *current*
// binder has a local that matches!
hasNameConflicts = originalBinder.ValidateDeclarationNameConflictsInScope(IterationVariable, diagnostics);
// If the type in syntax is "var", then the type should be set explicitly so that the
// Type property doesn't fail.
TypeSyntax typeSyntax = node.Type;
if (typeSyntax is ScopedTypeSyntax scopedType)
{
// Check for support for 'scoped'.
ModifierUtils.CheckScopedModifierAvailability(typeSyntax, scopedType.ScopedKeyword, diagnostics);
typeSyntax = scopedType.Type;
}
if (typeSyntax is RefTypeSyntax refType)
{
MessageID.IDS_FeatureRefForEach.CheckFeatureAvailability(diagnostics, typeSyntax);
typeSyntax = refType.Type;
}
bool isVar;
AliasSymbol alias;
TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar, out alias);
if (isVar)
{
declType = inferredType.HasType ? inferredType : TypeWithAnnotations.Create(CreateErrorType("var"));
}
else
{
Debug.Assert(declType.HasType);
}
iterationVariableType = declType;
boundIterationVariableType = new BoundTypeExpression(typeSyntax, alias, iterationVariableType);
SourceLocalSymbol local = this.IterationVariable;
local.SetTypeWithAnnotations(declType);
CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declType.Type, diagnostics, typeSyntax);
if (local.Scope == ScopedKind.ScopedValue && !declType.Type.IsErrorOrRefLikeOrAllowsRefLikeType())
{
diagnostics.Add(ErrorCode.ERR_ScopedRefAndRefStructOnly, typeSyntax.Location);
}
if (local.RefKind != RefKind.None)
{
if (CheckRefLocalInAsyncOrIteratorMethod(local.IdentifierToken, diagnostics))
{
hasErrors = true;
}
}
if (!hasErrors)
{
BindValueKind requiredCurrentKind;
switch (local.RefKind)
{
case RefKind.None:
requiredCurrentKind = BindValueKind.RValue;
break;
case RefKind.Ref:
requiredCurrentKind = BindValueKind.Assignable | BindValueKind.RefersToLocation;
break;
case RefKind.RefReadOnly:
requiredCurrentKind = BindValueKind.RefersToLocation;
break;
default:
throw ExceptionUtilities.UnexpectedValue(local.RefKind);
}
if (builder.InlineArraySpanType == WellKnownType.Unknown)
{
hasErrors |= !CheckMethodReturnValueKind(
builder.CurrentPropertyGetter,
callSyntaxOpt: null,
collectionExpr.Syntax,
requiredCurrentKind,
checkingReceiver: false,
diagnostics);
}
else
{
hasErrors |= !CheckValueKind(collectionExpr.Syntax, collectionExpr, requiredCurrentKind, checkingReceiver: false, diagnostics);
}
}
break;
}
case SyntaxKind.ForEachVariableStatement:
{
var node = (ForEachVariableStatementSyntax)_syntax;
iterationVariableType = inferredType.HasType ? inferredType : TypeWithAnnotations.Create(CreateErrorType("var"));
var variables = node.Variable;
if (variables.IsDeconstructionLeft())
{
var valuePlaceholder = new BoundDeconstructValuePlaceholder(_syntax.Expression, variableSymbol: null, isDiscardExpression: false, iterationVariableType.Type).MakeCompilerGenerated();
DeclarationExpressionSyntax declaration = null;
ExpressionSyntax expression = null;
BoundDeconstructionAssignmentOperator deconstruction = BindDeconstruction(
variables,
variables,
right: _syntax.Expression,
diagnostics: diagnostics,
rightPlaceholder: valuePlaceholder,
declaration: ref declaration,
expression: ref expression);
if (expression != null)
{
// error: must declare foreach loop iteration variables.
Error(diagnostics, ErrorCode.ERR_MustDeclareForeachIteration, variables);
hasErrors = true;
}
deconstructStep = new BoundForEachDeconstructStep(variables, deconstruction, valuePlaceholder).MakeCompilerGenerated();
}
else
{
// Bind the expression for error recovery, but discard all new diagnostics
iterationErrorExpression = BindToTypeForErrorRecovery(BindExpression(node.Variable, BindingDiagnosticBag.Discarded));
if (iterationErrorExpression.Kind == BoundKind.DiscardExpression)
{
iterationErrorExpression = ((BoundDiscardExpression)iterationErrorExpression).FailInference(this, diagnosticsOpt: null);
}
hasErrors = true;
if (!node.HasErrors)
{
Error(diagnostics, ErrorCode.ERR_MustDeclareForeachIteration, variables);
}
}
boundIterationVariableType = new BoundTypeExpression(variables, aliasOpt: null, typeWithAnnotations: iterationVariableType).MakeCompilerGenerated();
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(_syntax.Kind());
}
BoundStatement body = originalBinder.BindPossibleEmbeddedStatement(_syntax.Statement, diagnostics);
// NOTE: in error cases, binder may collect all kind of variables, not just formally declared iteration variables.
// As a matter of error recovery, we will treat such variables the same as the iteration variables.
// I.E. - they will be considered declared and assigned in each iteration step.
ImmutableArray<LocalSymbol> iterationVariables = this.Locals;
Debug.Assert(hasErrors ||
_syntax.HasErrors ||
iterationVariables.All(local => local.DeclarationKind == LocalDeclarationKind.ForEachIterationVariable),
"Should not have iteration variables that are not ForEachIterationVariable in valid code");
hasErrors = hasErrors || boundIterationVariableType.HasErrors || iterationVariableType.Type.IsErrorType();
// Skip the conversion checks and array/enumerator differentiation if we know we have an error (except local name conflicts).
if (hasErrors)
{
return new BoundForEachStatement(
_syntax,
enumeratorInfoOpt: null, // can't be sure that it's complete
elementPlaceholder: null,
elementConversion: null,
boundIterationVariableType,
iterationVariables,
iterationErrorExpression,
collectionExpr,
deconstructStep,
awaitInfo,
body,
this.BreakLabel,
this.ContinueLabel,
hasErrors);
}
hasErrors |= hasNameConflicts;
var foreachKeyword = _syntax.ForEachKeyword;
ReportDiagnosticsIfObsolete(diagnostics, getEnumeratorMethod, foreachKeyword, hasBaseReceiver: false);
ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, getEnumeratorMethod, foreachKeyword, isDelegateConversion: false);
// MoveNext is an instance method, so it does not need to have unmanaged callers only diagnostics reported.
// Either a diagnostic was reported at the declaration of the method (for the invalid attribute), or MoveNext
// is marked as not supported and we won't get here in the first place (for metadata import).
ReportDiagnosticsIfObsolete(diagnostics, builder.MoveNextInfo.Method, foreachKeyword, hasBaseReceiver: false);
ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter, foreachKeyword, hasBaseReceiver: false);
ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter.AssociatedSymbol, foreachKeyword, hasBaseReceiver: false);
// We want to convert from inferredType in the array/string case and builder.ElementType in the enumerator case,
// but it turns out that these are equivalent (when both are available).
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
Conversion elementConversionClassification = this.Conversions.ClassifyConversionFromType(inferredType.Type, iterationVariableType.Type, isChecked: CheckOverflowAtRuntime, ref useSiteInfo, forCast: true);
if (elementConversionClassification.Kind != ConversionKind.Identity && IterationVariable.RefKind is RefKind.Ref or RefKind.RefReadOnly)
{
Error(diagnostics, ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion, collectionExpr.Syntax, iterationVariableType.Type);
hasErrors = true;
}
var elementPlaceholder = new BoundValuePlaceholder(_syntax, inferredType.Type).MakeCompilerGenerated();
BindingDiagnosticBag createConversionDiagnostics;
if (!elementConversionClassification.IsValid)
{
ImmutableArray<MethodSymbol> originalUserDefinedConversions = elementConversionClassification.OriginalUserDefinedConversions;
if (originalUserDefinedConversions.Length > 1)
{
diagnostics.Add(ErrorCode.ERR_AmbigUDConv, foreachKeyword.GetLocation(), originalUserDefinedConversions[0], originalUserDefinedConversions[1], inferredType.Type, iterationVariableType);
}
else
{
SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, inferredType.Type, iterationVariableType.Type);
diagnostics.Add(ErrorCode.ERR_NoExplicitConv, foreachKeyword.GetLocation(), distinguisher.First, distinguisher.Second);
}
hasErrors = true;
createConversionDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: false, withDependencies: false);
}
else
{
createConversionDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics);
}
BoundExpression elementConversion = CreateConversion(_syntax, elementPlaceholder, elementConversionClassification, isCast: false, conversionGroupOpt: null, iterationVariableType.Type, createConversionDiagnostics);
if (createConversionDiagnostics.AccumulatesDiagnostics && !createConversionDiagnostics.DiagnosticBag.IsEmptyWithoutResolution)
{
diagnostics.AddDependencies(createConversionDiagnostics);
var location = _syntax.ForEachKeyword.GetLocation();
foreach (var d in createConversionDiagnostics.DiagnosticBag.AsEnumerableWithoutResolution())
{
diagnostics.Add(d.WithLocation(location));
}
}
else
{
diagnostics.AddRange(createConversionDiagnostics);
}
createConversionDiagnostics.Free();
// Spec (§8.8.4):
// If the type X of expression is dynamic then there is an implicit conversion from >>expression<< (not the type of the expression)
// to the System.Collections.IEnumerable interface (§6.1.8).
Conversion collectionConversionClassification = this.Conversions.ClassifyConversionFromExpression(collectionExpr, builder.CollectionType, isChecked: CheckOverflowAtRuntime, ref useSiteInfo);
Conversion currentConversionClassification = this.Conversions.ClassifyConversionFromType(builder.CurrentPropertyGetter.ReturnType, builder.ElementType, isChecked: CheckOverflowAtRuntime, ref useSiteInfo);
TypeSymbol getEnumeratorType = getEnumeratorMethod.ReturnType;
if (builder.InlineArraySpanType == WellKnownType.Unknown && getEnumeratorType.IsRestrictedType() && (IsDirectlyInIterator || IsInAsyncMethod()))
{
CheckFeatureAvailability(foreachKeyword, MessageID.IDS_FeatureRefUnsafeInIteratorAsync, diagnostics);
}
diagnostics.Add(_syntax.ForEachKeyword, useSiteInfo);
// Due to the way we extracted the various types, these conversions should always be possible.
// CAVEAT: if we're iterating over an array of pointers, the current conversion will fail since we
// can't convert from object to a pointer type. Similarly, if we're iterating over an array of
// Nullable<Error>, the current conversion will fail because we don't know if an ErrorType is a
// value type. This doesn't matter in practice, since we won't actually use the enumerator pattern
// when we lower the loop.
Debug.Assert(collectionConversionClassification.IsValid);
Debug.Assert(currentConversionClassification.IsValid ||
(builder.ElementType.IsPointerOrFunctionPointer() && collectionExpr.Type.IsArray()) ||
(builder.ElementType.IsNullableType() && builder.ElementType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single().IsErrorType() && collectionExpr.Type.IsArray()));
// If user-defined conversions could occur here, we would need to check for ObsoleteAttribute.
Debug.Assert((object)collectionConversionClassification.Method == null,
"Conversion from collection expression to collection type should not be user-defined");
Debug.Assert((object)currentConversionClassification.Method == null,
"Conversion from Current property type to element type should not be user-defined");
BoundExpression convertedCollectionExpression = ConvertForEachCollection(collectionExpr, collectionConversionClassification, builder.CollectionType, diagnostics);
if (currentConversionClassification.IsValid)
{
builder.CurrentPlaceholder = new BoundValuePlaceholder(_syntax, builder.CurrentPropertyGetter.ReturnType).MakeCompilerGenerated();
builder.CurrentConversion = CreateConversion(_syntax, builder.CurrentPlaceholder, currentConversionClassification, isCast: false, conversionGroupOpt: null, builder.ElementType, diagnostics);
}
if (builder.NeedsDisposal && IsAsync)
{
hasErrors |= GetAwaitDisposeAsyncInfo(ref builder, diagnostics);
}
Debug.Assert(
hasErrors ||
collectionConversionClassification.IsIdentity ||
(collectionConversionClassification.IsImplicit &&
(IsIEnumerable(builder.CollectionType) ||
IsIEnumerableT(builder.CollectionType.OriginalDefinition, IsAsync, Compilation) ||
builder.GetEnumeratorInfo.Method.IsExtensionMethod)) ||
// For compat behavior, we can enumerate over System.String even if it's not IEnumerable. That will
// result in an explicit reference conversion in the bound nodes, but that conversion won't be emitted.
(collectionConversionClassification.Kind == ConversionKind.ExplicitReference && collectionExpr.Type.SpecialType == SpecialType.System_String));
return new BoundForEachStatement(
_syntax,
builder.Build(this.Flags),
elementPlaceholder,
elementConversion,
boundIterationVariableType,
iterationVariables,
iterationErrorExpression,
convertedCollectionExpression,
deconstructStep,
awaitInfo,
body,
this.BreakLabel,
this.ContinueLabel,
hasErrors);
}
private bool GetAwaitDisposeAsyncInfo(ref ForEachEnumeratorInfo.Builder builder, BindingDiagnosticBag diagnostics)
{
var awaitableType = builder.PatternDisposeInfo is null
? this.GetWellKnownType(WellKnownType.System_Threading_Tasks_ValueTask, diagnostics, this._syntax)
: builder.PatternDisposeInfo.Method.ReturnType;
bool hasErrors = false;
var expr = _syntax.Expression;
ReportBadAwaitDiagnostics(_syntax.AwaitKeyword, diagnostics, ref hasErrors);
var placeholder = new BoundAwaitableValuePlaceholder(expr, awaitableType);
builder.DisposeAwaitableInfo = BindAwaitInfo(placeholder, expr, diagnostics, ref hasErrors);
return hasErrors;
}
internal TypeWithAnnotations InferCollectionElementType(BindingDiagnosticBag diagnostics, ExpressionSyntax collectionSyntax)
{
// Use the right binder to avoid seeing iteration variable
BoundExpression collectionExpr = this.GetBinder(collectionSyntax).BindValue(collectionSyntax, diagnostics, BindValueKind.RValue);
GetEnumeratorInfoAndInferCollectionElementType(_syntax, collectionSyntax, ref collectionExpr, isAsync: IsAsync, isSpread: false, diagnostics, out TypeWithAnnotations inferredType, builder: out _);
return inferredType;
}
}
partial class Binder
{
protected BoundExpression ConvertForEachCollection(
BoundExpression collectionExpr,
Conversion collectionConversionClassification,
TypeSymbol collectionType,
BindingDiagnosticBag diagnostics)
{
// We're wrapping the collection expression in a (non-synthesized) conversion so that its converted
// type (i.e. builder.CollectionType) will be available in the binding API.
Debug.Assert(!collectionConversionClassification.IsUserDefined);
BoundExpression convertedCollectionExpression = CreateConversion(
collectionExpr.Syntax,
collectionExpr,
collectionConversionClassification,
isCast: false,
conversionGroupOpt: null,
collectionType,
diagnostics);
if ((convertedCollectionExpression as BoundConversion)?.Operand != (object)collectionExpr)
{
Debug.Assert(collectionConversionClassification.IsIdentity);
Debug.Assert(convertedCollectionExpression == (object)collectionExpr);
Debug.Assert(collectionType.Equals(collectionExpr.Type, TypeCompareKind.AllIgnoreOptions)); // Should not create an Identity conversion that changes type.
convertedCollectionExpression = new BoundConversion(
collectionExpr.Syntax,
collectionExpr,
collectionConversionClassification,
@checked: CheckOverflowAtRuntime,
explicitCastInCode: false,
conversionGroupOpt: null,
ConstantValue.NotAvailable,
collectionType);
}
return convertedCollectionExpression;
}
internal bool GetEnumeratorInfoAndInferCollectionElementType(
SyntaxNode syntax,
SyntaxNode collectionSyntax,
ref BoundExpression collectionExpr,
bool isAsync,
bool isSpread,
BindingDiagnosticBag diagnostics,
out TypeWithAnnotations inferredType,
out ForEachEnumeratorInfo.Builder builder)
{
Debug.Assert(!isAsync || !isSpread);
bool gotInfo = GetEnumeratorInfo(syntax, collectionSyntax, ref collectionExpr, isAsync, isSpread, diagnostics, out builder);
if (!gotInfo)
{
inferredType = default;
}
else if (collectionExpr.HasDynamicType())
{
// If the enumerator is dynamic, it yields dynamic values
inferredType = TypeWithAnnotations.Create(DynamicTypeSymbol.Instance);
}
else if (collectionExpr.Type.SpecialType == SpecialType.System_String && builder.CollectionType.SpecialType == SpecialType.System_Collections_IEnumerable)
{
// Reproduce dev11 behavior: we're always going to lower a foreach loop over a string to a for loop
// over the string's Chars indexer. Therefore, we should infer "char", regardless of what the spec
// indicates the element type is. This actually matters in practice because the System.String in
// the portable library doesn't have a pattern GetEnumerator method or implement IEnumerable<char>.
inferredType = TypeWithAnnotations.Create(GetSpecialType(SpecialType.System_Char, diagnostics, collectionExpr.Syntax));
}
else
{
inferredType = builder.ElementTypeWithAnnotations;
}
return gotInfo;
}
private BoundExpression UnwrapCollectionExpressionIfNullable(BoundExpression collectionExpr, BindingDiagnosticBag diagnostics)
{
TypeSymbol collectionExprType = collectionExpr.Type;
// If collectionExprType is a nullable type, then use the underlying type and take the value (i.e. .Value) of collectionExpr.
// This behavior is not spec'd, but it's what Dev10 does.
if ((object)collectionExprType != null && collectionExprType.IsNullableType())
{
SyntaxNode exprSyntax = collectionExpr.Syntax;
MethodSymbol nullableValueGetter = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value, diagnostics, exprSyntax);
if ((object)nullableValueGetter != null)
{
nullableValueGetter = nullableValueGetter.AsMember((NamedTypeSymbol)collectionExprType);
// Synthesized call, because we don't want to modify the type in the SemanticModel.
return BoundCall.Synthesized(
syntax: exprSyntax,
receiverOpt: collectionExpr,
initialBindingReceiverIsSubjectToCloning: ReceiverIsSubjectToCloning(collectionExpr, nullableValueGetter),
method: nullableValueGetter);
}
else
{
return new BoundBadExpression(
exprSyntax,
LookupResultKind.Empty,
ImmutableArray<Symbol>.Empty,
ImmutableArray.Create(collectionExpr),
collectionExprType.GetNullableUnderlyingType())
{ WasCompilerGenerated = true }; // Don't affect the type in the SemanticModel.
}
}
return collectionExpr;
}
/// <summary>
/// The spec describes an algorithm for finding the following types:
/// 1) Collection type
/// 2) Enumerator type
/// 3) Element type
///
/// The implementation details are a bit different. If we're iterating over a string or an array, then we don't need to record anything
/// but the inferredType (in case the iteration variable is implicitly typed). If we're iterating over anything else, then we want the
/// inferred type plus a ForEachEnumeratorInfo.Builder with:
/// 1) Collection type
/// 2) Element type
/// 3) GetEnumerator (or GetAsyncEnumerator) method of the collection type (return type will be the enumerator type from the spec)
/// 4) Current property and MoveNext (or MoveNextAsync) method of the enumerator type
///
/// The caller will have to do some extra conversion checks before creating a ForEachEnumeratorInfo for the BoundForEachStatement.
/// </summary>
/// <param name="builder">Builder to fill in (partially, all but conversions).</param>
/// <param name="collectionExpr">The expression over which to iterate.</param>
/// <param name="diagnostics">Populated with binding diagnostics.</param>
/// <returns>Partially populated (all but conversions) or null if there was an error.</returns>
private bool GetEnumeratorInfo(
SyntaxNode syntax,
SyntaxNode collectionSyntax,
ref BoundExpression collectionExpr,
bool isAsync,
bool isSpread,
BindingDiagnosticBag diagnostics,
out ForEachEnumeratorInfo.Builder builder)
{
Debug.Assert(!isAsync || !isSpread);
BoundExpression originalCollectionExpr = collectionExpr;
EnumeratorResult found = GetEnumeratorInfoCore(syntax, collectionSyntax, ref collectionExpr, isAsync, diagnostics, out builder);
switch (found)
{
case EnumeratorResult.Succeeded:
return true;
case EnumeratorResult.FailedAndReported:
return false;
}
TypeSymbol collectionExprType = collectionExpr.Type;
if (string.IsNullOrEmpty(collectionExprType.Name) && collectionExpr.HasErrors)
{
return false;
}
if (collectionExprType.IsErrorType())
{
return false;
}
// Retry with a different assumption about whether the foreach is async
bool wrongAsync = GetEnumeratorInfoCore(syntax, collectionSyntax, ref originalCollectionExpr, !isAsync, BindingDiagnosticBag.Discarded, builder: out _) == EnumeratorResult.Succeeded;
ErrorCode errorCode = (wrongAsync, isAsync, isSpread) switch
{
(true, true, _) => ErrorCode.ERR_AwaitForEachMissingMemberWrongAsync,
(true, false, _) => ErrorCode.ERR_ForEachMissingMemberWrongAsync,
(false, true, _) => ErrorCode.ERR_AwaitForEachMissingMember,
(false, false, true) => ErrorCode.ERR_SpreadMissingMember,
(false, false, false) => ErrorCode.ERR_ForEachMissingMember,
};
diagnostics.Add(errorCode, collectionSyntax.Location,
collectionExprType, isAsync ? WellKnownMemberNames.GetAsyncEnumeratorMethodName : WellKnownMemberNames.GetEnumeratorMethodName);
return false;
}
private enum EnumeratorResult
{
Succeeded,
FailedNotReported,
FailedAndReported
}
private EnumeratorResult GetEnumeratorInfoCore(SyntaxNode syntax, SyntaxNode collectionSyntax, ref BoundExpression collectionExpr, bool isAsync, BindingDiagnosticBag diagnostics, out ForEachEnumeratorInfo.Builder builder)
{
EnumeratorResult result;
if (!isAsync && collectionExpr.Type?.HasInlineArrayAttribute(out _) == true && collectionExpr.Type.TryGetPossiblyUnsupportedByLanguageInlineArrayElementField() is FieldSymbol elementField)
{
WellKnownType wellKnownSpan;
bool usedAsValue = false;
if (CheckValueKind(collectionExpr.Syntax, collectionExpr, BindValueKind.RefersToLocation | BindValueKind.Assignable, checkingReceiver: false, BindingDiagnosticBag.Discarded))
{
wellKnownSpan = WellKnownType.System_Span_T;
}
else
{
wellKnownSpan = WellKnownType.System_ReadOnlySpan_T;
if (!CheckValueKind(collectionExpr.Syntax, collectionExpr, BindValueKind.RefersToLocation, checkingReceiver: false, BindingDiagnosticBag.Discarded))
{
usedAsValue = true;
}
}
NamedTypeSymbol spanType = GetWellKnownType(wellKnownSpan, diagnostics, collectionExpr.Syntax);
if (spanType.IsErrorType())
{
builder = new ForEachEnumeratorInfo.Builder();
return EnumeratorResult.FailedAndReported;
}
spanType = spanType.Construct(ImmutableArray.Create(elementField.TypeWithAnnotations));
if (!TypeSymbol.IsInlineArrayElementFieldSupported(elementField))
{
diagnostics.Add(ErrorCode.ERR_InlineArrayForEachNotSupported, collectionExpr.Syntax.GetLocation(), collectionExpr.Type);
builder = new ForEachEnumeratorInfo.Builder();
return EnumeratorResult.FailedAndReported;
}
var enumeratorInfoDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics);
BoundExpression span = new BoundValuePlaceholder(collectionExpr.Syntax, spanType).MakeCompilerGenerated();
#if DEBUG
var originalSpan = span;
#endif
result = getEnumeratorInfo(syntax, collectionSyntax, ref span, isAsync: false, enumeratorInfoDiagnostics, out builder);
#if DEBUG
Debug.Assert(span == originalSpan);
Debug.Assert(!builder.ViaExtensionMethod || builder.GetEnumeratorInfo.Method.IsExtensionMethod);
#endif
if (!builder.ViaExtensionMethod &&
((result is EnumeratorResult.Succeeded && builder.ElementTypeWithAnnotations.Equals(elementField.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions) &&
builder.CurrentPropertyGetter?.RefKind == (wellKnownSpan == WellKnownType.System_ReadOnlySpan_T ? RefKind.RefReadOnly : RefKind.Ref)) ||
result is EnumeratorResult.FailedAndReported))
{
Debug.Assert(builder.CollectionType == (object)spanType);
builder.CollectionType = collectionExpr.Type;
builder.InlineArraySpanType = wellKnownSpan;
builder.InlineArrayUsedAsValue = usedAsValue;
diagnostics.AddRangeAndFree(enumeratorInfoDiagnostics);
CheckFeatureAvailability(collectionExpr.Syntax, MessageID.IDS_FeatureInlineArrays, diagnostics);
if (result == EnumeratorResult.Succeeded)
{
if (wellKnownSpan == WellKnownType.System_ReadOnlySpan_T)
{
_ = GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_Unsafe__AsRef_T, diagnostics, syntax: collectionExpr.Syntax);
}
_ = GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_Unsafe__Add_T, diagnostics, syntax: collectionExpr.Syntax);
_ = GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_Unsafe__As_T, diagnostics, syntax: collectionExpr.Syntax);
CheckInlineArrayTypeIsSupported(collectionExpr.Syntax, collectionExpr.Type, elementField.Type, diagnostics);
}
return result;
}
enumeratorInfoDiagnostics.Free();
diagnostics.Add(ErrorCode.ERR_InlineArrayForEachNotSupported, collectionExpr.Syntax.GetLocation(), collectionExpr.Type);
builder = new ForEachEnumeratorInfo.Builder();
return EnumeratorResult.FailedAndReported;
}
#if DEBUG
var originalCollectionExpr = collectionExpr;
#endif
result = getEnumeratorInfo(syntax, collectionSyntax, ref collectionExpr, isAsync, diagnostics, out builder);
#if DEBUG
Debug.Assert(collectionExpr == originalCollectionExpr ||
(originalCollectionExpr.Type?.IsNullableType() == true && originalCollectionExpr.Type.StrippedType().Equals(collectionExpr.Type, TypeCompareKind.AllIgnoreOptions)));
Debug.Assert(!builder.ViaExtensionMethod || builder.GetEnumeratorInfo.Method.IsExtensionMethod);
#endif
return result;
EnumeratorResult getEnumeratorInfo(SyntaxNode syntax, SyntaxNode collectionSyntax, ref BoundExpression collectionExpr, bool isAsync, BindingDiagnosticBag diagnostics, out ForEachEnumeratorInfo.Builder builder)
{
builder = new ForEachEnumeratorInfo.Builder();
builder.IsAsync = isAsync;
TypeSymbol collectionExprType = collectionExpr.Type;
if (collectionExprType is null) // There's no way to enumerate something without a type.
{
if (!ReportConstantNullCollectionExpr(collectionExpr, diagnostics))
{
// Anything else with a null type is a method group or anonymous function
diagnostics.Add(ErrorCode.ERR_AnonMethGrpInForEach, collectionSyntax.Location, collectionExpr.Display);
}
// CONSIDER: dev10 also reports ERR_ForEachMissingMember (i.e. failed pattern match).
return EnumeratorResult.FailedAndReported;
}
if (collectionExpr.ResultKind == LookupResultKind.NotAValue)
{
// Short-circuiting to prevent strange behavior in the case where the collection
// expression is a type expression and the type is enumerable.
Debug.Assert(collectionExpr.HasAnyErrors); // should already have been reported
return EnumeratorResult.FailedAndReported;
}
if (collectionExprType.Kind == SymbolKind.DynamicType && isAsync)
{
diagnostics.Add(ErrorCode.ERR_BadDynamicAwaitForEach, collectionSyntax.Location);
return EnumeratorResult.FailedAndReported;
}
// The spec specifically lists the collection, enumerator, and element types for arrays and dynamic.
if (collectionExprType.Kind == SymbolKind.ArrayType || collectionExprType.Kind == SymbolKind.DynamicType)
{
if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics))
{
return EnumeratorResult.FailedAndReported;
}
builder = GetDefaultEnumeratorInfo(syntax, builder, diagnostics, collectionExprType);
return EnumeratorResult.Succeeded;
}
var unwrappedCollectionExpr = UnwrapCollectionExpressionIfNullable(collectionExpr, diagnostics);
var unwrappedCollectionExprType = unwrappedCollectionExpr.Type;
if (SatisfiesGetEnumeratorPattern(syntax, collectionSyntax, ref builder, unwrappedCollectionExpr, isAsync, viaExtensionMethod: false, diagnostics))
{
collectionExpr = unwrappedCollectionExpr;
if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics))
{
return EnumeratorResult.FailedAndReported;
}
return createPatternBasedEnumeratorResult(ref builder, unwrappedCollectionExpr, isAsync, viaExtensionMethod: false, diagnostics);
}
if (!isAsync && IsIEnumerable(unwrappedCollectionExprType))
{
collectionExpr = unwrappedCollectionExpr;
// This indicates a problem with the special IEnumerable type - it should have satisfied the GetEnumerator pattern.
diagnostics.Add(ErrorCode.ERR_ForEachMissingMember, collectionSyntax.Location, unwrappedCollectionExprType, WellKnownMemberNames.GetEnumeratorMethodName);
return EnumeratorResult.FailedAndReported;
}
if (isAsync && IsIAsyncEnumerable(unwrappedCollectionExprType))
{
collectionExpr = unwrappedCollectionExpr;
// This indicates a problem with the well-known IAsyncEnumerable type - it should have satisfied the GetAsyncEnumerator pattern.
diagnostics.Add(ErrorCode.ERR_AwaitForEachMissingMember, collectionSyntax.Location, unwrappedCollectionExprType, WellKnownMemberNames.GetAsyncEnumeratorMethodName);
return EnumeratorResult.FailedAndReported;
}
if (SatisfiesIEnumerableInterfaces(collectionSyntax, ref builder, unwrappedCollectionExpr, isAsync, diagnostics, unwrappedCollectionExprType) is not EnumeratorResult.FailedNotReported and var result)
{
collectionExpr = unwrappedCollectionExpr;
return result;
}
// COMPAT:
// In some rare cases, like MicroFramework, System.String does not implement foreach pattern.
// For compat reasons we must still treat System.String as valid to use in a foreach
// Similarly to the cases with array and dynamic, we will default to IEnumerable for binding purposes.
// Lowering will not use iterator info with strings, so it is ok.
if (!isAsync && collectionExprType.SpecialType == SpecialType.System_String)
{
if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics))
{