forked from dotnet/roslyn
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUnboundLambda.cs
1617 lines (1415 loc) · 76 KB
/
UnboundLambda.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal interface IBoundLambdaOrFunction
{
MethodSymbol Symbol { get; }
SyntaxNode Syntax { get; }
BoundBlock? Body { get; }
bool WasCompilerGenerated { get; }
}
internal sealed partial class BoundLocalFunctionStatement : IBoundLambdaOrFunction
{
MethodSymbol IBoundLambdaOrFunction.Symbol { get { return Symbol; } }
SyntaxNode IBoundLambdaOrFunction.Syntax { get { return Syntax; } }
BoundBlock? IBoundLambdaOrFunction.Body { get => this.Body; }
}
internal readonly struct InferredLambdaReturnType
{
internal readonly int NumExpressions;
internal readonly bool IsExplicitType;
internal readonly bool HadExpressionlessReturn;
internal readonly RefKind RefKind;
internal readonly TypeWithAnnotations TypeWithAnnotations;
internal readonly bool InferredFromFunctionType;
internal readonly ImmutableArray<DiagnosticInfo> UseSiteDiagnostics;
internal readonly ImmutableArray<AssemblySymbol> Dependencies;
internal InferredLambdaReturnType(
int numExpressions,
bool isExplicitType,
bool hadExpressionlessReturn,
RefKind refKind,
TypeWithAnnotations typeWithAnnotations,
bool inferredFromFunctionType,
ImmutableArray<DiagnosticInfo> useSiteDiagnostics,
ImmutableArray<AssemblySymbol> dependencies)
{
NumExpressions = numExpressions;
IsExplicitType = isExplicitType;
HadExpressionlessReturn = hadExpressionlessReturn;
RefKind = refKind;
TypeWithAnnotations = typeWithAnnotations;
InferredFromFunctionType = inferredFromFunctionType;
UseSiteDiagnostics = useSiteDiagnostics;
Dependencies = dependencies;
}
}
internal sealed partial class BoundLambda : IBoundLambdaOrFunction
{
public MessageID MessageID { get { return Syntax.Kind() == SyntaxKind.AnonymousMethodExpression ? MessageID.IDS_AnonMethod : MessageID.IDS_Lambda; } }
internal InferredLambdaReturnType InferredReturnType { get; }
internal bool InAnonymousFunctionConversion { get; private set; }
MethodSymbol IBoundLambdaOrFunction.Symbol { get { return Symbol; } }
SyntaxNode IBoundLambdaOrFunction.Syntax { get { return Syntax; } }
public BoundLambda(SyntaxNode syntax, UnboundLambda unboundLambda, BoundBlock body, ReadOnlyBindingDiagnostic<AssemblySymbol> diagnostics, Binder binder, TypeSymbol? delegateType, InferredLambdaReturnType inferredReturnType)
: this(syntax, unboundLambda.WithNoCache(), (LambdaSymbol)binder.ContainingMemberOrLambda!, body, diagnostics, binder, delegateType)
{
InferredReturnType = inferredReturnType;
Debug.Assert(
syntax.IsAnonymousFunction() || // lambda expressions
syntax is ExpressionSyntax && LambdaUtilities.IsLambdaBody(syntax, allowReducedLambdas: true) || // query lambdas
LambdaUtilities.IsQueryPairLambda(syntax) // "pair" lambdas in queries
);
}
internal BoundLambda WithInAnonymousFunctionConversion()
{
if (InAnonymousFunctionConversion)
{
return this;
}
var result = (BoundLambda)MemberwiseClone();
result.InAnonymousFunctionConversion = true;
return result;
}
public TypeWithAnnotations GetInferredReturnType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool inferredFromFunctionType)
{
// Nullability (and conversions) are ignored.
return GetInferredReturnType(conversions: null, nullableState: null, ref useSiteInfo, out inferredFromFunctionType);
}
/// <summary>
/// Infer return type. If `nullableState` is non-null, nullability is also inferred and `NullableWalker.Analyze`
/// uses that state to set the inferred nullability of variables in the enclosing scope. `conversions` is
/// only needed when nullability is inferred.
/// </summary>
public TypeWithAnnotations GetInferredReturnType(ConversionsBase? conversions, NullableWalker.VariableState? nullableState, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool inferredFromFunctionType)
{
if (!InferredReturnType.UseSiteDiagnostics.IsEmpty)
{
useSiteInfo.AddDiagnostics(InferredReturnType.UseSiteDiagnostics);
}
if (!InferredReturnType.Dependencies.IsEmpty)
{
useSiteInfo.AddDependencies(InferredReturnType.Dependencies);
}
InferredLambdaReturnType inferredReturnType;
if (nullableState == null || InferredReturnType.IsExplicitType)
{
inferredReturnType = InferredReturnType;
}
else
{
Debug.Assert(!UnboundLambda.HasExplicitReturnType(out _, out _));
Debug.Assert(conversions != null);
// Diagnostics from NullableWalker.Analyze can be dropped here since Analyze
// will be called again from NullableWalker.ApplyConversion when the
// BoundLambda is converted to an anonymous function.
// https://github.com/dotnet/roslyn/issues/31752: Can we avoid generating extra
// diagnostics? And is this exponential when there are nested lambdas?
var returnTypes = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance();
var diagnostics = DiagnosticBag.GetInstance();
var delegateType = Type.GetDelegateType();
var compilation = Binder.Compilation;
NullableWalker.Analyze(compilation,
lambda: this,
(Conversions)conversions,
diagnostics,
delegateInvokeMethodOpt: delegateType?.DelegateInvokeMethod,
initialState: nullableState,
returnTypes);
diagnostics.Free();
inferredReturnType = InferReturnType(returnTypes, node: this, Binder, delegateType, Symbol.IsAsync, conversions);
returnTypes.Free();
}
inferredFromFunctionType = inferredReturnType.InferredFromFunctionType;
return inferredReturnType.TypeWithAnnotations;
}
internal LambdaSymbol CreateLambdaSymbol(NamedTypeSymbol delegateType, Symbol containingSymbol) =>
UnboundLambda.Data.CreateLambdaSymbol(delegateType, containingSymbol);
internal LambdaSymbol CreateLambdaSymbol(
Symbol containingSymbol,
TypeWithAnnotations returnType,
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
RefKind refKind)
=> UnboundLambda.Data.CreateLambdaSymbol(
containingSymbol,
returnType,
parameterTypes,
parameterRefKinds.IsDefault ? Enumerable.Repeat(RefKind.None, parameterTypes.Length).ToImmutableArray() : parameterRefKinds,
refKind);
/// <summary>
/// Indicates the type of return statement with no expression. Used in InferReturnType.
/// </summary>
internal static readonly TypeSymbol NoReturnExpression = new UnsupportedMetadataTypeSymbol();
internal static InferredLambdaReturnType InferReturnType(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes,
BoundLambda node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions)
{
Debug.Assert(!node.UnboundLambda.HasExplicitReturnType(out _, out _));
return InferReturnTypeImpl(returnTypes, node, binder, delegateType, isAsync, conversions, node.UnboundLambda.WithDependencies);
}
internal static InferredLambdaReturnType InferReturnType(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes,
UnboundLambda node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions)
{
Debug.Assert(!node.HasExplicitReturnType(out _, out _));
return InferReturnTypeImpl(returnTypes, node, binder, delegateType, isAsync, conversions, node.WithDependencies);
}
/// <summary>
/// Behavior of this function should be kept aligned with <see cref="UnboundLambdaState.ReturnInferenceCacheKey"/>.
/// </summary>
private static InferredLambdaReturnType InferReturnTypeImpl(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes,
BoundNode node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions, bool withDependencies)
{
var types = ArrayBuilder<(BoundExpression expr, TypeWithAnnotations resultType, bool isChecked)>.GetInstance();
bool hasReturnWithoutArgument = false;
RefKind refKind = RefKind.None;
foreach (var (returnStatement, type) in returnTypes)
{
RefKind rk = returnStatement.RefKind;
if (rk != RefKind.None)
{
refKind = rk;
}
if ((object)type.Type == NoReturnExpression)
{
hasReturnWithoutArgument = true;
}
else
{
types.Add((returnStatement.ExpressionOpt!, type, returnStatement.Checked));
}
}
var useSiteInfo = withDependencies ? new CompoundUseSiteInfo<AssemblySymbol>(binder.Compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies;
var bestType = CalculateReturnType(binder, conversions, delegateType, types, isAsync, node, ref useSiteInfo, out bool inferredFromFunctionType);
Debug.Assert(bestType.Type is not FunctionTypeSymbol);
int numExpressions = types.Count;
types.Free();
return new InferredLambdaReturnType(
numExpressions,
isExplicitType: false,
hadExpressionlessReturn: hasReturnWithoutArgument,
refKind,
bestType,
inferredFromFunctionType: inferredFromFunctionType,
useSiteInfo.Diagnostics.AsImmutableOrEmpty(),
useSiteInfo.AccumulatesDependencies ? useSiteInfo.Dependencies.AsImmutableOrEmpty() : ImmutableArray<AssemblySymbol>.Empty);
}
private static TypeWithAnnotations CalculateReturnType(
Binder binder,
ConversionsBase conversions,
TypeSymbol? delegateType,
ArrayBuilder<(BoundExpression expr, TypeWithAnnotations resultType, bool isChecked)> returns,
bool isAsync,
BoundNode node,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
out bool inferredFromFunctionType)
{
TypeWithAnnotations bestResultType;
int n = returns.Count;
switch (n)
{
case 0:
inferredFromFunctionType = false;
bestResultType = default;
break;
case 1:
if (conversions.IncludeNullability)
{
inferredFromFunctionType = false;
bestResultType = returns[0].resultType;
}
else
{
var bestType = returns[0].expr.GetTypeOrFunctionType();
if (bestType is FunctionTypeSymbol functionType)
{
bestType = functionType.GetInternalDelegateType();
inferredFromFunctionType = bestType is { };
}
else
{
inferredFromFunctionType = false;
}
bestResultType = TypeWithAnnotations.Create(bestType);
}
break;
default:
// Need to handle ref returns. See https://github.com/dotnet/roslyn/issues/30432
if (conversions.IncludeNullability)
{
bestResultType = NullableWalker.BestTypeForLambdaReturns(returns, binder, node, (Conversions)conversions, out inferredFromFunctionType);
}
else
{
var bestType = BestTypeInferrer.InferBestType(returns.SelectAsArray(pair => pair.expr), conversions, ref useSiteInfo, out inferredFromFunctionType);
bestResultType = TypeWithAnnotations.Create(bestType);
}
break;
}
if (!isAsync)
{
return bestResultType;
}
// For async lambdas, the return type is the return type of the
// delegate Invoke method if Invoke has a Task-like return type.
// Otherwise the return type is Task or Task<T>.
NamedTypeSymbol? taskType = null;
var delegateReturnType = delegateType?.GetDelegateType()?.DelegateInvokeMethod?.ReturnType as NamedTypeSymbol;
if (delegateReturnType?.IsVoidType() == false)
{
if (delegateReturnType.IsCustomTaskType(builderArgument: out _))
{
taskType = delegateReturnType.ConstructedFrom;
}
}
if (n == 0)
{
// No return statements have expressions; use delegate InvokeMethod
// or infer type Task if delegate type not available.
var resultType = taskType?.Arity == 0 ?
taskType :
binder.Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task);
return TypeWithAnnotations.Create(resultType);
}
if (!bestResultType.HasType || bestResultType.IsVoidType())
{
// If the best type was 'void', ERR_CantReturnVoid is reported while binding the "return void"
// statement(s).
return default;
}
// Some non-void best type T was found; use delegate InvokeMethod
// or infer type Task<T> if delegate type not available.
var taskTypeT = taskType?.Arity == 1 ?
taskType :
binder.Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T);
return TypeWithAnnotations.Create(taskTypeT.Construct(ImmutableArray.Create(bestResultType)));
}
internal sealed class BlockReturns : BoundTreeWalker
{
private readonly ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> _builder;
private BlockReturns(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> builder)
{
_builder = builder;
}
public static void GetReturnTypes(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> builder, BoundBlock block)
{
var visitor = new BlockReturns(builder);
visitor.Visit(block);
}
public override BoundNode? Visit(BoundNode node)
{
if (!(node is BoundExpression))
{
return base.Visit(node);
}
return null;
}
protected override BoundNode VisitExpressionOrPatternWithoutStackGuard(BoundNode node)
{
throw ExceptionUtilities.Unreachable();
}
public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
// Do not recurse into local functions; we don't want their returns.
return null;
}
public override BoundNode? VisitReturnStatement(BoundReturnStatement node)
{
var expression = node.ExpressionOpt;
var type = (expression is null) ?
NoReturnExpression :
expression.Type?.SetUnknownNullabilityForReferenceTypes();
_builder.Add((node, TypeWithAnnotations.Create(type)));
return null;
}
}
}
internal partial class UnboundLambda
{
private readonly NullableWalker.VariableState? _nullableState;
public static UnboundLambda Create(
CSharpSyntaxNode syntax,
Binder binder,
bool withDependencies,
RefKind returnRefKind,
TypeWithAnnotations returnType,
ImmutableArray<SyntaxList<AttributeListSyntax>> parameterAttributes,
ImmutableArray<RefKind> refKinds,
ImmutableArray<ScopedKind> declaredScopes,
ImmutableArray<TypeWithAnnotations> types,
ImmutableArray<string> names,
ImmutableArray<bool> discardsOpt,
SeparatedSyntaxList<ParameterSyntax>? syntaxList,
ImmutableArray<EqualsValueClauseSyntax?> defaultValues,
bool isAsync,
bool isStatic)
{
Debug.Assert(binder != null);
Debug.Assert(syntax.IsAnonymousFunction());
bool hasErrors = !types.IsDefault && types.Any(static t => t.Type?.Kind == SymbolKind.ErrorType);
var functionType = FunctionTypeSymbol.CreateIfFeatureEnabled(syntax, binder, static (binder, expr) => ((UnboundLambda)expr).Data.InferDelegateType());
var data = new PlainUnboundLambdaState(binder, returnRefKind, returnType, parameterAttributes, names, discardsOpt, types, refKinds, declaredScopes, defaultValues, syntaxList, isAsync: isAsync, isStatic: isStatic, includeCache: true);
var lambda = new UnboundLambda(syntax, data, functionType, withDependencies, hasErrors: hasErrors);
data.SetUnboundLambda(lambda);
functionType?.SetExpression(lambda.WithNoCache());
return lambda;
}
private UnboundLambda(SyntaxNode syntax, UnboundLambdaState state, FunctionTypeSymbol? functionType, bool withDependencies, NullableWalker.VariableState? nullableState, bool hasErrors) :
this(syntax, state, functionType, withDependencies, hasErrors)
{
this._nullableState = nullableState;
}
internal UnboundLambda WithNullableState(NullableWalker.VariableState nullableState)
{
var data = Data.WithCaching(true);
var lambda = new UnboundLambda(Syntax, data, FunctionType, WithDependencies, nullableState, HasErrors);
data.SetUnboundLambda(lambda);
return lambda;
}
internal UnboundLambda WithNoCache()
{
var data = Data.WithCaching(false);
if ((object)data == Data)
{
return this;
}
var lambda = new UnboundLambda(Syntax, data, FunctionType, WithDependencies, _nullableState, HasErrors);
data.SetUnboundLambda(lambda);
return lambda;
}
public MessageID MessageID { get { return Data.MessageID; } }
public BoundLambda Bind(NamedTypeSymbol delegateType, bool isExpressionTree)
=> SuppressIfNeeded(Data.Bind(delegateType, isExpressionTree));
public BoundLambda BindForErrorRecovery()
=> SuppressIfNeeded(Data.BindForErrorRecovery());
public BoundLambda BindForReturnTypeInference(NamedTypeSymbol delegateType)
=> SuppressIfNeeded(Data.BindForReturnTypeInference(delegateType));
private BoundLambda SuppressIfNeeded(BoundLambda lambda)
=> this.IsSuppressed ? (BoundLambda)lambda.WithSuppression() : lambda;
public bool HasSignature { get { return Data.HasSignature; } }
public bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType)
=> Data.HasExplicitReturnType(out refKind, out returnType);
public Binder GetWithParametersBinder(LambdaSymbol lambdaSymbol, Binder binder)
=> Data.GetWithParametersBinder(lambdaSymbol, binder);
/// <summary>
/// Whether or not the original syntax had explicit parameter list specified where all parameters had an
/// explicit type syntax included. Examples of where this is true are: `() => ...` `(int a) => ...` `(int a,
/// ref int b) => ...` and so on.
///
/// Examples of where this is false is `a => ...` `(a) => ...` `(a, b) => ...` `(ref a) => ...` `(int a, ref b) => ...`.
///
/// Note 1: in the case where some parameters have types and some do not, this will return false. That case is
/// an error case and an error will have already been reported to the user. In this case, we treat the
/// parameter list as if no parameter types were provided.
///
/// Note 2: `(ref a) => ...` is legal. So this property should not be used to determine if a parameter should
/// have its ref/scoped/attributes checked.
/// </summary>
public bool HasExplicitlyTypedParameterList => Data.HasExplicitlyTypedParameterList;
public int ParameterCount { get { return Data.ParameterCount; } }
public TypeWithAnnotations InferReturnType(ConversionsBase conversions, NamedTypeSymbol delegateType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool inferredFromFunctionType)
=> BindForReturnTypeInference(delegateType).GetInferredReturnType(conversions, _nullableState, ref useSiteInfo, out inferredFromFunctionType);
public RefKind RefKind(int index) { return Data.RefKind(index); }
public ScopedKind DeclaredScope(int index) { return Data.DeclaredScope(index); }
public void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, TypeSymbol targetType) { Data.GenerateAnonymousFunctionConversionError(diagnostics, targetType); }
public bool GenerateSummaryErrors(BindingDiagnosticBag diagnostics) { return Data.GenerateSummaryErrors(diagnostics); }
public bool IsAsync { get { return Data.IsAsync; } }
public bool IsStatic => Data.IsStatic;
public SyntaxList<AttributeListSyntax> ParameterAttributes(int index) { return Data.ParameterAttributes(index); }
public TypeWithAnnotations ParameterTypeWithAnnotations(int index) { return Data.ParameterTypeWithAnnotations(index); }
public TypeSymbol ParameterType(int index) { return ParameterTypeWithAnnotations(index).Type; }
/// <summary>
/// Returns the corresponding <see cref="ParameterSyntax"/> at the given index if the lambda was declared with
/// explicit parameter syntax.
/// </summary>
public ParameterSyntax? ParameterSyntax(int index) => Data.ParameterSyntax(index);
public Location ParameterLocation(int index) { return Data.ParameterLocation(index); }
public string ParameterName(int index) { return Data.ParameterName(index); }
public bool ParameterIsDiscard(int index) { return Data.ParameterIsDiscard(index); }
}
/// <summary>
/// Lambda binding state, recorded during testing only.
/// </summary>
internal sealed class LambdaBindingData
{
/// <summary>
/// Number of lambdas bound.
/// </summary>
internal int LambdaBindingCount;
}
internal abstract class UnboundLambdaState
{
private UnboundLambda _unboundLambda = null!; // we would prefer this readonly, but we have an initialization cycle.
internal readonly Binder Binder;
[PerformanceSensitive(
"https://github.com/dotnet/roslyn/issues/23582",
Constraint = "Avoid " + nameof(ConcurrentDictionary<(NamedTypeSymbol, bool), BoundLambda>) + " which has a large default size, but this cache is normally small.")]
private ImmutableDictionary<(NamedTypeSymbol Type, bool IsExpressionLambda), BoundLambda>? _bindingCache;
[PerformanceSensitive(
"https://github.com/dotnet/roslyn/issues/23582",
Constraint = "Avoid " + nameof(ConcurrentDictionary<ReturnInferenceCacheKey, BoundLambda>) + " which has a large default size, but this cache is normally small.")]
private ImmutableDictionary<ReturnInferenceCacheKey, BoundLambda>? _returnInferenceCache;
private BoundLambda? _errorBinding;
public UnboundLambdaState(Binder binder, bool includeCache)
{
Debug.Assert(binder != null);
Debug.Assert(binder.ContainingMemberOrLambda != null);
if (includeCache)
{
_bindingCache = ImmutableDictionary<(NamedTypeSymbol Type, bool IsExpressionLambda), BoundLambda>.Empty.WithComparers(BindingCacheComparer.Instance);
_returnInferenceCache = ImmutableDictionary<ReturnInferenceCacheKey, BoundLambda>.Empty;
}
this.Binder = binder;
}
public void SetUnboundLambda(UnboundLambda unbound)
{
Debug.Assert(unbound != null);
Debug.Assert(_unboundLambda == null || (object)_unboundLambda == unbound);
_unboundLambda = unbound;
}
protected abstract UnboundLambdaState WithCachingCore(bool includeCache);
internal UnboundLambdaState WithCaching(bool includeCache)
{
if ((_bindingCache == null) != includeCache)
{
return this;
}
var state = WithCachingCore(includeCache);
Debug.Assert((state._bindingCache == null) != includeCache);
return state;
}
public UnboundLambda UnboundLambda => _unboundLambda;
public abstract MessageID MessageID { get; }
public abstract string ParameterName(int index);
public abstract bool ParameterIsDiscard(int index);
public abstract SyntaxList<AttributeListSyntax> ParameterAttributes(int index);
public abstract bool HasSignature { get; }
public abstract bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType);
public abstract bool HasExplicitlyTypedParameterList { get; }
public abstract int ParameterCount { get; }
public abstract bool IsAsync { get; }
public abstract bool IsStatic { get; }
public abstract Location ParameterLocation(int index);
public abstract TypeWithAnnotations ParameterTypeWithAnnotations(int index);
public abstract RefKind RefKind(int index);
public abstract ScopedKind DeclaredScope(int index);
public abstract ParameterSyntax? ParameterSyntax(int i);
protected BoundBlock BindLambdaBody(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics)
{
if (lambdaSymbol.DeclaringCompilation?.TestOnlyCompilationData is LambdaBindingData data)
{
Interlocked.Increment(ref data.LambdaBindingCount);
}
Binder.RecordLambdaBinding(UnboundLambda.Syntax);
return BindLambdaBodyCore(lambdaSymbol, lambdaBodyBinder, diagnostics);
}
protected abstract BoundBlock BindLambdaBodyCore(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics);
/// <summary>
/// Return the bound expression if the lambda has an expression body and can be reused easily.
/// This is an optimization only. Implementations can return null to skip reuse.
/// </summary>
protected abstract BoundExpression? GetLambdaExpressionBody(BoundBlock body);
/// <summary>
/// Produce a bound block for the expression returned from GetLambdaExpressionBody.
/// </summary>
protected abstract BoundBlock CreateBlockFromLambdaExpressionBody(Binder lambdaBodyBinder, BoundExpression expression, BindingDiagnosticBag diagnostics);
public virtual void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, TypeSymbol targetType)
{
this.Binder.GenerateAnonymousFunctionConversionError(diagnostics, _unboundLambda.Syntax, _unboundLambda, targetType);
}
// Returns the inferred return type, or null if none can be inferred.
public BoundLambda Bind(NamedTypeSymbol delegateType, bool isTargetExpressionTree)
{
bool inExpressionTree = Binder.InExpressionTree || isTargetExpressionTree;
if (!_bindingCache!.TryGetValue((delegateType, inExpressionTree), out BoundLambda? result))
{
result = ReallyBind(delegateType, inExpressionTree);
result = ImmutableInterlocked.GetOrAdd(ref _bindingCache, (delegateType, inExpressionTree), result);
}
return result;
}
internal IEnumerable<TypeSymbol> InferredReturnTypes()
{
bool any = false;
foreach (var lambda in _returnInferenceCache!.Values)
{
var type = lambda.InferredReturnType.TypeWithAnnotations;
if (type.HasType)
{
any = true;
yield return type.Type;
}
}
if (!any)
{
var type = BindForErrorRecovery().InferredReturnType.TypeWithAnnotations;
if (type.HasType)
{
yield return type.Type;
}
}
}
private static MethodSymbol? DelegateInvokeMethod(NamedTypeSymbol? delegateType)
{
return delegateType.GetDelegateType()?.DelegateInvokeMethod;
}
private static TypeWithAnnotations DelegateReturnTypeWithAnnotations(MethodSymbol? invokeMethod, out RefKind refKind)
{
if (invokeMethod is null)
{
refKind = CodeAnalysis.RefKind.None;
return default;
}
refKind = invokeMethod.RefKind;
return invokeMethod.ReturnTypeWithAnnotations;
}
internal (ImmutableArray<RefKind>, ArrayBuilder<ScopedKind>, ImmutableArray<TypeWithAnnotations>, bool) CollectParameterProperties()
{
var parameterRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(ParameterCount);
var parameterScopesBuilder = ArrayBuilder<ScopedKind>.GetInstance(ParameterCount);
var parameterTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(ParameterCount);
bool getEffectiveScopeFromSymbol = false;
for (int i = 0; i < ParameterCount; i++)
{
var refKind = RefKind(i);
var scope = DeclaredScope(i);
var type = ParameterTypeWithAnnotations(i);
if (scope == ScopedKind.None)
{
if (ParameterHelpers.IsRefScopedByDefault(Binder.UseUpdatedEscapeRules, refKind))
{
scope = ScopedKind.ScopedRef;
if (_unboundLambda.ParameterAttributes(i).Any())
{
getEffectiveScopeFromSymbol = true;
}
}
else if (type.IsRefLikeOrAllowsRefLikeType() && ParameterSyntax(i)?.Modifiers.Any(SyntaxKind.ParamsKeyword) == true)
{
scope = ScopedKind.ScopedValue;
if (_unboundLambda.ParameterAttributes(i).Any())
{
getEffectiveScopeFromSymbol = true;
}
}
}
else if (scope == ScopedKind.ScopedValue && _unboundLambda.ParameterAttributes(i).Any())
{
getEffectiveScopeFromSymbol = true;
}
parameterRefKindsBuilder.Add(refKind);
parameterScopesBuilder.Add(scope);
parameterTypesBuilder.Add(type);
}
var parameterRefKinds = parameterRefKindsBuilder.ToImmutableAndFree();
var parameterTypes = parameterTypesBuilder.ToImmutableAndFree();
return (parameterRefKinds, parameterScopesBuilder, parameterTypes, getEffectiveScopeFromSymbol);
}
internal NamedTypeSymbol? InferDelegateType()
{
Debug.Assert(Binder.ContainingMemberOrLambda is { });
if (!HasExplicitlyTypedParameterList)
{
return null;
}
var (parameterRefKinds, parameterScopesBuilder, parameterTypes, getEffectiveScopeFromSymbol) = CollectParameterProperties();
var lambdaSymbol = CreateLambdaSymbol(
Binder.ContainingMemberOrLambda,
returnType: default,
parameterTypes,
parameterRefKinds,
refKind: default);
if (!HasExplicitReturnType(out var returnRefKind, out var returnType))
{
var lambdaBodyBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, GetWithParametersBinder(lambdaSymbol, Binder));
var block = BindLambdaBody(lambdaSymbol, lambdaBodyBinder, BindingDiagnosticBag.Discarded);
var returnTypes = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance();
BoundLambda.BlockReturns.GetReturnTypes(returnTypes, block);
var inferredReturnType = BoundLambda.InferReturnType(
returnTypes,
_unboundLambda,
lambdaBodyBinder,
delegateType: null,
isAsync: IsAsync,
Binder.Conversions);
returnType = inferredReturnType.TypeWithAnnotations;
returnRefKind = inferredReturnType.RefKind;
if (!returnType.HasType && inferredReturnType.NumExpressions > 0)
{
return null;
}
}
#if !DEBUG
if (getEffectiveScopeFromSymbol)
#endif
{
for (int i = 0; i < ParameterCount; i++)
{
if (((DeclaredScope(i) == ScopedKind.None && parameterScopesBuilder[i] == ScopedKind.ScopedRef) ||
DeclaredScope(i) == ScopedKind.ScopedValue || parameterScopesBuilder[i] == ScopedKind.ScopedValue) &&
_unboundLambda.ParameterAttributes(i).Any())
{
Debug.Assert(getEffectiveScopeFromSymbol);
parameterScopesBuilder[i] = lambdaSymbol.Parameters[i].EffectiveScope;
}
else
{
Debug.Assert(lambdaSymbol.Parameters[i].EffectiveScope == parameterScopesBuilder[i]);
}
}
}
if (!returnType.HasType)
{
// Binder.GetMethodGroupOrLambdaDelegateType() expects a non-null return type.
returnType = TypeWithAnnotations.Create(Binder.Compilation.GetSpecialType(SpecialType.System_Void));
}
return Binder.GetMethodGroupOrLambdaDelegateType(
_unboundLambda.Syntax,
lambdaSymbol,
hasParams: OverloadResolution.IsValidParams(Binder, lambdaSymbol, disallowExpandedNonArrayParams: false, out _),
parameterScopesBuilder.ToImmutableAndFree(),
lambdaSymbol.Parameters.SelectAsArray(p => p.HasUnscopedRefAttribute && p.UseUpdatedEscapeRules),
returnRefKind,
returnType);
}
private BoundLambda ReallyBind(NamedTypeSymbol delegateType, bool inExpressionTree)
{
Debug.Assert(Binder.ContainingMemberOrLambda is { });
var invokeMethod = DelegateInvokeMethod(delegateType);
var returnType = DelegateReturnTypeWithAnnotations(invokeMethod, out RefKind refKind);
LambdaSymbol lambdaSymbol;
Binder lambdaBodyBinder;
BoundBlock block;
var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, _unboundLambda.WithDependencies);
var compilation = Binder.Compilation;
var cacheKey = ReturnInferenceCacheKey.Create(delegateType, IsAsync);
// When binding for real (not for return inference), there is still a good chance
// we could reuse a body of a lambda previous bound for return type inference.
// For simplicity, reuse is limited to expression-bodied lambdas. In those cases,
// we reuse the bound expression and apply any conversion to the return value
// since the inferred return type was not used when binding for return inference.
// We don't reuse the body if we're binding in an expression tree, because we didn't
// know that we were binding for an expression tree when originally binding the lambda
// for return inference.
if (!inExpressionTree &&
refKind == CodeAnalysis.RefKind.None &&
_returnInferenceCache!.TryGetValue(cacheKey, out BoundLambda? returnInferenceLambda) &&
GetLambdaExpressionBody(returnInferenceLambda.Body) is BoundExpression expression &&
(lambdaSymbol = returnInferenceLambda.Symbol).RefKind == refKind &&
(object)LambdaSymbol.InferenceFailureReturnType != lambdaSymbol.ReturnType &&
lambdaSymbol.ReturnTypeWithAnnotations.Equals(returnType, TypeCompareKind.ConsiderEverything))
{
lambdaBodyBinder = returnInferenceLambda.Binder;
block = CreateBlockFromLambdaExpressionBody(lambdaBodyBinder, expression, diagnostics);
diagnostics.AddRange(returnInferenceLambda.Diagnostics);
}
else
{
lambdaSymbol = CreateLambdaSymbol(Binder.ContainingMemberOrLambda, returnType, cacheKey.ParameterTypes, cacheKey.ParameterRefKinds, refKind);
lambdaBodyBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, GetWithParametersBinder(lambdaSymbol, Binder), inExpressionTree ? BinderFlags.InExpressionTree : BinderFlags.None);
block = BindLambdaBody(lambdaSymbol, lambdaBodyBinder, diagnostics);
}
lambdaSymbol.GetDeclarationDiagnostics(diagnostics);
if (lambdaSymbol.RefKind == CodeAnalysis.RefKind.RefReadOnly)
{
compilation.EnsureIsReadOnlyAttributeExists(diagnostics, lambdaSymbol.DiagnosticLocation, modifyCompilation: false);
}
var lambdaParameters = lambdaSymbol.Parameters;
ParameterHelpers.EnsureRefKindAttributesExist(compilation, lambdaParameters, diagnostics, modifyCompilation: false);
// Not emitting ParamCollectionAttribute/ParamArrayAttribute for lambdas
if (returnType.HasType)
{
if (compilation.ShouldEmitNativeIntegerAttributes(returnType.Type))
{
compilation.EnsureNativeIntegerAttributeExists(diagnostics, lambdaSymbol.DiagnosticLocation, modifyCompilation: false);
}
if (compilation.ShouldEmitNullableAttributes(lambdaSymbol) &&
returnType.NeedsNullableAttribute())
{
compilation.EnsureNullableAttributeExists(diagnostics, lambdaSymbol.DiagnosticLocation, modifyCompilation: false);
// Note: we don't need to warn on annotations used in #nullable disable context for lambdas, as this is handled in binding already
}
}
ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, lambdaParameters, diagnostics, modifyCompilation: false);
ParameterHelpers.EnsureScopedRefAttributeExists(compilation, lambdaParameters, diagnostics, modifyCompilation: false);
ParameterHelpers.EnsureNullableAttributeExists(compilation, lambdaSymbol, lambdaParameters, diagnostics, modifyCompilation: false);
// Note: we don't need to warn on annotations used in #nullable disable context for lambdas, as this is handled in binding already
ValidateUnsafeParameters(diagnostics, cacheKey.ParameterTypes);
bool reachableEndpoint = ControlFlowPass.Analyze(compilation, lambdaSymbol, block, diagnostics.DiagnosticBag);
if (reachableEndpoint)
{
if (Binder.MethodOrLambdaRequiresValue(lambdaSymbol, this.Binder.Compilation))
{
// Not all code paths return a value in {0} of type '{1}'
diagnostics.Add(ErrorCode.ERR_AnonymousReturnExpected, lambdaSymbol.DiagnosticLocation, this.MessageID.Localize(), delegateType);
}
else
{
block = FlowAnalysisPass.AppendImplicitReturn(block, lambdaSymbol);
}
}
if (IsAsync && !ErrorFacts.PreventsSuccessfulDelegateConversion(diagnostics.DiagnosticBag))
{
if (returnType.HasType && // Can be null if "delegateType" is not actually a delegate type.
!returnType.IsVoidType() &&
!lambdaSymbol.IsAsyncEffectivelyReturningTask(compilation) &&
!lambdaSymbol.IsAsyncEffectivelyReturningGenericTask(compilation))
{
// Cannot convert async {0} to delegate type '{1}'. An async {0} may return void, Task or Task<T>, none of which are convertible to '{1}'.
diagnostics.Add(ErrorCode.ERR_CantConvAsyncAnonFuncReturns, lambdaSymbol.DiagnosticLocation, lambdaSymbol.MessageID.Localize(), delegateType);
}
}
var result = new BoundLambda(_unboundLambda.Syntax, _unboundLambda, block, diagnostics.ToReadOnlyAndFree(), lambdaBodyBinder, delegateType, inferredReturnType: default)
{ WasCompilerGenerated = _unboundLambda.WasCompilerGenerated };
return result;
}
internal LambdaSymbol CreateLambdaSymbol(
Symbol containingSymbol,
TypeWithAnnotations returnType,
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
RefKind refKind)
=> new LambdaSymbol(
Binder,
Binder.Compilation,
containingSymbol,
_unboundLambda,
parameterTypes,
parameterRefKinds,
refKind,
returnType);
internal LambdaSymbol CreateLambdaSymbol(NamedTypeSymbol delegateType, Symbol containingSymbol)
{
var invokeMethod = DelegateInvokeMethod(delegateType);
var returnType = DelegateReturnTypeWithAnnotations(invokeMethod, out RefKind refKind);
ReturnInferenceCacheKey.GetFields(delegateType, IsAsync, out var parameterTypes, out var parameterRefKinds, out _);
return CreateLambdaSymbol(containingSymbol, returnType, parameterTypes, parameterRefKinds, refKind);
}
private void ValidateUnsafeParameters(BindingDiagnosticBag diagnostics, ImmutableArray<TypeWithAnnotations> targetParameterTypes)
{
// It is legal to use a delegate type that has unsafe parameter types inside
// a safe context if the anonymous method has no parameter list!
//
// unsafe delegate void D(int* p);
// class C { D d = delegate {}; }
//
// is legal even if C is not an unsafe context because no int* is actually used.
if (this.HasSignature)
{
// NOTE: we can get here with targetParameterTypes.Length > ParameterCount
// in a case where we are binding for error reporting purposes
var numParametersToCheck = Math.Min(targetParameterTypes.Length, ParameterCount);
for (int i = 0; i < numParametersToCheck; i++)
{
if (targetParameterTypes[i].Type.ContainsPointerOrFunctionPointer())
{
this.Binder.ReportUnsafeIfNotAllowed(this.ParameterLocation(i), diagnostics);
}
}
}
}
private BoundLambda ReallyInferReturnType(
NamedTypeSymbol? delegateType,
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds)
{
bool hasExplicitReturnType = HasExplicitReturnType(out var refKind, out var returnType);
(var lambdaSymbol, var block, var lambdaBodyBinder, var diagnostics) = BindWithParameterAndReturnType(parameterTypes, parameterRefKinds, returnType, refKind);
InferredLambdaReturnType inferredReturnType;
if (hasExplicitReturnType)
{
// The InferredLambdaReturnType fields other than RefKind and ReturnType
// are only used when actually inferring a type, not when the type is explicit.
inferredReturnType = new InferredLambdaReturnType(
numExpressions: 0,
isExplicitType: true,
hadExpressionlessReturn: false,
refKind,
returnType,
inferredFromFunctionType: false,
ImmutableArray<DiagnosticInfo>.Empty,
ImmutableArray<AssemblySymbol>.Empty);
}
else
{
var returnTypes = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance();
BoundLambda.BlockReturns.GetReturnTypes(returnTypes, block);
inferredReturnType = BoundLambda.InferReturnType(returnTypes, _unboundLambda, lambdaBodyBinder, delegateType, lambdaSymbol.IsAsync, lambdaBodyBinder.Conversions);
// TODO: Should InferredReturnType.UseSiteDiagnostics be merged into BoundLambda.Diagnostics?
refKind = inferredReturnType.RefKind;
returnType = inferredReturnType.TypeWithAnnotations;
if (!returnType.HasType)
{
bool forErrorRecovery = delegateType is null;
returnType = (forErrorRecovery && returnTypes.Count == 0)
? TypeWithAnnotations.Create(this.Binder.Compilation.GetSpecialType(SpecialType.System_Void))
: TypeWithAnnotations.Create(LambdaSymbol.InferenceFailureReturnType);
}
returnTypes.Free();
}
var result = new BoundLambda(
_unboundLambda.Syntax,
_unboundLambda,
block,
diagnostics.ToReadOnlyAndFree(),
lambdaBodyBinder,
delegateType,
inferredReturnType)
{ WasCompilerGenerated = _unboundLambda.WasCompilerGenerated };