-
Notifications
You must be signed in to change notification settings - Fork 4k
/
UnboundLambda.cs
1280 lines (1116 loc) · 58.1 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.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
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 HadExpressionlessReturn;
internal readonly RefKind RefKind;
internal readonly TypeWithAnnotations TypeWithAnnotations;
internal readonly ImmutableArray<DiagnosticInfo> UseSiteDiagnostics;
internal InferredLambdaReturnType(
int numExpressions,
bool hadExpressionlessReturn,
RefKind refKind,
TypeWithAnnotations typeWithAnnotations,
ImmutableArray<DiagnosticInfo> useSiteDiagnostics)
{
NumExpressions = numExpressions;
HadExpressionlessReturn = hadExpressionlessReturn;
RefKind = refKind;
TypeWithAnnotations = typeWithAnnotations;
UseSiteDiagnostics = useSiteDiagnostics;
}
}
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; private set; }
MethodSymbol IBoundLambdaOrFunction.Symbol { get { return Symbol; } }
SyntaxNode IBoundLambdaOrFunction.Syntax { get { return Syntax; } }
public BoundLambda(SyntaxNode syntax, UnboundLambda unboundLambda, BoundBlock body, ImmutableArray<Diagnostic> 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
);
}
public TypeWithAnnotations GetInferredReturnType(ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// Nullability (and conversions) are ignored.
return GetInferredReturnType(conversions: null, nullableState: null, ref useSiteDiagnostics);
}
/// <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 HashSet<DiagnosticInfo> useSiteDiagnostics)
{
if (!InferredReturnType.UseSiteDiagnostics.IsEmpty)
{
if (useSiteDiagnostics == null)
{
useSiteDiagnostics = new HashSet<DiagnosticInfo>();
}
foreach (var info in InferredReturnType.UseSiteDiagnostics)
{
useSiteDiagnostics.Add(info);
}
}
if (nullableState == null)
{
return InferredReturnType.TypeWithAnnotations;
}
else
{
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();
var inferredReturnType = InferReturnType(returnTypes, node: this, Binder, delegateType, Symbol.IsAsync, conversions);
returnTypes.Free();
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,
diagnostics: null,
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();
/// <summary>
/// Behavior of this function should be kept aligned with <see cref="UnboundLambdaState.ReturnInferenceCacheKey"/>.
/// </summary>
internal static InferredLambdaReturnType InferReturnType(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes,
BoundNode node, Binder binder, TypeSymbol delegateType, bool isAsync, ConversionsBase conversions)
{
var types = ArrayBuilder<(BoundExpression, TypeWithAnnotations)>.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));
}
}
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
var bestType = CalculateReturnType(binder, conversions, delegateType, types, isAsync, node, ref useSiteDiagnostics);
int numExpressions = types.Count;
types.Free();
return new InferredLambdaReturnType(numExpressions, hasReturnWithoutArgument, refKind, bestType, useSiteDiagnostics.AsImmutableOrEmpty());
}
private static TypeWithAnnotations CalculateReturnType(
Binder binder,
ConversionsBase conversions,
TypeSymbol delegateType,
ArrayBuilder<(BoundExpression, TypeWithAnnotations resultType)> returns,
bool isAsync,
BoundNode node,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
TypeWithAnnotations bestResultType;
int n = returns.Count;
switch (n)
{
case 0:
bestResultType = default;
break;
case 1:
bestResultType = returns[0].resultType;
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);
}
else
{
var typesOnly = ArrayBuilder<TypeSymbol>.GetInstance(n);
foreach (var (_, resultType) in returns)
{
typesOnly.Add(resultType.Type);
}
var bestType = BestTypeInferrer.GetBestType(typesOnly, conversions, ref useSiteDiagnostics);
bestResultType = bestType is null ? default : TypeWithAnnotations.Create(bestType);
typesOnly.Free();
}
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 ((object)delegateReturnType != null && !delegateReturnType.IsVoidType())
{
object builderType;
if (delegateReturnType.IsCustomTaskType(out builderType))
{
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 = (object)taskType != null && 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 = (object)taskType != null && 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 BoundLambda.BlockReturns(builder);
visitor.Visit(block);
}
public override BoundNode Visit(BoundNode node)
{
if (!(node is BoundExpression))
{
return base.Visit(node);
}
return null;
}
protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression 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 UnboundLambda(
CSharpSyntaxNode syntax,
Binder binder,
ImmutableArray<RefKind> refKinds,
ImmutableArray<TypeWithAnnotations> types,
ImmutableArray<string> names,
ImmutableArray<bool> discardsOpt,
bool isAsync,
bool isStatic)
: base(BoundKind.UnboundLambda, syntax, null, !types.IsDefault && types.Any(t => t.Type?.Kind == SymbolKind.ErrorType))
{
Debug.Assert(binder != null);
Debug.Assert(syntax.IsAnonymousFunction());
this.Data = new PlainUnboundLambdaState(this, binder, names, discardsOpt, types, refKinds, isAsync, isStatic, includeCache: true);
}
private UnboundLambda(SyntaxNode syntax, UnboundLambdaState state, NullableWalker.VariableState nullableState, bool hasErrors) :
base(BoundKind.UnboundLambda, syntax, null, hasErrors)
{
this._nullableState = nullableState;
this.Data = state;
}
internal UnboundLambda WithNullableState(Binder binder, NullableWalker.VariableState nullableState)
{
var data = Data.WithCaching(true);
var lambda = new UnboundLambda(Syntax, data, 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, _nullableState, HasErrors);
data.SetUnboundLambda(lambda);
return lambda;
}
public MessageID MessageID { get { return Data.MessageID; } }
public BoundLambda Bind(NamedTypeSymbol delegateType)
=> SuppressIfNeeded(Data.Bind(delegateType));
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 HasExplicitlyTypedParameterList { get { return Data.HasExplicitlyTypedParameterList; } }
public int ParameterCount { get { return Data.ParameterCount; } }
public TypeWithAnnotations InferReturnType(ConversionsBase conversions, NamedTypeSymbol delegateType, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
=> BindForReturnTypeInference(delegateType).GetInferredReturnType(conversions, _nullableState, ref useSiteDiagnostics);
public RefKind RefKind(int index) { return Data.RefKind(index); }
public void GenerateAnonymousFunctionConversionError(DiagnosticBag diagnostics, TypeSymbol targetType) { Data.GenerateAnonymousFunctionConversionError(diagnostics, targetType); }
public bool GenerateSummaryErrors(DiagnosticBag diagnostics) { return Data.GenerateSummaryErrors(diagnostics); }
public bool IsAsync { get { return Data.IsAsync; } }
public bool IsStatic => Data.IsStatic;
public TypeWithAnnotations ParameterTypeWithAnnotations(int index) { return Data.ParameterTypeWithAnnotations(index); }
public TypeSymbol ParameterType(int index) { return ParameterTypeWithAnnotations(index).Type; }
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); }
}
internal abstract class UnboundLambdaState
{
private UnboundLambda _unboundLambda; // 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, BoundLambda>) + " which has a large default size, but this cache is normally small.")]
private ImmutableDictionary<NamedTypeSymbol, 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, UnboundLambda unboundLambdaOpt, bool includeCache)
{
Debug.Assert(binder != null);
if (includeCache)
{
_bindingCache = ImmutableDictionary<NamedTypeSymbol, BoundLambda>.Empty.WithComparers(Symbols.SymbolEqualityComparer.ConsiderEverything);
_returnInferenceCache = ImmutableDictionary<ReturnInferenceCacheKey, BoundLambda>.Empty;
}
// might be initialized later (for query lambdas)
_unboundLambda = unboundLambdaOpt;
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 bool HasSignature { get; }
public abstract bool HasExplicitlyTypedParameterList { get; }
public abstract int ParameterCount { get; }
public abstract bool IsAsync { get; }
public abstract bool HasNames { get; }
public abstract bool IsStatic { get; }
public abstract Location ParameterLocation(int index);
public abstract TypeWithAnnotations ParameterTypeWithAnnotations(int index);
public abstract RefKind RefKind(int index);
protected abstract BoundBlock BindLambdaBody(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, DiagnosticBag 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, DiagnosticBag diagnostics);
public virtual void GenerateAnonymousFunctionConversionError(DiagnosticBag 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)
{
BoundLambda result;
if (!_bindingCache.TryGetValue(delegateType, out result))
{
result = ReallyBind(delegateType);
result = ImmutableInterlocked.GetOrAdd(ref _bindingCache, delegateType, 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 TypeWithAnnotations DelegateReturnTypeWithAnnotations(MethodSymbol invokeMethod, out RefKind refKind)
{
if ((object)invokeMethod == null)
{
refKind = CodeAnalysis.RefKind.None;
return default;
}
refKind = invokeMethod.RefKind;
return invokeMethod.ReturnTypeWithAnnotations;
}
private bool DelegateNeedsReturn(MethodSymbol invokeMethod)
{
if ((object)invokeMethod == null || invokeMethod.ReturnsVoid)
{
return false;
}
if (IsAsync && invokeMethod.ReturnType.IsNonGenericTaskType(this.Binder.Compilation))
{
return false;
}
return true;
}
private BoundLambda ReallyBind(NamedTypeSymbol delegateType)
{
var invokeMethod = DelegateInvokeMethod(delegateType);
var returnType = DelegateReturnTypeWithAnnotations(invokeMethod, out RefKind refKind);
LambdaSymbol lambdaSymbol;
Binder lambdaBodyBinder;
BoundBlock block;
var diagnostics = DiagnosticBag.GetInstance();
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.
if (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, diagnostics, cacheKey.ParameterTypes, cacheKey.ParameterRefKinds, refKind);
lambdaBodyBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, ParameterBinder(lambdaSymbol, Binder));
block = BindLambdaBody(lambdaSymbol, lambdaBodyBinder, diagnostics);
}
if (lambdaSymbol.RefKind == CodeAnalysis.RefKind.RefReadOnly)
{
compilation.EnsureIsReadOnlyAttributeExists(diagnostics, lambdaSymbol.DiagnosticLocation, modifyCompilation: false);
}
var lambdaParameters = lambdaSymbol.Parameters;
ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, lambdaParameters, diagnostics, modifyCompilation: false);
if (returnType.HasType)
{
if (returnType.Type.ContainsNativeInteger())
{
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.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);
if (reachableEndpoint)
{
if (DelegateNeedsReturn(invokeMethod))
{
// 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))
{
if (returnType.HasType && // Can be null if "delegateType" is not actually a delegate type.
!returnType.IsVoidType() &&
!returnType.Type.IsNonGenericTaskType(compilation) &&
!returnType.Type.IsGenericTaskType(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);
}
}
if (IsAsync)
{
Debug.Assert(lambdaSymbol.IsAsync);
lambdaSymbol.ReportAsyncParameterErrors(diagnostics, lambdaSymbol.DiagnosticLocation);
}
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,
DiagnosticBag diagnostics,
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
RefKind refKind)
=> new LambdaSymbol(
Binder.Compilation,
containingSymbol,
_unboundLambda,
parameterTypes,
parameterRefKinds,
refKind,
returnType,
diagnostics);
internal LambdaSymbol CreateLambdaSymbol(NamedTypeSymbol delegateType, Symbol containingSymbol)
{
var invokeMethod = DelegateInvokeMethod(delegateType);
var returnType = DelegateReturnTypeWithAnnotations(invokeMethod, out RefKind refKind);
var cacheKey = ReturnInferenceCacheKey.Create(delegateType, IsAsync);
return CreateLambdaSymbol(containingSymbol, returnType, new DiagnosticBag(), cacheKey.ParameterTypes, cacheKey.ParameterRefKinds, refKind);
}
private void ValidateUnsafeParameters(DiagnosticBag 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.IsUnsafe())
{
this.Binder.ReportUnsafeIfNotAllowed(this.ParameterLocation(i), diagnostics);
}
}
}
}
private BoundLambda ReallyInferReturnType(
NamedTypeSymbol delegateType,
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds)
{
(var lambdaSymbol, var block, var lambdaBodyBinder, var diagnostics) = BindWithParameterAndReturnType(parameterTypes, parameterRefKinds, returnType: default);
var returnTypes = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance();
BoundLambda.BlockReturns.GetReturnTypes(returnTypes, block);
var inferredReturnType = BoundLambda.InferReturnType(returnTypes, _unboundLambda, lambdaBodyBinder, delegateType, lambdaSymbol.IsAsync, lambdaBodyBinder.Conversions);
var result = new BoundLambda(
_unboundLambda.Syntax,
_unboundLambda,
block,
diagnostics.ToReadOnlyAndFree(),
lambdaBodyBinder,
delegateType,
inferredReturnType)
{ WasCompilerGenerated = _unboundLambda.WasCompilerGenerated };
// TODO: Should InferredReturnType.UseSiteDiagnostics be merged into BoundLambda.Diagnostics?
var 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);
}
lambdaSymbol.SetInferredReturnType(inferredReturnType.RefKind, returnType);
returnTypes.Free();
return result;
}
private (LambdaSymbol lambdaSymbol, BoundBlock block, ExecutableCodeBinder lambdaBodyBinder, DiagnosticBag diagnostics) BindWithDelegateAndReturnType(
NamedTypeSymbol delegateType,
TypeWithAnnotations returnType)
{
var cacheKey = ReturnInferenceCacheKey.Create(delegateType, IsAsync);
return BindWithParameterAndReturnType(cacheKey.ParameterTypes, cacheKey.ParameterRefKinds, returnType);
}
private (LambdaSymbol lambdaSymbol, BoundBlock block, ExecutableCodeBinder lambdaBodyBinder, DiagnosticBag diagnostics) BindWithParameterAndReturnType(
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
TypeWithAnnotations returnType)
{
var diagnostics = DiagnosticBag.GetInstance();
var lambdaSymbol = CreateLambdaSymbol(Binder.ContainingMemberOrLambda,
returnType,
diagnostics,
parameterTypes,
parameterRefKinds,
CodeAnalysis.RefKind.None);
var lambdaBodyBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, ParameterBinder(lambdaSymbol, Binder));
var block = BindLambdaBody(lambdaSymbol, lambdaBodyBinder, diagnostics);
return (lambdaSymbol, block, lambdaBodyBinder, diagnostics);
}
public BoundLambda BindForReturnTypeInference(NamedTypeSymbol delegateType)
{
var cacheKey = ReturnInferenceCacheKey.Create(delegateType, IsAsync);
BoundLambda result;
if (!_returnInferenceCache.TryGetValue(cacheKey, out result))
{
result = ReallyInferReturnType(delegateType, cacheKey.ParameterTypes, cacheKey.ParameterRefKinds);
result = ImmutableInterlocked.GetOrAdd(ref _returnInferenceCache, cacheKey, result);
}
return result;
}
/// <summary>
/// Behavior of this key should be kept aligned with <see cref="BoundLambda.InferReturnType"/>.
/// </summary>
private sealed class ReturnInferenceCacheKey
{
public readonly ImmutableArray<TypeWithAnnotations> ParameterTypes;
public readonly ImmutableArray<RefKind> ParameterRefKinds;
public readonly NamedTypeSymbol TaskLikeReturnTypeOpt;
public static readonly ReturnInferenceCacheKey Empty = new ReturnInferenceCacheKey(ImmutableArray<TypeWithAnnotations>.Empty, ImmutableArray<RefKind>.Empty, null);
private ReturnInferenceCacheKey(ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, NamedTypeSymbol taskLikeReturnTypeOpt)
{
Debug.Assert(parameterTypes.Length == parameterRefKinds.Length);
Debug.Assert((object)taskLikeReturnTypeOpt == null || ((object)taskLikeReturnTypeOpt == taskLikeReturnTypeOpt.ConstructedFrom && taskLikeReturnTypeOpt.IsCustomTaskType(out var builderArgument)));
this.ParameterTypes = parameterTypes;
this.ParameterRefKinds = parameterRefKinds;
this.TaskLikeReturnTypeOpt = taskLikeReturnTypeOpt;
}
public override bool Equals(object obj)
{
if ((object)this == obj)
{
return true;
}
var other = obj as ReturnInferenceCacheKey;
if ((object)other == null ||
other.ParameterTypes.Length != this.ParameterTypes.Length ||
!TypeSymbol.Equals(other.TaskLikeReturnTypeOpt, this.TaskLikeReturnTypeOpt, TypeCompareKind.ConsiderEverything2))
{
return false;
}
for (int i = 0; i < this.ParameterTypes.Length; i++)
{
if (!other.ParameterTypes[i].Equals(this.ParameterTypes[i], TypeCompareKind.ConsiderEverything) ||
other.ParameterRefKinds[i] != this.ParameterRefKinds[i])
{
return false;
}
}
return true;
}
public override int GetHashCode()
{
var value = TaskLikeReturnTypeOpt?.GetHashCode() ?? 0;
foreach (var type in ParameterTypes)
{
value = Hash.Combine(type.Type, value);
}
return value;
}
public static ReturnInferenceCacheKey Create(NamedTypeSymbol delegateType, bool isAsync)
{
// delegateType or DelegateInvokeMethod can be null in cases of malformed delegates
// in such case we would want something trivial with no parameters
var parameterTypes = ImmutableArray<TypeWithAnnotations>.Empty;
var parameterRefKinds = ImmutableArray<RefKind>.Empty;
NamedTypeSymbol taskLikeReturnTypeOpt = null;
MethodSymbol invoke = DelegateInvokeMethod(delegateType);
if ((object)invoke != null)
{
int parameterCount = invoke.ParameterCount;
if (parameterCount > 0)
{
var typesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(parameterCount);
var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(parameterCount);
foreach (var p in invoke.Parameters)
{
refKindsBuilder.Add(p.RefKind);
typesBuilder.Add(p.TypeWithAnnotations);
}
parameterTypes = typesBuilder.ToImmutableAndFree();
parameterRefKinds = refKindsBuilder.ToImmutableAndFree();
}
if (isAsync)
{
var delegateReturnType = invoke.ReturnType as NamedTypeSymbol;
if ((object)delegateReturnType != null && !delegateReturnType.IsVoidType())
{
if (delegateReturnType.IsCustomTaskType(out var builderType))
{
taskLikeReturnTypeOpt = delegateReturnType.ConstructedFrom;
}
}
}
}
if (parameterTypes.IsEmpty && parameterRefKinds.IsEmpty && (object)taskLikeReturnTypeOpt == null)
{
return Empty;
}
return new ReturnInferenceCacheKey(parameterTypes, parameterRefKinds, taskLikeReturnTypeOpt);
}
}
public virtual Binder ParameterBinder(LambdaSymbol lambdaSymbol, Binder binder)
{
return new WithLambdaParametersBinder(lambdaSymbol, binder);
}
// UNDONE: [MattWar]
// UNDONE: Here we enable the consumer of an unbound lambda that could not be
// UNDONE: successfully converted to a best bound lambda to do error recovery
// UNDONE: by either picking an existing binding, or by binding the body using
// UNDONE: error types for parameter types as necessary. This is not exactly
// UNDONE: the strategy we discussed in the design meeting; rather there we
// UNDONE: decided to do this more the way we did it in the native compiler:
// UNDONE: there we wrote a post-processing pass that searched the tree for
// UNDONE: unbound lambdas and did this sort of replacement on them, so that
// UNDONE: we never observed an unbound lambda in the tree.
// UNDONE:
// UNDONE: I think that is a reasonable approach but it is not implemented yet.
// UNDONE: When we figure out precisely where that rewriting pass should go,
// UNDONE: we can use the gear implemented in this method as an implementation
// UNDONE: detail of it.
// UNDONE:
// UNDONE: Note: that rewriting can now be done in BindToTypeForErrorRecovery.
public BoundLambda BindForErrorRecovery()
{
// It is possible that either (1) we never did a binding, because
// we've got code like "var x = (z)=>{int y = 123; M(y, z);};" or
// (2) we did a bunch of bindings but none of them turned out to
// be the one we wanted. In such a situation we still want
// IntelliSense to work on y in the body of the lambda, and
// possibly to make a good guess as to what M means even if we
// don't know the type of z.
if (_errorBinding == null)
{
Interlocked.CompareExchange(ref _errorBinding, ReallyBindForErrorRecovery(), null);
}
return _errorBinding;
}
private BoundLambda ReallyBindForErrorRecovery()
{
// If we have bindings, we can use heuristics to choose one.
// If not, we can assign error types to all the parameters
// and bind.
return
GuessBestBoundLambda(_bindingCache)
?? rebind(GuessBestBoundLambda(_returnInferenceCache))
?? rebind(ReallyInferReturnType(null, ImmutableArray<TypeWithAnnotations>.Empty, ImmutableArray<RefKind>.Empty));
// Rebind a lambda to push target conversions through the return/result expressions
BoundLambda rebind(BoundLambda lambda)
{
if (lambda is null)
return null;
var delegateType = (NamedTypeSymbol)lambda.Type;
InferredLambdaReturnType inferredReturnType = lambda.InferredReturnType;
var returnType = inferredReturnType.TypeWithAnnotations;
var refKind = lambda.Symbol.RefKind;
if (!returnType.HasType)
{
var invokeMethod = DelegateInvokeMethod(delegateType);
returnType = DelegateReturnTypeWithAnnotations(invokeMethod, out refKind);
if (!returnType.HasType || returnType.Type.ContainsTypeParameter())
{
var t = (inferredReturnType.HadExpressionlessReturn || inferredReturnType.NumExpressions == 0)
? this.Binder.Compilation.GetSpecialType(SpecialType.System_Void)
: this.Binder.CreateErrorType();
returnType = TypeWithAnnotations.Create(t);
refKind = CodeAnalysis.RefKind.None;
}
}
(var lambdaSymbol, var block, var lambdaBodyBinder, var diagnostics) = BindWithDelegateAndReturnType(delegateType, returnType);
return new BoundLambda(
_unboundLambda.Syntax,
_unboundLambda,
block,
diagnostics.ToReadOnlyAndFree(),
lambdaBodyBinder,
delegateType,
new InferredLambdaReturnType(inferredReturnType.NumExpressions, inferredReturnType.HadExpressionlessReturn, refKind, returnType, ImmutableArray<DiagnosticInfo>.Empty))
{ WasCompilerGenerated = _unboundLambda.WasCompilerGenerated };
}
}
private static BoundLambda GuessBestBoundLambda<T>(ImmutableDictionary<T, BoundLambda> candidates)
{
switch (candidates.Count)
{
case 0:
return null;
case 1:
return candidates.First().Value;
default:
// Prefer candidates with fewer diagnostics.
IEnumerable<KeyValuePair<T, BoundLambda>> minDiagnosticsGroup = candidates.GroupBy(lambda => lambda.Value.Diagnostics.Length).OrderBy(group => group.Key).First();
// If multiple candidates have the same number of diagnostics, order them by delegate type name.
// It's not great, but it should be stable.
return minDiagnosticsGroup
.OrderBy(lambda => GetLambdaSortString(lambda.Value.Symbol))
.FirstOrDefault()
.Value;
}
}
private static string GetLambdaSortString(LambdaSymbol lambda)
{
var builder = PooledStringBuilder.GetInstance();
foreach (var parameter in lambda.Parameters)