-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathBinder_Invocation.cs
2407 lines (2137 loc) · 122 KB
/
Binder_Invocation.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.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>.
/// </summary>
internal partial class Binder
{
private BoundExpression BindMethodGroup(ExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics)
{
switch (node.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics);
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics);
case SyntaxKind.ParenthesizedExpression:
return BindMethodGroup(((ParenthesizedExpressionSyntax)node).Expression, invoked: false, indexed: false, diagnostics: diagnostics);
default:
return BindExpression(node, diagnostics, invoked, indexed);
}
}
private static ImmutableArray<MethodSymbol> GetOriginalMethods(OverloadResolutionResult<MethodSymbol> overloadResolutionResult)
{
// If overload resolution has failed then we want to stash away the original methods that we
// considered so that the IDE can display tooltips or other information about them.
// However, if a method group contained a generic method that was type inferred then
// the IDE wants information about the *inferred* method, not the original unconstructed
// generic method.
if (overloadResolutionResult == null)
{
return ImmutableArray<MethodSymbol>.Empty;
}
var builder = ArrayBuilder<MethodSymbol>.GetInstance();
foreach (var result in overloadResolutionResult.Results)
{
builder.Add(result.Member);
}
return builder.ToImmutableAndFree();
}
#nullable enable
/// <summary>
/// Helper method to create a synthesized method invocation expression.
/// </summary>
/// <param name="node">Syntax Node.</param>
/// <param name="receiver">Receiver for the method call.</param>
/// <param name="methodName">Method to be invoked on the receiver.</param>
/// <param name="args">Arguments to the method call.</param>
/// <param name="diagnostics">Diagnostics.</param>
/// <param name="typeArgsSyntax">Optional type arguments syntax.</param>
/// <param name="typeArgs">Optional type arguments.</param>
/// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param>
/// <param name="allowFieldsAndProperties">True to allow invocation of fields and properties of delegate type. Only methods are allowed otherwise.</param>
/// <param name="ignoreNormalFormIfHasValidParamsParameter">True to prevent selecting a params method in unexpanded form.</param>
/// <returns>Synthesized method invocation expression.</returns>
internal BoundExpression MakeInvocationExpression(
SyntaxNode node,
BoundExpression receiver,
string methodName,
ImmutableArray<BoundExpression> args,
BindingDiagnosticBag diagnostics,
SeparatedSyntaxList<TypeSyntax> typeArgsSyntax = default(SeparatedSyntaxList<TypeSyntax>),
ImmutableArray<TypeWithAnnotations> typeArgs = default(ImmutableArray<TypeWithAnnotations>),
ImmutableArray<(string Name, Location Location)?> names = default,
CSharpSyntaxNode? queryClause = null,
bool allowFieldsAndProperties = false,
bool ignoreNormalFormIfHasValidParamsParameter = false,
bool searchExtensionMethodsIfNecessary = true,
bool disallowExpandedNonArrayParams = false)
{
//
// !!! ATTENTION !!!
//
// In terms of errors relevant for HasCollectionExpressionApplicableAddMethod check
// this function should be kept in sync with local function
// HasCollectionExpressionApplicableAddMethod.makeInvocationExpression
//
Debug.Assert(receiver != null);
Debug.Assert(names.IsDefault || names.Length == args.Length);
receiver = BindToNaturalType(receiver, diagnostics);
var boundExpression = BindInstanceMemberAccess(node, node, receiver, methodName, typeArgs.NullToEmpty().Length, typeArgsSyntax, typeArgs, invoked: true, indexed: false, diagnostics, searchExtensionMethodsIfNecessary);
// The other consumers of this helper (await and collection initializers) require the target member to be a method.
if (!allowFieldsAndProperties && (boundExpression.Kind == BoundKind.FieldAccess || boundExpression.Kind == BoundKind.PropertyAccess))
{
ReportMakeInvocationExpressionBadMemberKind(node, methodName, boundExpression, diagnostics);
Symbol symbol;
if (boundExpression.Kind == BoundKind.FieldAccess)
{
symbol = ((BoundFieldAccess)boundExpression).FieldSymbol;
}
else
{
symbol = ((BoundPropertyAccess)boundExpression).PropertySymbol;
}
return BadExpression(node, LookupResultKind.Empty, ImmutableArray.Create(symbol), args.Add(receiver), wasCompilerGenerated: true);
}
Debug.Assert(allowFieldsAndProperties || boundExpression.Kind is (BoundKind.MethodGroup or BoundKind.BadExpression));
boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics);
boundExpression.WasCompilerGenerated = true;
var analyzedArguments = AnalyzedArguments.GetInstance();
Debug.Assert(!args.Any(static e => e.Kind == BoundKind.OutVariablePendingInference ||
e.Kind == BoundKind.OutDeconstructVarPendingInference ||
e.Kind == BoundKind.DiscardExpression && !e.HasExpressionType()));
analyzedArguments.Arguments.AddRange(args);
if (!names.IsDefault)
{
analyzedArguments.Names.AddRange(names);
}
BoundExpression result = BindInvocationExpression(
node, node, methodName, boundExpression, analyzedArguments, diagnostics, queryClause,
ignoreNormalFormIfHasValidParamsParameter: ignoreNormalFormIfHasValidParamsParameter,
disallowExpandedNonArrayParams: disallowExpandedNonArrayParams);
// Query operator can't be called dynamically.
if (queryClause != null && result.Kind == BoundKind.DynamicInvocation)
{
// the error has already been reported by BindInvocationExpression
Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors());
result = CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments);
}
result.WasCompilerGenerated = true;
analyzedArguments.Free();
return result;
}
private static void ReportMakeInvocationExpressionBadMemberKind(SyntaxNode node, string methodName, BoundExpression boundExpression, BindingDiagnosticBag diagnostics)
{
MessageID msgId;
if (boundExpression.Kind == BoundKind.FieldAccess)
{
msgId = MessageID.IDS_SK_FIELD;
}
else
{
msgId = MessageID.IDS_SK_PROPERTY;
}
diagnostics.Add(
ErrorCode.ERR_BadSKknown,
node.Location,
methodName,
msgId.Localize(),
MessageID.IDS_SK_METHOD.Localize());
}
#nullable disable
/// <summary>
/// Bind an expression as a method invocation.
/// </summary>
private BoundExpression BindInvocationExpression(
InvocationExpressionSyntax node,
BindingDiagnosticBag diagnostics)
{
BoundExpression result;
if (TryBindNameofOperator(node, diagnostics, out result))
{
return result; // all of the binding is done by BindNameofOperator
}
// M(__arglist()) is legal, but M(__arglist(__arglist()) is not!
bool isArglist = node.Expression.Kind() == SyntaxKind.ArgListExpression;
AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance();
if (isArglist)
{
BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: false);
result = BindArgListOperator(node, diagnostics, analyzedArguments);
}
else if (receiverIsInvocation(node, out InvocationExpressionSyntax nested))
{
var invocations = ArrayBuilder<InvocationExpressionSyntax>.GetInstance();
invocations.Push(node);
node = nested;
while (receiverIsInvocation(node, out nested))
{
invocations.Push(node);
node = nested;
}
BoundExpression boundExpression = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics: diagnostics);
while (true)
{
result = bindArgumentsAndInvocation(node, boundExpression, analyzedArguments, diagnostics);
nested = node;
if (!invocations.TryPop(out node))
{
break;
}
Debug.Assert(node.Expression.Kind() is SyntaxKind.SimpleMemberAccessExpression);
var memberAccess = (MemberAccessExpressionSyntax)node.Expression;
analyzedArguments.Clear();
CheckContextForPointerTypes(nested, diagnostics, result); // BindExpression does this after calling BindExpressionInternal
boundExpression = BindMemberAccessWithBoundLeft(memberAccess, result, memberAccess.Name, memberAccess.OperatorToken, invoked: true, indexed: false, diagnostics);
}
invocations.Free();
}
else
{
BoundExpression boundExpression = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics: diagnostics);
result = bindArgumentsAndInvocation(node, boundExpression, analyzedArguments, diagnostics);
}
analyzedArguments.Free();
return result;
BoundExpression bindArgumentsAndInvocation(InvocationExpressionSyntax node, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics)
{
boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics);
string name = boundExpression.Kind == BoundKind.MethodGroup ? GetName(node.Expression) : null;
BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true);
return BindInvocationExpression(node, node.Expression, name, boundExpression, analyzedArguments, diagnostics);
}
static bool receiverIsInvocation(InvocationExpressionSyntax node, out InvocationExpressionSyntax nested)
{
if (node.Expression is MemberAccessExpressionSyntax { Expression: InvocationExpressionSyntax receiver, RawKind: (int)SyntaxKind.SimpleMemberAccessExpression } && !receiver.MayBeNameofOperator())
{
nested = receiver;
return true;
}
nested = null;
return false;
}
}
private BoundExpression BindArgListOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, AnalyzedArguments analyzedArguments)
{
bool hasErrors = analyzedArguments.HasErrors;
// We allow names, oddly enough; M(__arglist(x : 123)) is legal. We just ignore them.
TypeSymbol objType = GetSpecialType(SpecialType.System_Object, diagnostics, node);
for (int i = 0; i < analyzedArguments.Arguments.Count; ++i)
{
BoundExpression argument = analyzedArguments.Arguments[i];
if (argument.Kind == BoundKind.OutVariablePendingInference)
{
analyzedArguments.Arguments[i] = ((OutVariablePendingInference)argument).FailInference(this, diagnostics);
}
else if ((object)argument.Type == null && !argument.HasAnyErrors)
{
// We are going to need every argument in here to have a type. If we don't have one,
// try converting it to object. We'll either succeed (if it is a null literal)
// or fail with a good error message.
//
// Note that the native compiler converts null literals to object, and for everything
// else it either crashes, or produces nonsense code. Roslyn improves upon this considerably.
analyzedArguments.Arguments[i] = GenerateConversionForAssignment(objType, argument, diagnostics);
}
else if (argument.Type.IsVoidType())
{
Error(diagnostics, ErrorCode.ERR_CantUseVoidInArglist, argument.Syntax);
hasErrors = true;
}
else if (analyzedArguments.RefKind(i) == RefKind.None)
{
analyzedArguments.Arguments[i] = BindToNaturalType(analyzedArguments.Arguments[i], diagnostics);
}
switch (analyzedArguments.RefKind(i))
{
case RefKind.None:
case RefKind.Ref:
break;
default:
// Disallow "in" or "out" arguments
Error(diagnostics, ErrorCode.ERR_CantUseInOrOutInArglist, argument.Syntax);
hasErrors = true;
break;
}
}
ImmutableArray<BoundExpression> arguments = analyzedArguments.Arguments.ToImmutable();
ImmutableArray<RefKind> refKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
return new BoundArgListOperator(node, arguments, refKinds, null, hasErrors);
}
/// <summary>
/// Bind an expression as a method invocation.
/// </summary>
private BoundExpression BindInvocationExpression(
SyntaxNode node,
SyntaxNode expression,
string methodName,
BoundExpression boundExpression,
AnalyzedArguments analyzedArguments,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause = null,
bool ignoreNormalFormIfHasValidParamsParameter = false,
bool disallowExpandedNonArrayParams = false)
{
//
// !!! ATTENTION !!!
//
// In terms of errors relevant for HasCollectionExpressionApplicableAddMethod check
// this function should be kept in sync with local function
// HasCollectionExpressionApplicableAddMethod.bindInvocationExpression
//
BoundExpression result;
NamedTypeSymbol delegateType;
if ((object)boundExpression.Type != null && boundExpression.Type.IsDynamic())
{
// Either we have a dynamic method group invocation "dyn.M(...)" or
// a dynamic delegate invocation "dyn(...)" -- either way, bind it as a dynamic
// invocation and let the lowering pass sort it out.
ReportSuppressionIfNeeded(boundExpression, diagnostics);
result = BindDynamicInvocation(node, boundExpression, analyzedArguments, ImmutableArray<MethodSymbol>.Empty, diagnostics, queryClause);
}
else if (boundExpression.Kind == BoundKind.MethodGroup)
{
ReportSuppressionIfNeeded(boundExpression, diagnostics);
result = BindMethodGroupInvocation(
node, expression, methodName, (BoundMethodGroup)boundExpression, analyzedArguments,
diagnostics, queryClause,
ignoreNormalFormIfHasValidParamsParameter: ignoreNormalFormIfHasValidParamsParameter,
disallowExpandedNonArrayParams: disallowExpandedNonArrayParams,
anyApplicableCandidates: out _);
}
else if ((object)(delegateType = GetDelegateType(boundExpression)) != null)
{
if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, node: node))
{
return CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments);
}
result = BindDelegateInvocation(node, expression, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, delegateType);
}
else if (boundExpression.Type?.Kind == SymbolKind.FunctionPointerType)
{
ReportSuppressionIfNeeded(boundExpression, diagnostics);
result = BindFunctionPointerInvocation(node, boundExpression, analyzedArguments, diagnostics);
}
else
{
if (!boundExpression.HasAnyErrors)
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_MethodNameExpected), expression.Location);
}
result = CreateBadCall(node, boundExpression, LookupResultKind.NotInvocable, analyzedArguments);
}
CheckRestrictedTypeReceiver(result, this.Compilation, diagnostics);
return result;
}
#nullable enable
private BoundExpression BindDynamicInvocation(
SyntaxNode node,
BoundExpression expression,
AnalyzedArguments arguments,
ImmutableArray<MethodSymbol> applicableMethods,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause)
{
CheckNamedArgumentsForDynamicInvocation(arguments, diagnostics);
bool hasErrors = false;
BoundExpression? receiver;
if (expression.Kind == BoundKind.MethodGroup)
{
BoundMethodGroup methodGroup = (BoundMethodGroup)expression;
receiver = methodGroup.ReceiverOpt;
// receiver is null if we are calling a static method declared on an outer class via its simple name:
if (receiver != null)
{
switch (receiver.Kind)
{
case BoundKind.BaseReference:
Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBase, node, methodGroup.Name);
hasErrors = true;
break;
case BoundKind.ThisReference:
// Can't call the HasThis method due to EE doing odd things with containing member and its containing type.
if ((InConstructorInitializer || InFieldInitializer) && receiver.WasCompilerGenerated)
{
// Only a static method can be called in a constructor initializer. If we were not in a ctor initializer
// the runtime binder would ignore the receiver, but in a ctor initializer we can't read "this" before
// the base constructor is called. We need to handle this as a type qualified static method call.
// Also applicable to things like field initializers, which run before the ctor initializer.
Debug.Assert(ContainingType is not null);
expression = methodGroup.Update(
methodGroup.TypeArgumentsOpt,
methodGroup.Name,
methodGroup.Methods,
methodGroup.LookupSymbolOpt,
methodGroup.LookupError,
methodGroup.Flags & ~BoundMethodGroupFlags.HasImplicitReceiver,
methodGroup.FunctionType,
receiverOpt: new BoundTypeExpression(node, null, this.ContainingType).MakeCompilerGenerated(),
resultKind: methodGroup.ResultKind);
}
break;
case BoundKind.TypeOrValueExpression:
var typeOrValue = (BoundTypeOrValueExpression)receiver;
// Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value".
// Ideally the runtime binder would choose between type and value based on the result of the overload resolution.
// We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed.
bool inStaticContext;
bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext);
BoundExpression finalReceiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics);
expression = methodGroup.Update(
methodGroup.TypeArgumentsOpt,
methodGroup.Name,
methodGroup.Methods,
methodGroup.LookupSymbolOpt,
methodGroup.LookupError,
methodGroup.Flags,
methodGroup.FunctionType,
finalReceiver,
methodGroup.ResultKind);
break;
}
}
}
else
{
expression = BindToNaturalType(expression, diagnostics);
if (expression is BoundDynamicMemberAccess memberAccess)
{
receiver = memberAccess.Receiver;
}
else
{
receiver = expression;
}
}
ImmutableArray<BoundExpression> argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics);
var refKindsArray = arguments.RefKinds.ToImmutableOrNull();
hasErrors &= ReportBadDynamicArguments(node, receiver, argArray, refKindsArray, diagnostics, queryClause);
return new BoundDynamicInvocation(
node,
arguments.GetNames(),
refKindsArray,
applicableMethods,
expression,
argArray,
type: Compilation.DynamicType,
hasErrors: hasErrors);
}
#nullable disable
private void CheckNamedArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics)
{
if (arguments.Names.Count == 0)
{
return;
}
if (!Compilation.LanguageVersion.AllowNonTrailingNamedArguments())
{
return;
}
bool seenName = false;
for (int i = 0; i < arguments.Names.Count; i++)
{
if (arguments.Names[i] != null)
{
seenName = true;
}
else if (seenName)
{
Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, arguments.Arguments[i].Syntax);
return;
}
}
}
private ImmutableArray<BoundExpression> BuildArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics)
{
var builder = ArrayBuilder<BoundExpression>.GetInstance(arguments.Arguments.Count);
builder.AddRange(arguments.Arguments);
for (int i = 0, n = builder.Count; i < n; i++)
{
builder[i] = builder[i] switch
{
OutVariablePendingInference outvar => outvar.FailInference(this, diagnostics),
BoundDiscardExpression discard when !discard.HasExpressionType() => discard.FailInference(this, diagnostics),
var arg => BindToNaturalType(arg, diagnostics)
};
}
return builder.ToImmutableAndFree();
}
// Returns true if there were errors.
#nullable enable
private static bool ReportBadDynamicArguments(
SyntaxNode node,
BoundExpression? receiver,
ImmutableArray<BoundExpression> arguments,
ImmutableArray<RefKind> refKinds,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode? queryClause)
{
bool hasErrors = false;
bool reportedBadQuery = false;
if (receiver != null && !IsLegalDynamicOperand(receiver))
{
// Cannot perform a dynamic invocation on an expression with type '{0}'.
Debug.Assert(receiver.Type is not null);
Error(diagnostics, ErrorCode.ERR_CannotDynamicInvokeOnExpression, receiver.Syntax, receiver.Type);
hasErrors = true;
}
if (!refKinds.IsDefault)
{
for (int argIndex = 0; argIndex < refKinds.Length; argIndex++)
{
if (refKinds[argIndex] == RefKind.In)
{
Error(diagnostics, ErrorCode.ERR_InDynamicMethodArg, arguments[argIndex].Syntax);
hasErrors = true;
}
}
}
foreach (var arg in arguments)
{
if (!IsLegalDynamicOperand(arg))
{
if (queryClause != null && !reportedBadQuery)
{
reportedBadQuery = true;
Error(diagnostics, ErrorCode.ERR_BadDynamicQuery, node);
hasErrors = true;
continue;
}
if (arg.Kind == BoundKind.Lambda || arg.Kind == BoundKind.UnboundLambda)
{
// Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgLambda, arg.Syntax);
hasErrors = true;
}
else if (arg.Kind == BoundKind.MethodGroup)
{
// Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method?
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgMemgrp, arg.Syntax);
hasErrors = true;
}
else if (arg.Kind == BoundKind.ArgListOperator)
{
// Not a great error message, since __arglist is not a type, but it'll do.
// error CS1978: Cannot use an expression of type '__arglist' as an argument to a dynamically dispatched operation
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, "__arglist");
}
else
{
// Lambdas,anonymous methods and method groups are the typeless expressions that
// are not usable as dynamic arguments; if we get here then the expression must have a type.
Debug.Assert((object?)arg.Type != null);
// error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, arg.Type);
hasErrors = true;
}
}
}
return hasErrors;
}
#nullable disable
private BoundExpression BindDelegateInvocation(
SyntaxNode node,
SyntaxNode expression,
string methodName,
BoundExpression boundExpression,
AnalyzedArguments analyzedArguments,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause,
NamedTypeSymbol delegateType)
{
BoundExpression result;
var methodGroup = MethodGroup.GetInstance();
methodGroup.PopulateWithSingleMethod(boundExpression, delegateType.DelegateInvokeMethod);
var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance();
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
OverloadResolution.MethodInvocationOverloadResolution(
methods: methodGroup.Methods,
typeArguments: methodGroup.TypeArguments,
receiver: methodGroup.Receiver,
arguments: analyzedArguments,
result: overloadResolutionResult,
useSiteInfo: ref useSiteInfo,
options: analyzedArguments.HasDynamicArgument ? OverloadResolution.Options.DynamicResolution : OverloadResolution.Options.None);
diagnostics.Add(node, useSiteInfo);
// If overload resolution on the "Invoke" method found an applicable candidate, and one of the arguments
// was dynamic then treat this as a dynamic call.
if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember)
{
var applicable = overloadResolutionResult.Results.Single(r => r.IsApplicable);
ReportMemberNotSupportedByDynamicDispatch(node, applicable, diagnostics);
result = BindDynamicInvocation(node, boundExpression, analyzedArguments, overloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause);
}
else
{
result = BindInvocationExpressionContinued(node, expression, methodName, overloadResolutionResult, analyzedArguments, methodGroup, delegateType, diagnostics, queryClause);
}
overloadResolutionResult.Free();
methodGroup.Free();
return result;
}
private static bool HasApplicableConditionalMethod(ImmutableArray<MemberResolutionResult<MethodSymbol>> finalApplicableCandidates)
{
foreach (var candidate in finalApplicableCandidates)
{
if (candidate.Member.IsConditional)
{
return true;
}
}
return false;
}
private void ReportMemberNotSupportedByDynamicDispatch<TMember>(SyntaxNode syntax, MemberResolutionResult<TMember> candidate, BindingDiagnosticBag diagnostics)
where TMember : Symbol
{
if (candidate.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm &&
!candidate.Member.GetParameters().Last().Type.IsSZArray())
{
Error(diagnostics,
ErrorCode.ERR_DynamicDispatchToParamsCollection,
syntax, candidate.LeastOverriddenMember);
}
}
private BoundExpression BindMethodGroupInvocation(
SyntaxNode syntax,
SyntaxNode expression,
string methodName,
BoundMethodGroup methodGroup,
AnalyzedArguments analyzedArguments,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause,
bool ignoreNormalFormIfHasValidParamsParameter,
out bool anyApplicableCandidates,
bool disallowExpandedNonArrayParams = false)
{
//
// !!! ATTENTION !!!
//
// In terms of errors relevant for HasCollectionExpressionApplicableAddMethod check
// this function should be kept in sync with local function
// HasCollectionExpressionApplicableAddMethod.bindMethodGroupInvocation
//
BoundExpression result = null;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var resolution = this.ResolveMethodGroup(
methodGroup, expression, methodName, analyzedArguments,
useSiteInfo: ref useSiteInfo,
options: (ignoreNormalFormIfHasValidParamsParameter ? OverloadResolution.Options.IgnoreNormalFormIfHasValidParamsParameter : OverloadResolution.Options.None) |
(disallowExpandedNonArrayParams ? OverloadResolution.Options.DisallowExpandedNonArrayParams : OverloadResolution.Options.None) |
(analyzedArguments.HasDynamicArgument ? OverloadResolution.Options.DynamicResolution : OverloadResolution.Options.None));
diagnostics.Add(expression, useSiteInfo);
anyApplicableCandidates = resolution.ResultKind == LookupResultKind.Viable && resolution.OverloadResolutionResult.HasAnyApplicableMember;
if (!methodGroup.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading.
if (resolution.HasAnyErrors)
{
ImmutableArray<MethodSymbol> originalMethods;
LookupResultKind resultKind;
ImmutableArray<TypeWithAnnotations> typeArguments;
if (resolution.OverloadResolutionResult != null)
{
originalMethods = GetOriginalMethods(resolution.OverloadResolutionResult);
resultKind = resolution.MethodGroup.ResultKind;
typeArguments = resolution.MethodGroup.TypeArguments.ToImmutable();
}
else
{
originalMethods = methodGroup.Methods;
resultKind = methodGroup.ResultKind;
typeArguments = methodGroup.TypeArgumentsOpt;
}
result = CreateBadCall(
syntax,
methodName,
methodGroup.ReceiverOpt,
originalMethods,
resultKind,
typeArguments,
analyzedArguments,
invokedAsExtensionMethod: resolution.IsExtensionMethodGroup,
isDelegate: false);
}
else if (!resolution.IsEmpty)
{
// We're checking resolution.ResultKind, rather than methodGroup.HasErrors
// to better handle the case where there's a problem with the receiver
// (e.g. inaccessible), but the method group resolved correctly (e.g. because
// it's actually an accessible static method on a base type).
// CONSIDER: could check for error types amongst method group type arguments.
if (resolution.ResultKind != LookupResultKind.Viable)
{
if (resolution.MethodGroup != null)
{
// we want to force any unbound lambda arguments to cache an appropriate conversion if possible; see 9448.
result = BindInvocationExpressionContinued(
syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments,
resolution.MethodGroup, delegateTypeOpt: null, diagnostics: BindingDiagnosticBag.Discarded, queryClause: queryClause);
}
// Since the resolution is non-empty and has no diagnostics, the LookupResultKind in its MethodGroup is uninteresting.
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
else
{
// If overload resolution found one or more applicable methods and at least one argument
// was dynamic then treat this as a dynamic call.
if (resolution.AnalyzedArguments.HasDynamicArgument &&
resolution.OverloadResolutionResult.HasAnyApplicableMember)
{
// Note that the runtime binder may consider candidates that haven't passed compile-time final validation
// and an ambiguity error may be reported. Also additional checks are performed in runtime final validation
// that are not performed at compile-time.
// Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime.
var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, resolution.OverloadResolutionResult,
methodGroup.ReceiverOpt,
methodGroup.TypeArgumentsOpt,
invokedAsExtensionMethod: resolution.IsExtensionMethodGroup,
diagnostics);
if (finalApplicableCandidates.Length == 0)
{
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
else if (finalApplicableCandidates.Length == 1)
{
Debug.Assert(finalApplicableCandidates[0].IsApplicable);
result = TryEarlyBindSingleCandidateInvocationWithDynamicArgument(syntax, expression, methodName, methodGroup, diagnostics, queryClause, resolution, finalApplicableCandidates[0]);
if (result is null && finalApplicableCandidates[0].LeastOverriddenMember.MethodKind != MethodKind.LocalFunction)
{
ReportMemberNotSupportedByDynamicDispatch(syntax, finalApplicableCandidates[0], diagnostics);
}
}
if (result is null)
{
Debug.Assert(finalApplicableCandidates.Length > 0);
if (resolution.IsExtensionMethodGroup)
{
// error CS1973: 'T' has no applicable method named 'M' but appears to have an
// extension method by that name. Extension methods cannot be dynamically dispatched. Consider
// casting the dynamic arguments or calling the extension method without the extension method
// syntax.
// We found an extension method, so the instance associated with the method group must have
// existed and had a type.
Debug.Assert(methodGroup.InstanceOpt != null && (object)methodGroup.InstanceOpt.Type != null);
Error(diagnostics, ErrorCode.ERR_BadArgTypeDynamicExtension, syntax, methodGroup.InstanceOpt.Type, methodGroup.Name);
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
else
{
ReportDynamicInvocationWarnings(syntax, methodGroup, diagnostics, finalApplicableCandidates);
result = BindDynamicInvocation(syntax, methodGroup, resolution.AnalyzedArguments, finalApplicableCandidates.SelectAsArray(r => r.Member), diagnostics, queryClause);
}
}
}
else
{
result = BindInvocationExpressionContinued(
syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments,
resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause);
}
}
}
else
{
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
resolution.Free();
return result;
}
private void ReportDynamicInvocationWarnings(SyntaxNode syntax, BoundMethodGroup methodGroup, BindingDiagnosticBag diagnostics, ImmutableArray<MemberResolutionResult<MethodSymbol>> finalApplicableCandidates)
{
if (HasApplicableConditionalMethod(finalApplicableCandidates))
{
// warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime
// because one or more applicable overloads are conditional methods
Error(diagnostics, ErrorCode.WRN_DynamicDispatchToConditionalMethod, syntax, methodGroup.Name);
}
}
private bool IsAmbiguousDynamicParamsArgument<TMethodOrPropertySymbol>(ArrayBuilder<BoundExpression> arguments, MemberResolutionResult<TMethodOrPropertySymbol> candidate, out SyntaxNode argumentSyntax)
where TMethodOrPropertySymbol : Symbol
{
if (OverloadResolution.IsValidParams(this, candidate.LeastOverriddenMember, disallowExpandedNonArrayParams: false, out _) &&
candidate.Result.Kind == MemberResolutionKind.ApplicableInNormalForm)
{
var parameters = candidate.Member.GetParameters();
var lastParamIndex = parameters.Length - 1;
for (int i = 0; i < arguments.Count; ++i)
{
var arg = arguments[i];
if (arg.HasDynamicType() &&
candidate.Result.ParameterFromArgument(i) == lastParamIndex)
{
argumentSyntax = arg.Syntax;
return true;
}
}
}
argumentSyntax = null;
return false;
}
private bool CanEarlyBindSingleCandidateInvocationWithDynamicArgument(
SyntaxNode syntax,
BoundMethodGroup boundMethodGroup,
BindingDiagnosticBag diagnostics,
MethodGroupResolution resolution,
MemberResolutionResult<MethodSymbol> methodResolutionResult,
MethodSymbol singleCandidate)
{
if (singleCandidate.MethodKind != MethodKind.LocalFunction)
{
return false;
}
if (boundMethodGroup.TypeArgumentsOpt.IsDefaultOrEmpty && singleCandidate.IsGenericMethod)
{
// If we call an unconstructed generic function with a
// dynamic argument in a place where it influences the type
// parameters, we need to dynamically dispatch the call (as the
// function must be constructed at runtime). We disallow that
// when we know that runtime binder will not be able to handle the case.
// See https://github.com/dotnet/roslyn/issues/21317
// However, doing a specific analysis of each
// argument and its corresponding parameter to check if it's
// generic (and allow dynamic in non-generic parameters) doesn't
// seem to worth the complexity. So, just disallow any mixing of dynamic and
// inferred generics. (Explicit generic arguments are fine)
Error(diagnostics,
ErrorCode.ERR_DynamicLocalFunctionTypeParameter,
syntax, singleCandidate.Name);
return false;
}
if (IsAmbiguousDynamicParamsArgument(resolution.AnalyzedArguments.Arguments, methodResolutionResult, out SyntaxNode argumentSyntax))
{
// We're only in trouble if a dynamic argument is passed to the
// params parameter and is ambiguous at compile time between normal
// and expanded form i.e., there is exactly one dynamic argument to
// a params parameter, and we know that runtime binder might not be
// able to handle the disambiguation
// See https://github.com/dotnet/roslyn/issues/10708
Error(diagnostics,
ErrorCode.ERR_DynamicLocalFunctionParamsParameter,
argumentSyntax, singleCandidate.Parameters.Last().Name, singleCandidate.Name);
return false;
}
return true;
}
private BoundExpression TryEarlyBindSingleCandidateInvocationWithDynamicArgument(
SyntaxNode syntax,
SyntaxNode expression,
string methodName,
BoundMethodGroup boundMethodGroup,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause,
MethodGroupResolution resolution,
MemberResolutionResult<MethodSymbol> methodResolutionResult)
{
MethodSymbol singleCandidate = methodResolutionResult.LeastOverriddenMember;
if (!CanEarlyBindSingleCandidateInvocationWithDynamicArgument(syntax, boundMethodGroup, diagnostics, resolution, methodResolutionResult, singleCandidate))
{
return null;
}
var resultWithSingleCandidate = OverloadResolutionResult<MethodSymbol>.GetInstance();
resultWithSingleCandidate.ResultsBuilder.Add(methodResolutionResult);
BoundExpression result = BindInvocationExpressionContinued(
node: syntax,
expression: expression,
methodName: methodName,
result: resultWithSingleCandidate,
analyzedArguments: resolution.AnalyzedArguments,
methodGroup: resolution.MethodGroup,
delegateTypeOpt: null,
diagnostics: diagnostics,
queryClause: queryClause);
resultWithSingleCandidate.Free();
return result;
}
private ImmutableArray<MemberResolutionResult<TMethodOrPropertySymbol>> GetCandidatesPassingFinalValidation<TMethodOrPropertySymbol>(
SyntaxNode syntax,
OverloadResolutionResult<TMethodOrPropertySymbol> overloadResolutionResult,
BoundExpression receiverOpt,
ImmutableArray<TypeWithAnnotations> typeArgumentsOpt,
bool invokedAsExtensionMethod,
BindingDiagnosticBag diagnostics) where TMethodOrPropertySymbol : Symbol
{
Debug.Assert(overloadResolutionResult.HasAnyApplicableMember);
var finalCandidates = ArrayBuilder<MemberResolutionResult<TMethodOrPropertySymbol>>.GetInstance();
BindingDiagnosticBag firstFailed = null;
var candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics);
for (int i = 0, n = overloadResolutionResult.ResultsBuilder.Count; i < n; i++)
{
var result = overloadResolutionResult.ResultsBuilder[i];
if (result.Result.IsApplicable)
{
// For F to pass the check, all of the following must hold:
// ...
// * If the type parameters of F were substituted in the step above, their constraints are satisfied.
// * If F is a static method, the method group must have resulted from a simple-name, a member-access through a type,
// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1).
// * If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value,
// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1).
if (!MemberGroupFinalValidationAccessibilityChecks(receiverOpt, result.Member, syntax, candidateDiagnostics, invokedAsExtensionMethod: invokedAsExtensionMethod) &&
(typeArgumentsOpt.IsDefault || ((MethodSymbol)(object)result.Member).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, syntax.Location, candidateDiagnostics))))
{
finalCandidates.Add(result);