-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Binder_Operators.cs
4040 lines (3536 loc) · 203 KB
/
Binder_Operators.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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, DiagnosticBag diagnostics)
{
node.Left.CheckDeconstructionCompatibleArgument(diagnostics);
BoundExpression left = BindValue(node.Left, diagnostics, GetBinaryAssignmentKind(node.Kind()));
ReportSuppressionIfNeeded(left, diagnostics);
BoundExpression right = BindValue(node.Right, diagnostics, BindValueKind.RValue);
BinaryOperatorKind kind = SyntaxKindToBinaryOperatorKind(node.Kind());
// If either operand is bad, don't try to do binary operator overload resolution; that will just
// make cascading errors.
if (left.Kind == BoundKind.EventAccess)
{
BinaryOperatorKind kindOperator = kind.Operator();
switch (kindOperator)
{
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
return BindEventAssignment(node, (BoundEventAccess)left, right, kindOperator, diagnostics);
// fall-through for other operators, if RHS is dynamic we produce dynamic operation, otherwise we'll report an error ...
}
}
if (left.HasAnyErrors || right.HasAnyErrors)
{
// NOTE: no overload resolution candidates.
left = BindToTypeForErrorRecovery(left);
right = BindToTypeForErrorRecovery(right);
return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right,
Conversion.NoConversion, Conversion.NoConversion, LookupResultKind.Empty, CreateErrorType(), hasErrors: true);
}
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
if (left.HasDynamicType() || right.HasDynamicType())
{
if (IsLegalDynamicOperand(right) && IsLegalDynamicOperand(left))
{
left = BindToNaturalType(left, diagnostics);
right = BindToNaturalType(right, diagnostics);
var finalDynamicConversion = this.Compilation.Conversions.ClassifyConversionFromExpression(right, left.Type, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
return new BoundCompoundAssignmentOperator(
node,
new BinaryOperatorSignature(
kind.WithType(BinaryOperatorKind.Dynamic).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime),
left.Type,
right.Type,
Compilation.DynamicType),
left,
right,
Conversion.NoConversion,
finalDynamicConversion,
LookupResultKind.Viable,
left.Type,
hasErrors: false);
}
else
{
Error(diagnostics, ErrorCode.ERR_BadBinaryOps, node, node.OperatorToken.Text, left.Display, right.Display);
// error: operator can't be applied on dynamic and a type that is not convertible to dynamic:
left = BindToTypeForErrorRecovery(left);
right = BindToTypeForErrorRecovery(right);
return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right,
Conversion.NoConversion, Conversion.NoConversion, LookupResultKind.Empty, CreateErrorType(), hasErrors: true);
}
}
if (left.Kind == BoundKind.EventAccess && !CheckEventValueKind((BoundEventAccess)left, BindValueKind.Assignable, diagnostics))
{
// If we're in a place where the event can be assigned, then continue so that we give errors
// about the types and operator not lining up. Otherwise, just report that the event can't
// be used here.
// NOTE: no overload resolution candidates.
left = BindToTypeForErrorRecovery(left);
right = BindToTypeForErrorRecovery(right);
return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right,
Conversion.NoConversion, Conversion.NoConversion, LookupResultKind.NotAVariable, CreateErrorType(), hasErrors: true);
}
// A compound operator, say, x |= y, is bound as x = (X)( ((T)x) | ((T)y) ). We must determine
// the binary operator kind, the type conversions from each side to the types expected by
// the operator, and the type conversion from the return type of the operand to the left hand side.
//
// We can get away with binding the right-hand-side of the operand into its converted form early.
// This is convenient because first, it is never rewritten into an access to a temporary before
// the conversion, and second, because that is more convenient for the "d += lambda" case.
// We want to have the converted (bound) lambda in the bound tree, not the unconverted unbound lambda.
LookupResultKind resultKind;
ImmutableArray<MethodSymbol> originalUserDefinedOperators;
BinaryOperatorAnalysisResult best = this.BinaryOperatorOverloadResolution(kind, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators);
if (!best.HasValue)
{
ReportAssignmentOperatorError(node, diagnostics, left, right, resultKind);
left = BindToTypeForErrorRecovery(left);
right = BindToTypeForErrorRecovery(right);
return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right,
Conversion.NoConversion, Conversion.NoConversion, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true);
}
// The rules in the spec for determining additional errors are bit confusing. In particular
// this line is misleading:
//
// "for predefined operators ... x op= y is permitted if both x op y and x = y are permitted"
//
// That's not accurate in many cases. For example, "x += 1" is permitted if x is string or
// any enum type, but x = 1 is not legal for strings or enums.
//
// The correct rules are spelled out in the spec:
//
// Spec §7.17.2:
// An operation of the form x op= y is processed by applying binary operator overload
// resolution (§7.3.4) as if the operation was written x op y.
// Let R be the return type of the selected operator, and T the type of x. Then,
//
// * If an implicit conversion from an expression of type R to the type T exists,
// the operation is evaluated as x = (T)(x op y), except that x is evaluated only once.
// [no cast is inserted, unless the conversion is implicit dynamic]
// * Otherwise, if
// (1) the selected operator is a predefined operator,
// (2) if R is explicitly convertible to T, and
// (3.1) if y is implicitly convertible to T or
// (3.2) the operator is a shift operator... [then cast the result to T]
// * Otherwise ... a binding-time error occurs.
// So let's tease that out. There are two possible errors: the conversion from the
// operator result type to the left hand type could be bad, and the conversion
// from the right hand side to the left hand type could be bad.
//
// We report the first error under the following circumstances:
//
// * The final conversion is bad, or
// * The final conversion is explicit and the selected operator is not predefined
//
// We report the second error under the following circumstances:
//
// * The final conversion is explicit, and
// * The selected operator is predefined, and
// * the selected operator is not a shift, and
// * the right-to-left conversion is not implicit
bool hasError = false;
BinaryOperatorSignature bestSignature = best.Signature;
CheckNativeIntegerFeatureAvailability(bestSignature.Kind, node, diagnostics);
if (CheckOverflowAtRuntime)
{
bestSignature = new BinaryOperatorSignature(
bestSignature.Kind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime),
bestSignature.LeftType,
bestSignature.RightType,
bestSignature.ReturnType,
bestSignature.Method);
}
BoundExpression rightConverted = CreateConversion(right, best.RightConversion, bestSignature.RightType, diagnostics);
var leftType = left.Type;
Conversion finalConversion = Conversions.ClassifyConversionFromExpressionType(bestSignature.ReturnType, leftType, ref useSiteDiagnostics);
bool isPredefinedOperator = !bestSignature.Kind.IsUserDefined();
if (!finalConversion.IsValid || finalConversion.IsExplicit && !isPredefinedOperator)
{
hasError = true;
GenerateImplicitConversionError(diagnostics, this.Compilation, node, finalConversion, bestSignature.ReturnType, leftType);
}
else
{
ReportDiagnosticsIfObsolete(diagnostics, finalConversion, node, hasBaseReceiver: false);
}
if (finalConversion.IsExplicit &&
isPredefinedOperator &&
!kind.IsShift())
{
Conversion rightToLeftConversion = this.Conversions.ClassifyConversionFromExpression(right, leftType, ref useSiteDiagnostics);
if (!rightToLeftConversion.IsImplicit || !rightToLeftConversion.IsValid)
{
hasError = true;
GenerateImplicitConversionError(diagnostics, node, rightToLeftConversion, right, leftType);
}
}
diagnostics.Add(node, useSiteDiagnostics);
if (!hasError && leftType.IsVoidPointer())
{
Error(diagnostics, ErrorCode.ERR_VoidError, node);
hasError = true;
}
// Any events that weren't handled above (by BindEventAssignment) are bad - we just followed this
// code path for the diagnostics. Make sure we don't report success.
Debug.Assert(left.Kind != BoundKind.EventAccess || hasError);
Conversion leftConversion = best.LeftConversion;
ReportDiagnosticsIfObsolete(diagnostics, leftConversion, node, hasBaseReceiver: false);
return new BoundCompoundAssignmentOperator(node, bestSignature, left, rightConverted,
leftConversion, finalConversion, resultKind, originalUserDefinedOperators, leftType, hasError);
}
/// <summary>
/// For "receiver.event += expr", produce "receiver.add_event(expr)".
/// For "receiver.event -= expr", produce "receiver.remove_event(expr)".
/// </summary>
/// <remarks>
/// Performs some validation of the accessor that couldn't be done in CheckEventValueKind, because
/// the specific accessor wasn't known.
/// </remarks>
private BoundExpression BindEventAssignment(AssignmentExpressionSyntax node, BoundEventAccess left, BoundExpression right, BinaryOperatorKind opKind, DiagnosticBag diagnostics)
{
Debug.Assert(opKind == BinaryOperatorKind.Addition || opKind == BinaryOperatorKind.Subtraction);
bool hasErrors = false;
EventSymbol eventSymbol = left.EventSymbol;
BoundExpression receiverOpt = left.ReceiverOpt;
TypeSymbol delegateType = left.Type;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion argumentConversion = this.Conversions.ClassifyConversionFromExpression(right, delegateType, ref useSiteDiagnostics);
if (!argumentConversion.IsImplicit || !argumentConversion.IsValid) // NOTE: dev10 appears to allow user-defined conversions here.
{
hasErrors = true;
if (delegateType.IsDelegateType()) // Otherwise, suppress cascading.
{
GenerateImplicitConversionError(diagnostics, node, argumentConversion, right, delegateType);
}
}
BoundExpression argument = CreateConversion(right, argumentConversion, delegateType, diagnostics);
bool isAddition = opKind == BinaryOperatorKind.Addition;
MethodSymbol method = isAddition ? eventSymbol.AddMethod : eventSymbol.RemoveMethod;
TypeSymbol type;
if ((object)method == null)
{
type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node); //we know the return type would have been void
// There will be a diagnostic on the declaration if it is from source.
if (!eventSymbol.OriginalDefinition.IsFromCompilation(this.Compilation))
{
// CONSIDER: better error code? ERR_EventNeedsBothAccessors?
Error(diagnostics, ErrorCode.ERR_MissingPredefinedMember, node, delegateType, SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAddition));
}
}
else
{
CheckImplicitThisCopyInReadOnlyMember(receiverOpt, method, diagnostics);
if (!this.IsAccessible(method, ref useSiteDiagnostics, this.GetAccessThroughType(receiverOpt)))
{
// CONSIDER: depending on the accessibility (e.g. if it's private), dev10 might just report the whole event bogus.
Error(diagnostics, ErrorCode.ERR_BadAccess, node, method);
hasErrors = true;
}
else if (IsBadBaseAccess(node, receiverOpt, method, diagnostics, eventSymbol))
{
hasErrors = true;
}
else
{
CheckRuntimeSupportForSymbolAccess(node, receiverOpt, method, diagnostics);
}
if (eventSymbol.IsWindowsRuntimeEvent)
{
// Return type is actually void because this call will be later encapsulated in a call
// to WindowsRuntimeMarshal.AddEventHandler or RemoveEventHandler, which has the return
// type of void.
type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node);
}
else
{
type = method.ReturnType;
}
}
diagnostics.Add(node, useSiteDiagnostics);
return new BoundEventAssignmentOperator(
syntax: node,
@event: eventSymbol,
isAddition: isAddition,
isDynamic: right.HasDynamicType(),
receiverOpt: receiverOpt,
argument: argument,
type: type,
hasErrors: hasErrors);
}
private static bool IsLegalDynamicOperand(BoundExpression operand)
{
Debug.Assert(operand != null);
TypeSymbol type = operand.Type;
// Literal null is a legal operand to a dynamic operation. The other typeless expressions --
// method groups, lambdas, anonymous methods -- are not.
// If the operand is of a class, interface, delegate, array, struct, enum, nullable
// or type param types, it's legal to use in a dynamic expression. In short, the type
// must be one that is convertible to object.
if ((object)type == null)
{
return operand.IsLiteralNull();
}
// Pointer types and very special types are not convertible to object.
return !type.IsPointerOrFunctionPointer() && !type.IsRestrictedType() && !type.IsVoidType();
}
private BoundExpression BindDynamicBinaryOperator(
BinaryExpressionSyntax node,
BinaryOperatorKind kind,
BoundExpression left,
BoundExpression right,
DiagnosticBag diagnostics)
{
// This method binds binary * / % + - << >> < > <= >= == != & ! ^ && || operators where one or both
// of the operands are dynamic.
Debug.Assert((object)left.Type != null && left.Type.IsDynamic() || (object)right.Type != null && right.Type.IsDynamic());
bool hasError = false;
bool leftValidOperand = IsLegalDynamicOperand(left);
bool rightValidOperand = IsLegalDynamicOperand(right);
if (!leftValidOperand || !rightValidOperand)
{
// Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'
Error(diagnostics, ErrorCode.ERR_BadBinaryOps, node, node.OperatorToken.Text, left.Display, right.Display);
hasError = true;
}
MethodSymbol userDefinedOperator = null;
if (kind.IsLogical() && leftValidOperand)
{
// We need to make sure left is either implicitly convertible to Boolean or has user defined truth operator.
// left && right is lowered to {op_False|op_Implicit}(left) ? left : And(left, right)
// left || right is lowered to {op_True|!op_Implicit}(left) ? left : Or(left, right)
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
if (!IsValidDynamicCondition(left, isNegative: kind == BinaryOperatorKind.LogicalAnd, useSiteDiagnostics: ref useSiteDiagnostics, userDefinedOperator: out userDefinedOperator))
{
// Dev11 reports ERR_MustHaveOpTF. The error was shared between this case and user-defined binary Boolean operators.
// We report two distinct more specific error messages.
Error(diagnostics, ErrorCode.ERR_InvalidDynamicCondition, node.Left, left.Type, kind == BinaryOperatorKind.LogicalAnd ? "false" : "true");
hasError = true;
}
diagnostics.Add(node, useSiteDiagnostics);
}
return new BoundBinaryOperator(
syntax: node,
operatorKind: (hasError ? kind : kind.WithType(BinaryOperatorKind.Dynamic)).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime),
left: BindToNaturalType(left, diagnostics),
right: BindToNaturalType(right, diagnostics),
constantValueOpt: ConstantValue.NotAvailable,
methodOpt: userDefinedOperator,
resultKind: LookupResultKind.Viable,
type: Compilation.DynamicType,
hasErrors: hasError);
}
protected static bool IsSimpleBinaryOperator(SyntaxKind kind)
{
// We deliberately exclude &&, ||, ??, etc.
switch (kind)
{
case SyntaxKind.AddExpression:
case SyntaxKind.MultiplyExpression:
case SyntaxKind.SubtractExpression:
case SyntaxKind.DivideExpression:
case SyntaxKind.ModuloExpression:
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.LessThanExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.BitwiseAndExpression:
case SyntaxKind.BitwiseOrExpression:
case SyntaxKind.ExclusiveOrExpression:
case SyntaxKind.LeftShiftExpression:
case SyntaxKind.RightShiftExpression:
return true;
}
return false;
}
private BoundExpression BindSimpleBinaryOperator(BinaryExpressionSyntax node, DiagnosticBag diagnostics)
{
// The simple binary operators are left-associative, and expressions of the form
// a + b + c + d .... are relatively common in machine-generated code. The parser can handle
// creating a deep-on-the-left syntax tree no problem, and then we promptly blow the stack during
// semantic analysis. Here we build an explicit stack to handle the left-hand recursion.
Debug.Assert(IsSimpleBinaryOperator(node.Kind()));
var syntaxNodes = ArrayBuilder<BinaryExpressionSyntax>.GetInstance();
ExpressionSyntax current = node;
while (IsSimpleBinaryOperator(current.Kind()))
{
var binOp = (BinaryExpressionSyntax)current;
syntaxNodes.Push(binOp);
current = binOp.Left;
}
BoundExpression result = BindExpression(current, diagnostics);
if (node.IsKind(SyntaxKind.SubtractExpression)
&& current.IsKind(SyntaxKind.ParenthesizedExpression))
{
if (result.Kind == BoundKind.TypeExpression
&& !((ParenthesizedExpressionSyntax)current).Expression.IsKind(SyntaxKind.ParenthesizedExpression))
{
Error(diagnostics, ErrorCode.ERR_PossibleBadNegCast, node);
}
else if (result.Kind == BoundKind.BadExpression)
{
var parenthesizedExpression = (ParenthesizedExpressionSyntax)current;
if (parenthesizedExpression.Expression.IsKind(SyntaxKind.IdentifierName)
&& ((IdentifierNameSyntax)parenthesizedExpression.Expression).Identifier.ValueText == "dynamic")
{
Error(diagnostics, ErrorCode.ERR_PossibleBadNegCast, node);
}
}
}
while (syntaxNodes.Count > 0)
{
BinaryExpressionSyntax syntaxNode = syntaxNodes.Pop();
BindValueKind bindValueKind = GetBinaryAssignmentKind(syntaxNode.Kind());
BoundExpression left = CheckValue(result, bindValueKind, diagnostics);
BoundExpression right = BindValue(syntaxNode.Right, diagnostics, BindValueKind.RValue);
BoundExpression boundOp = BindSimpleBinaryOperator(syntaxNode, diagnostics, left, right);
result = boundOp;
}
syntaxNodes.Free();
return result;
}
private BoundExpression BindSimpleBinaryOperator(BinaryExpressionSyntax node, DiagnosticBag diagnostics,
BoundExpression left, BoundExpression right)
{
BinaryOperatorKind kind = SyntaxKindToBinaryOperatorKind(node.Kind());
// If either operand is bad, don't try to do binary operator overload resolution; that would just
// make cascading errors.
if (left.HasAnyErrors || right.HasAnyErrors)
{
// NOTE: no user-defined conversion candidates
left = BindToTypeForErrorRecovery(left);
right = BindToTypeForErrorRecovery(right);
return new BoundBinaryOperator(node, kind, ConstantValue.NotAvailable, null, LookupResultKind.Empty, left, right, GetBinaryOperatorErrorType(kind, diagnostics, node), true);
}
TypeSymbol leftType = left.Type;
TypeSymbol rightType = right.Type;
if ((object)leftType != null && leftType.IsDynamic() || (object)rightType != null && rightType.IsDynamic())
{
return BindDynamicBinaryOperator(node, kind, left, right, diagnostics);
}
// SPEC OMISSION: The C# 2.0 spec had a line in it that noted that the expressions "null == null"
// SPEC OMISSION: and "null != null" were to be automatically treated as the appropriate constant;
// SPEC OMISSION: overload resolution was to be skipped. That's because a strict reading
// SPEC OMISSION: of the overload resolution spec shows that overload resolution would give an
// SPEC OMISSION: ambiguity error for this case; the expression is ambiguous between the int?,
// SPEC OMISSION: bool? and string versions of equality. This line was accidentally edited
// SPEC OMISSION: out of the C# 3 specification; we should re-insert it.
bool leftNull = left.IsLiteralNull();
bool rightNull = right.IsLiteralNull();
bool isEquality = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual;
if (isEquality && leftNull && rightNull)
{
return new BoundLiteral(node, ConstantValue.Create(kind == BinaryOperatorKind.Equal), GetSpecialType(SpecialType.System_Boolean, diagnostics, node));
}
if (IsTupleBinaryOperation(left, right) &&
(kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual))
{
CheckFeatureAvailability(node, MessageID.IDS_FeatureTupleEquality, diagnostics);
return BindTupleBinaryOperator(node, kind, left, right, diagnostics);
}
// SPEC: For an operation of one of the forms x == null, null == x, x != null, null != x,
// SPEC: where x is an expression of nullable type, if operator overload resolution
// SPEC: fails to find an applicable operator, the result is instead computed from
// SPEC: the HasValue property of x.
// Note that the spec says "fails to find an applicable operator", not "fails to
// find a unique best applicable operator." For example:
// struct X {
// public static bool operator ==(X? x, double? y) {...}
// public static bool operator ==(X? x, decimal? y) {...}
//
// The comparison "x == null" should produce an ambiguity error rather
// that being bound as !x.HasValue.
//
LookupResultKind resultKind;
ImmutableArray<MethodSymbol> originalUserDefinedOperators;
BinaryOperatorSignature signature;
BinaryOperatorAnalysisResult best;
bool foundOperator = BindSimpleBinaryOperatorParts(node, diagnostics, left, right, kind,
out resultKind, out originalUserDefinedOperators, out signature, out best);
BinaryOperatorKind resultOperatorKind = signature.Kind;
bool hasErrors = false;
if (!foundOperator)
{
ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, resultKind);
resultOperatorKind &= ~BinaryOperatorKind.TypeMask;
hasErrors = true;
}
switch (node.Kind())
{
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
case SyntaxKind.LessThanExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
break;
default:
if (leftType.IsVoidPointer() || rightType.IsVoidPointer())
{
// CONSIDER: dev10 cascades this, but roslyn doesn't have to.
Error(diagnostics, ErrorCode.ERR_VoidError, node);
hasErrors = true;
}
break;
}
CheckNativeIntegerFeatureAvailability(resultOperatorKind, node, diagnostics);
TypeSymbol resultType = signature.ReturnType;
BoundExpression resultLeft = left;
BoundExpression resultRight = right;
ConstantValue resultConstant = null;
if (foundOperator && (resultOperatorKind.OperandTypes() != BinaryOperatorKind.NullableNull))
{
Debug.Assert((object)signature.LeftType != null);
Debug.Assert((object)signature.RightType != null);
resultLeft = CreateConversion(left, best.LeftConversion, signature.LeftType, diagnostics);
resultRight = CreateConversion(right, best.RightConversion, signature.RightType, diagnostics);
resultConstant = FoldBinaryOperator(node, resultOperatorKind, resultLeft, resultRight, resultType.SpecialType, diagnostics);
}
else
{
// If we found an operator, we'll have given the `default` literal a type.
// Otherwise, we'll have reported the problem in ReportBinaryOperatorError.
resultLeft = BindToNaturalType(resultLeft, diagnostics, reportNoTargetType: false);
resultRight = BindToNaturalType(resultRight, diagnostics, reportNoTargetType: false);
}
hasErrors = hasErrors || resultConstant != null && resultConstant.IsBad;
return new BoundBinaryOperator(
node,
resultOperatorKind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime),
resultLeft,
resultRight,
resultConstant,
signature.Method,
resultKind,
originalUserDefinedOperators,
resultType,
hasErrors);
}
private bool BindSimpleBinaryOperatorParts(BinaryExpressionSyntax node, DiagnosticBag diagnostics, BoundExpression left, BoundExpression right, BinaryOperatorKind kind,
out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators,
out BinaryOperatorSignature resultSignature, out BinaryOperatorAnalysisResult best)
{
bool foundOperator;
best = this.BinaryOperatorOverloadResolution(kind, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators);
// However, as an implementation detail, we never "fail to find an applicable
// operator" during overload resolution if we have x == null, x == default, etc. We always
// find at least the reference conversion object == object; the overload resolution
// code does not reject that. Therefore what we should do is only bind
// "x == null" as a nullable-to-null comparison if overload resolution chooses
// the reference conversion.
if (!best.HasValue)
{
resultSignature = new BinaryOperatorSignature(kind, leftType: null, rightType: null, CreateErrorType());
foundOperator = false;
}
else
{
var signature = best.Signature;
bool isObjectEquality = signature.Kind == BinaryOperatorKind.ObjectEqual || signature.Kind == BinaryOperatorKind.ObjectNotEqual;
bool leftNull = left.IsLiteralNull();
bool rightNull = right.IsLiteralNull();
TypeSymbol leftType = left.Type;
TypeSymbol rightType = right.Type;
bool isNullableEquality = (object)signature.Method == null &&
(signature.Kind.Operator() == BinaryOperatorKind.Equal || signature.Kind.Operator() == BinaryOperatorKind.NotEqual) &&
(leftNull && (object)rightType != null && rightType.IsNullableType() ||
rightNull && (object)leftType != null && leftType.IsNullableType());
if (isNullableEquality)
{
resultSignature = new BinaryOperatorSignature(kind | BinaryOperatorKind.NullableNull, leftType: null, rightType: null,
GetSpecialType(SpecialType.System_Boolean, diagnostics, node));
foundOperator = true;
}
else
{
resultSignature = signature;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
bool leftDefault = left.IsLiteralDefault();
bool rightDefault = right.IsLiteralDefault();
foundOperator = !isObjectEquality || BuiltInOperators.IsValidObjectEquality(Conversions, leftType, leftNull, leftDefault, rightType, rightNull, rightDefault, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
}
}
return foundOperator;
}
private static void ReportUnaryOperatorError(CSharpSyntaxNode node, DiagnosticBag diagnostics, string operatorName, BoundExpression operand, LookupResultKind resultKind)
{
if (operand.IsLiteralDefault())
{
// We'll have reported an error for not being able to target-type `default` so we can avoid a cascading diagnostic
return;
}
ErrorCode errorCode = resultKind == LookupResultKind.Ambiguous ?
ErrorCode.ERR_AmbigUnaryOp : // Operator '{0}' is ambiguous on an operand of type '{1}'
ErrorCode.ERR_BadUnaryOp; // Operator '{0}' cannot be applied to operand of type '{1}'
Error(diagnostics, errorCode, node, operatorName, operand.Display);
}
private void ReportAssignmentOperatorError(AssignmentExpressionSyntax node, DiagnosticBag diagnostics, BoundExpression left, BoundExpression right, LookupResultKind resultKind)
{
if (((SyntaxKind)node.OperatorToken.RawKind == SyntaxKind.PlusEqualsToken || (SyntaxKind)node.OperatorToken.RawKind == SyntaxKind.MinusEqualsToken) &&
(object)left.Type != null && left.Type.TypeKind == TypeKind.Delegate)
{
// Special diagnostic for delegate += and -= about wrong right-hand-side
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
var conversion = this.Conversions.ClassifyConversionFromExpression(right, left.Type, ref useSiteDiagnostics);
Debug.Assert(!conversion.IsImplicit);
GenerateImplicitConversionError(diagnostics, right.Syntax, conversion, right, left.Type);
// discard use-site diagnostics
}
else
{
ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, resultKind);
}
}
private static void ReportBinaryOperatorError(ExpressionSyntax node, DiagnosticBag diagnostics, SyntaxToken operatorToken, BoundExpression left, BoundExpression right, LookupResultKind resultKind)
{
bool isEquality = operatorToken.Kind() == SyntaxKind.EqualsEqualsToken || operatorToken.Kind() == SyntaxKind.ExclamationEqualsToken;
switch (left.Kind, right.Kind)
{
case (BoundKind.DefaultLiteral, _) when !isEquality:
case (_, BoundKind.DefaultLiteral) when !isEquality:
// other than == and !=, binary operators are disallowed on `default` literal
Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorToken.Text, "default");
return;
case (BoundKind.DefaultLiteral, BoundKind.DefaultLiteral):
Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnDefault, node, operatorToken.Text, left.Display, right.Display);
return;
case (BoundKind.DefaultLiteral, _) when right.Type is TypeParameterSymbol:
Debug.Assert(!right.Type.IsReferenceType);
Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnUnconstrainedDefault, node, operatorToken.Text, right.Type);
return;
case (_, BoundKind.DefaultLiteral) when left.Type is TypeParameterSymbol:
Debug.Assert(!left.Type.IsReferenceType);
Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnUnconstrainedDefault, node, operatorToken.Text, left.Type);
return;
case (BoundKind.UnconvertedObjectCreationExpression, _):
Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorToken.Text, left.Display);
return;
case (_, BoundKind.UnconvertedObjectCreationExpression):
Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorToken.Text, right.Display);
return;
}
ErrorCode errorCode = resultKind == LookupResultKind.Ambiguous ?
ErrorCode.ERR_AmbigBinaryOps : // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'
ErrorCode.ERR_BadBinaryOps; // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'
Error(diagnostics, errorCode, node, operatorToken.Text, left.Display, right.Display);
}
private BoundExpression BindConditionalLogicalOperator(BinaryExpressionSyntax node, DiagnosticBag diagnostics)
{
Debug.Assert(node.Kind() == SyntaxKind.LogicalOrExpression || node.Kind() == SyntaxKind.LogicalAndExpression);
// Do not blow the stack due to a deep recursion on the left.
BinaryExpressionSyntax binary = node;
ExpressionSyntax child;
while (true)
{
child = binary.Left;
var childAsBinary = child as BinaryExpressionSyntax;
if (childAsBinary == null ||
(childAsBinary.Kind() != SyntaxKind.LogicalOrExpression && childAsBinary.Kind() != SyntaxKind.LogicalAndExpression))
{
break;
}
binary = childAsBinary;
}
BoundExpression left = BindRValueWithoutTargetType(child, diagnostics);
do
{
binary = (BinaryExpressionSyntax)child.Parent;
BoundExpression right = BindRValueWithoutTargetType(binary.Right, diagnostics);
left = BindConditionalLogicalOperator(binary, left, right, diagnostics);
child = binary;
}
while ((object)child != node);
return left;
}
private BoundExpression BindConditionalLogicalOperator(BinaryExpressionSyntax node, BoundExpression left, BoundExpression right, DiagnosticBag diagnostics)
{
BinaryOperatorKind kind = SyntaxKindToBinaryOperatorKind(node.Kind());
Debug.Assert(kind == BinaryOperatorKind.LogicalAnd || kind == BinaryOperatorKind.LogicalOr);
// Let's take an easy out here. The vast majority of the time the operands will
// both be bool. This is the only situation in which the expression can be a
// constant expression, so do the folding now if we can.
if ((object)left.Type != null && left.Type.SpecialType == SpecialType.System_Boolean &&
(object)right.Type != null && right.Type.SpecialType == SpecialType.System_Boolean)
{
var constantValue = FoldBinaryOperator(node, kind | BinaryOperatorKind.Bool, left, right, SpecialType.System_Boolean, diagnostics);
// NOTE: no candidate user-defined operators.
return new BoundBinaryOperator(node, kind | BinaryOperatorKind.Bool, constantValue, methodOpt: null,
resultKind: LookupResultKind.Viable, left, right, type: left.Type, hasErrors: constantValue != null && constantValue.IsBad);
}
// If either operand is bad, don't try to do binary operator overload resolution; that will just
// make cascading errors.
if (left.HasAnyErrors || right.HasAnyErrors)
{
// NOTE: no candidate user-defined operators.
return new BoundBinaryOperator(node, kind, ConstantValue.NotAvailable, methodOpt: null,
resultKind: LookupResultKind.Empty, left, right, type: GetBinaryOperatorErrorType(kind, diagnostics, node), hasErrors: true);
}
if (left.HasDynamicType() || right.HasDynamicType())
{
left = BindToNaturalType(left, diagnostics);
right = BindToNaturalType(right, diagnostics);
return BindDynamicBinaryOperator(node, kind, left, right, diagnostics);
}
LookupResultKind lookupResult;
ImmutableArray<MethodSymbol> originalUserDefinedOperators;
var best = this.BinaryOperatorOverloadResolution(kind, left, right, node, diagnostics, out lookupResult, out originalUserDefinedOperators);
// SPEC: If overload resolution fails to find a single best operator, or if overload
// SPEC: resolution selects one of the predefined integer logical operators, a binding-
// SPEC: time error occurs.
//
// SPEC OMISSION: We should probably clarify that the enum logical operators count as
// SPEC OMISSION: integer logical operators. Basically the rule here should actually be:
// SPEC OMISSION: if overload resolution selects something other than a user-defined
// SPEC OMISSION: operator or the built in not-lifted operator on bool, an error occurs.
//
if (!best.HasValue)
{
ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, lookupResult);
}
else
{
// There are two non-error possibilities. Either both operands are implicitly convertible to
// bool, or we've got a valid user-defined operator.
BinaryOperatorSignature signature = best.Signature;
bool bothBool = signature.LeftType.SpecialType == SpecialType.System_Boolean &&
signature.RightType.SpecialType == SpecialType.System_Boolean;
MethodSymbol trueOperator = null, falseOperator = null;
if (!bothBool && !signature.Kind.IsUserDefined())
{
ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, lookupResult);
}
else if (bothBool || IsValidUserDefinedConditionalLogicalOperator(node, signature, diagnostics, out trueOperator, out falseOperator))
{
var resultLeft = CreateConversion(left, best.LeftConversion, signature.LeftType, diagnostics);
var resultRight = CreateConversion(right, best.RightConversion, signature.RightType, diagnostics);
var resultKind = kind | signature.Kind.OperandTypes();
if (signature.Kind.IsLifted())
{
resultKind |= BinaryOperatorKind.Lifted;
}
if (resultKind.IsUserDefined())
{
Debug.Assert(trueOperator != null && falseOperator != null);
return new BoundUserDefinedConditionalLogicalOperator(
node,
resultKind,
resultLeft,
resultRight,
signature.Method,
trueOperator,
falseOperator,
lookupResult,
originalUserDefinedOperators,
signature.ReturnType);
}
else
{
Debug.Assert(bothBool);
return new BoundBinaryOperator(
node,
resultKind,
resultLeft,
resultRight,
ConstantValue.NotAvailable,
signature.Method,
lookupResult,
originalUserDefinedOperators,
signature.ReturnType);
}
}
}
// We've already reported the error.
return new BoundBinaryOperator(node, kind, left, right, ConstantValue.NotAvailable, null, lookupResult, originalUserDefinedOperators, CreateErrorType(), true);
}
private bool IsValidDynamicCondition(BoundExpression left, bool isNegative, ref HashSet<DiagnosticInfo> useSiteDiagnostics, out MethodSymbol userDefinedOperator)
{
userDefinedOperator = null;
var type = left.Type;
if ((object)type == null)
{
return false;
}
if (type.IsDynamic())
{
return true;
}
var implicitConversion = Conversions.ClassifyImplicitConversionFromExpression(left, Compilation.GetSpecialType(SpecialType.System_Boolean), ref useSiteDiagnostics);
if (implicitConversion.Exists)
{
return true;
}
if (type.Kind != SymbolKind.NamedType)
{
return false;
}
var namedType = type as NamedTypeSymbol;
return HasApplicableBooleanOperator(namedType, isNegative ? WellKnownMemberNames.FalseOperatorName : WellKnownMemberNames.TrueOperatorName, type, ref useSiteDiagnostics, out userDefinedOperator);
}
private bool IsValidUserDefinedConditionalLogicalOperator(
CSharpSyntaxNode syntax,
BinaryOperatorSignature signature,
DiagnosticBag diagnostics,
out MethodSymbol trueOperator,
out MethodSymbol falseOperator)
{
Debug.Assert(signature.Kind.OperandTypes() == BinaryOperatorKind.UserDefined);
// SPEC: When the operands of && or || are of types that declare an applicable
// SPEC: user-defined operator & or |, both of the following must be true, where
// SPEC: T is the type in which the selected operator is defined:
// SPEC VIOLATION:
//
// The native compiler violates the specification, the native compiler allows:
//
// public static D? operator &(D? d1, D? d2) { ... }
// public static bool operator true(D? d) { ... }
// public static bool operator false(D? d) { ... }
//
// to be used as D? && D? or D? || D?. But if you do this:
//
// public static D operator &(D d1, D d2) { ... }
// public static bool operator true(D? d) { ... }
// public static bool operator false(D? d) { ... }
//
// And use the *lifted* form of the operator, this is disallowed.
//
// public static D? operator &(D? d1, D d2) { ... }
// public static bool operator true(D? d) { ... }
// public static bool operator false(D? d) { ... }
//
// Is not allowed because "the return type must be the same as the type of both operands"
// which is not at all what the spec says.
//
// We ought not to break backwards compatibility with the native compiler. The spec
// is plausibly in error; it is possible that this section of the specification was
// never updated when nullable types and lifted operators were added to the language.
// And it seems like the native compiler's behavior of allowing a nullable
// version but not a lifted version is a bug that should be fixed.
//
// Therefore we will do the following in Roslyn:
//
// * The return and parameter types of the chosen operator, whether lifted or unlifted,
// must be the same.
// * The return and parameter types must be either the enclosing type, or its corresponding
// nullable type.
// * There must be an operator true/operator false that takes the left hand type of the operator.
// Only classes and structs contain user-defined operators, so we know it is a named type symbol.
NamedTypeSymbol t = (NamedTypeSymbol)signature.Method.ContainingType;
// SPEC: The return type and the type of each parameter of the selected operator
// SPEC: must be T.
// As mentioned above, we relax this restriction. The types must all be the same.
bool typesAreSame = TypeSymbol.Equals(signature.LeftType, signature.RightType, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(signature.LeftType, signature.ReturnType, TypeCompareKind.ConsiderEverything2);
bool typeMatchesContainer = TypeSymbol.Equals(signature.ReturnType, t, TypeCompareKind.ConsiderEverything2) ||
signature.ReturnType.IsNullableType() && TypeSymbol.Equals(signature.ReturnType.GetNullableUnderlyingType(), t, TypeCompareKind.ConsiderEverything2);
if (!typesAreSame || !typeMatchesContainer)
{
// CS0217: In order to be applicable as a short circuit operator a user-defined logical
// operator ('{0}') must have the same return type and parameter types
Error(diagnostics, ErrorCode.ERR_BadBoolOp, syntax, signature.Method);
trueOperator = null;
falseOperator = null;
return false;
}