-
-
Notifications
You must be signed in to change notification settings - Fork 267
/
Copy pathopover.d
1604 lines (1477 loc) · 52.9 KB
/
opover.d
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
/**
* Handles operator overloading.
*
* Specification: $(LINK2 https://dlang.org/spec/operatoroverloading.html, Operator Overloading)
*
* Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/opover.d, _opover.d)
* Documentation: https://dlang.org/phobos/dmd_opover.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/opover.d
*/
module dmd.opover;
import core.stdc.stdio;
import dmd.aggregate;
import dmd.aliasthis;
import dmd.arraytypes;
import dmd.astenums;
import dmd.dclass;
import dmd.declaration;
import dmd.dscope;
import dmd.dstruct;
import dmd.dsymbol;
import dmd.dsymbolsem;
import dmd.dtemplate;
import dmd.errors;
import dmd.expression;
import dmd.expressionsem;
import dmd.func;
import dmd.funcsem;
import dmd.globals;
import dmd.hdrgen;
import dmd.id;
import dmd.identifier;
import dmd.location;
import dmd.mtype;
import dmd.optimize;
import dmd.statement;
import dmd.templatesem;
import dmd.tokens;
import dmd.typesem;
import dmd.visitor;
/***********************************
* Determine if operands of binary op can be reversed
* to fit operator overload.
*/
bool isCommutative(EXP op) @safe
{
switch (op)
{
case EXP.add:
case EXP.mul:
case EXP.and:
case EXP.or:
case EXP.xor:
// EqualExp
case EXP.equal:
case EXP.notEqual:
// CmpExp
case EXP.lessThan:
case EXP.lessOrEqual:
case EXP.greaterThan:
case EXP.greaterOrEqual:
return true;
default:
break;
}
return false;
}
/// Returns: whether `op` can be overloaded with `opBinary`
private bool hasOpBinary(EXP op) pure @safe
{
switch (op)
{
case EXP.add: return true;
case EXP.min: return true;
case EXP.mul: return true;
case EXP.div: return true;
case EXP.mod: return true;
case EXP.and: return true;
case EXP.or: return true;
case EXP.xor: return true;
case EXP.leftShift: return true;
case EXP.rightShift: return true;
case EXP.unsignedRightShift: return true;
case EXP.concatenate: return true;
case EXP.pow: return true;
case EXP.in_: return true;
default: return false;
}
}
/**
* Remove the = from op=, e.g. += becomes +
*
* Params:
* op = tag for a binary assign operator
* Returns: the corresponding binary operator, or `op` if it wasn't an assign operator
*/
private EXP stripAssignOp(EXP op)
{
switch (op)
{
case EXP.addAssign: return EXP.add;
case EXP.minAssign: return EXP.min;
case EXP.mulAssign: return EXP.mul;
case EXP.divAssign: return EXP.div;
case EXP.modAssign: return EXP.mod;
case EXP.andAssign: return EXP.and;
case EXP.orAssign: return EXP.or;
case EXP.xorAssign: return EXP.xor;
case EXP.leftShiftAssign: return EXP.leftShift;
case EXP.rightShiftAssign: return EXP.rightShift;
case EXP.unsignedRightShiftAssign: return EXP.unsignedRightShift;
case EXP.concatenateAssign: return EXP.concatenate;
case EXP.powAssign: return EXP.pow;
default: return op;
}
}
/*******************************************
* Helper function to turn operator into template argument list
*/
Objects* opToArg(Scope* sc, EXP op)
{
Expression e = new StringExp(Loc.initial, EXPtoString(stripAssignOp(op)));
e = e.expressionSemantic(sc);
auto tiargs = new Objects();
tiargs.push(e);
return tiargs;
}
// Try alias this on first operand
Expression checkAliasThisForLhs(AggregateDeclaration ad, Scope* sc, BinExp e, Type[2] aliasThisStop)
{
if (!ad || !ad.aliasthis)
return null;
/* Rewrite (e1 op e2) as:
* (e1.aliasthis op e2)
*/
if (isRecursiveAliasThis(aliasThisStop[0], e.e1.type))
return null;
//printf("att %s e1 = %s\n", Token.toChars(e.op), e.e1.type.toChars());
BinExp be = cast(BinExp)e.copy();
// Resolve 'alias this' but in case of assigment don't resolve properties yet
// because 'e1 = e2' could mean 'e1(e2)' or 'e1() = e2'
bool findOnly = e.isAssignExp() !is null;
be.e1 = resolveAliasThis(sc, e.e1, true, findOnly);
if (!be.e1)
return null;
return be.trySemanticAliasThis(sc, aliasThisStop);
}
// Try alias this on second operand
Expression checkAliasThisForRhs(AggregateDeclaration ad, Scope* sc, BinExp e, Type[2] aliasThisStop)
{
if (!ad || !ad.aliasthis)
return null;
/* Rewrite (e1 op e2) as:
* (e1 op e2.aliasthis)
*/
if (isRecursiveAliasThis(aliasThisStop[1], e.e2.type))
return null;
//printf("att %s e2 = %s\n", Token.toChars(e.op), e.e2.type.toChars());
BinExp be = cast(BinExp)e.copy();
be.e2 = resolveAliasThis(sc, e.e2, true);
if (!be.e2)
return null;
return be.trySemanticAliasThis(sc, aliasThisStop);
}
Expression opOverloadUnary(UnaExp e, Scope* sc)
{
if (auto ae = e.e1.isArrayExp())
{
ae.e1 = ae.e1.expressionSemantic(sc);
ae.e1 = resolveProperties(sc, ae.e1);
Expression ae1old = ae.e1;
const(bool) maybeSlice = (ae.arguments.length == 0 || ae.arguments.length == 1 && (*ae.arguments)[0].isIntervalExp());
IntervalExp ie = null;
if (maybeSlice && ae.arguments.length)
{
ie = (*ae.arguments)[0].isIntervalExp();
}
Type att = null; // first cyclic `alias this` type
while (true)
{
if (ae.e1.isErrorExp())
{
return ae.e1;
}
Expression ae1save = ae.e1;
ae.lengthVar = null;
AggregateDeclaration ad = isAggregate(ae.e1.type);
if (!ad)
break;
if (search_function(ad, Id.opIndexUnary))
{
Expression e0;
// Deal with $
Expression ae2 = resolveOpDollar(sc, ae, e0);
if (!ae2) // op(a[i..j]) might be: a.opSliceUnary!(op)(i, j)
goto Lfallback;
if (ae2.isErrorExp())
return ae2;
/* Rewrite op(a[arguments]) as:
* a.opIndexUnary!(op)(arguments)
*/
Expression result = dotTemplateCall(ae.e1, Id.opIndexUnary, opToArg(sc, e.op), (*ae.arguments)[]);
if (maybeSlice) // op(a[]) might be: a.opSliceUnary!(op)()
result = result.trySemantic(sc);
else
result = result.expressionSemantic(sc);
if (result)
return Expression.combine(e0, result);
}
Lfallback:
if (maybeSlice && search_function(ad, Id.opSliceUnary))
{
// Deal with $
Expression e0;
auto ae2 = resolveOpDollar(sc, ae, ie, e0);
if (ae2.isErrorExp())
return ae2;
/* Rewrite op(a[i..j]) as:
* a.opSliceUnary!(op)(i, j)
*/
Expression result = ie ?
dotTemplateCall(ae.e1, Id.opSliceUnary, opToArg(sc, e.op), ie.lwr, ie.upr) :
dotTemplateCall(ae.e1, Id.opSliceUnary, opToArg(sc, e.op));
return Expression.combine(e0, result.expressionSemantic(sc));
}
// Didn't find it. Forward to aliasthis
if (ad.aliasthis && !isRecursiveAliasThis(att, ae.e1.type))
{
/* Rewrite op(a[arguments]) as:
* op(a.aliasthis[arguments])
*/
ae.e1 = resolveAliasThis(sc, ae1save, true);
if (ae.e1)
continue;
}
break;
}
ae.e1 = ae1old; // recovery
ae.lengthVar = null;
}
e.e1 = e.e1.expressionSemantic(sc);
e.e1 = resolveProperties(sc, e.e1);
Type att = null; // first cyclic `alias this` type
while (1)
{
if (e.e1.isErrorExp())
{
return e.e1;
}
AggregateDeclaration ad = isAggregate(e.e1.type);
if (!ad)
break;
/* Rewrite as:
* e1.opUnary!(op)()
*/
if (Dsymbol fd = search_function(ad, Id.opUnary))
return dotTemplateCall(e.e1, Id.opUnary, opToArg(sc, e.op)).expressionSemantic(sc);
// Didn't find it. Forward to aliasthis
if (ad.aliasthis && !isRecursiveAliasThis(att, e.e1.type))
{
/* Rewrite op(e1) as:
* op(e1.aliasthis)
*/
//printf("att una %s e1 = %s\n", EXPtoString(op).ptr, this.e1.type.toChars());
if (auto e1 = resolveAliasThis(sc, e.e1, true))
{
e.e1 = e1;
continue;
}
break;
}
// For ++ and --, rewrites to += and -= are also tried, so don't error yet
if (!e.isPreExp())
{
error(e.loc, "operator `%s` is not defined for `%s`", EXPtoString(e.op).ptr, ad.toChars());
errorSupplemental(ad.loc, "perhaps overload the operator with `auto opUnary(string op : \"%s\")() {}`",
EXPtoString(e.op).ptr);
return ErrorExp.get();
}
break;
}
return null;
}
Expression opOverloadArray(ArrayExp ae, Scope* sc)
{
ae.e1 = ae.e1.expressionSemantic(sc);
ae.e1 = resolveProperties(sc, ae.e1);
Expression ae1old = ae.e1;
const(bool) maybeSlice = (ae.arguments.length == 0 || ae.arguments.length == 1 && (*ae.arguments)[0].isIntervalExp());
IntervalExp ie = null;
if (maybeSlice && ae.arguments.length)
{
ie = (*ae.arguments)[0].isIntervalExp();
}
Type att = null; // first cyclic `alias this` type
while (true)
{
if (ae.e1.isErrorExp())
{
return ae.e1;
}
Expression e0 = null;
Expression ae1save = ae.e1;
ae.lengthVar = null;
Type t1b = ae.e1.type.toBasetype();
AggregateDeclaration ad = isAggregate(t1b);
if (!ad)
{
// If the non-aggregate expression ae.e1 is indexable or sliceable,
// convert it to the corresponding concrete expression.
if (isIndexableNonAggregate(t1b) || ae.e1.isTypeExp())
{
// Convert to SliceExp
if (maybeSlice)
return new SliceExp(ae.loc, ae.e1, ie).expressionSemantic(sc);
// Convert to IndexExp
if (ae.arguments.length == 1)
return new IndexExp(ae.loc, ae.e1, (*ae.arguments)[0]).expressionSemantic(sc);
}
break;
}
if (search_function(ad, Id.opIndex))
{
// Deal with $
auto ae2 = resolveOpDollar(sc, ae, e0);
if (!ae2) // a[i..j] might be: a.opSlice(i, j)
goto Lfallback;
if (ae2.isErrorExp())
return ae2;
/* Rewrite e1[arguments] as:
* e1.opIndex(arguments)
*/
Expressions* a = ae.arguments.copy();
Expression result = new DotIdExp(ae.loc, ae.e1, Id.opIndex);
result = new CallExp(ae.loc, result, a);
if (maybeSlice) // a[] might be: a.opSlice()
result = result.trySemantic(sc);
else
result = result.expressionSemantic(sc);
if (result)
return Expression.combine(e0, result);
}
Lfallback:
if (maybeSlice && ae.e1.isTypeExp())
{
Expression result = new SliceExp(ae.loc, ae.e1, ie);
result = result.expressionSemantic(sc);
return Expression.combine(e0, result);
}
if (maybeSlice && search_function(ad, Id.opSlice))
{
// Deal with $
auto ae2 = resolveOpDollar(sc, ae, ie, e0);
if (ae2.isErrorExp())
{
if (!e0 && !search_function(ad, Id.dollar))
ad.loc.errorSupplemental("perhaps define `opDollar` for `%s`", ad.toChars());
return ae2;
}
/* Rewrite a[i..j] as:
* a.opSlice(i, j)
*/
auto a = new Expressions();
if (ie)
{
a.push(ie.lwr);
a.push(ie.upr);
}
Expression result = new DotIdExp(ae.loc, ae.e1, Id.opSlice);
result = new CallExp(ae.loc, result, a);
result = result.expressionSemantic(sc);
return Expression.combine(e0, result);
}
// Didn't find it. Forward to aliasthis
if (ad.aliasthis && !isRecursiveAliasThis(att, ae.e1.type))
{
//printf("att arr e1 = %s\n", this.e1.type.toChars());
/* Rewrite op(a[arguments]) as:
* op(a.aliasthis[arguments])
*/
ae.e1 = resolveAliasThis(sc, ae1save, true);
if (ae.e1)
continue;
}
break;
}
ae.e1 = ae1old; // recovery
ae.lengthVar = null;
return null;
}
/***********************************************
* This is mostly the same as opOverloadUnary but has
* a different rewrite.
*/
Expression opOverloadCast(CastExp e, Scope* sc, Type att = null)
{
AggregateDeclaration ad = isAggregate(e.e1.type);
if (!ad)
return null;
// Rewrite as: e1.opCast!(T)()
if (Dsymbol fd = search_function(ad, Id.opCast))
{
version (all)
{
// Backwards compatibility with D1 if opCast is a function, not a template
if (fd.isFuncDeclaration())
{
// Rewrite as: e1.opCast()
return build_overload(e.loc, sc, e.e1, null, fd);
}
}
auto tiargs = new Objects();
tiargs.push(e.to);
return dotTemplateCall(e.e1, Id.opCast, tiargs).expressionSemantic(sc);
}
// Didn't find it. Forward to aliasthis
if (ad.aliasthis && !isRecursiveAliasThis(att, e.e1.type))
{
// Rewrite `e1.opCast()` as `e1.aliasthis.opCast()`
if (auto e1 = resolveAliasThis(sc, e.e1, true))
{
CastExp result = e.copy().isCastExp();
result.e1 = e1;
return result.opOverloadCast(sc, att);
}
}
return null;
}
// When no operator overload functions are found for `e`, recursively try with `alias this`
// Returns: `null` when still no overload found, otherwise resolved lowering
Expression binAliasThis(BinExp e, Scope* sc, Type[2] aliasThisStop)
{
AggregateDeclaration ad1 = isAggregate(e.e1.type);
AggregateDeclaration ad2 = isAggregate(e.e2.type);
Expression rewrittenLhs;
if (!(e.isAssignExp && ad2 && ad1 == ad2)) // https://issues.dlang.org/show_bug.cgi?id=2943
{
if (Expression result = checkAliasThisForLhs(ad1, sc, e, aliasThisStop))
{
/* https://issues.dlang.org/show_bug.cgi?id=19441
*
* alias this may not be used for partial assignment.
* If a struct has a single member which is aliased this
* directly or aliased to a ref getter function that returns
* the mentioned member, then alias this may be
* used since the object will be fully initialised.
* If the struct is nested, the context pointer is considered
* one of the members, hence the `ad1.fields.length == 2 && ad1.vthis`
* condition.
*/
auto ae = result.isAssignExp();
if (!ae)
return result; // i.e: Rewrote `e1 = e2` -> `e1(e2)`
auto dve = ae.e1.isDotVarExp();
if (!dve)
return result; // i.e: Rewrote `e1 = e2` -> `e1() = e2`
if (auto ad = dve.var.isMember2())
{
// i.e: Rewrote `e1 = e2` -> `e1.some.var = e2`
// Ensure that `var` is the only field member in `ad`
if (ad.fields.length == 1 || (ad.fields.length == 2 && ad.vthis))
{
if (dve.var == ad.aliasthis.sym)
return result;
}
}
rewrittenLhs = ae.e1;
}
}
if (!(e.isAssignExp && ad1 && ad1 == ad2)) // https://issues.dlang.org/show_bug.cgi?id=2943
{
if (Expression result = checkAliasThisForRhs(ad2, sc, e, aliasThisStop))
return result;
}
if (rewrittenLhs)
{
error(e.loc, "cannot use `alias this` to partially initialize variable `%s` of type `%s`. Use `%s`",
e.e1.toChars(), ad1.toChars(), rewrittenLhs.toChars());
return ErrorExp.get();
}
return null;
}
Expression opOverloadAssign(AssignExp e, Scope* sc, Type[2] aliasThisStop)
{
AggregateDeclaration ad1 = isAggregate(e.e1.type);
AggregateDeclaration ad2 = isAggregate(e.e2.type);
if (ad1 == ad2)
{
StructDeclaration sd = ad1.isStructDeclaration();
if (sd &&
(!sd.hasIdentityAssign ||
/* Do a blit if we can and the rvalue is something like .init,
* where a postblit is not necessary.
*/
(sd.hasBlitAssign && !e.e2.isLvalue())))
{
/* This is bitwise struct assignment. */
return null;
}
}
Dsymbol s = search_function(ad1, Id.opAssign);
bool choseReverse;
if (auto result = pickBestBinaryOverload(sc, null, s, null, e, choseReverse))
return result;
return binAliasThis(e, sc, aliasThisStop);
}
Expression opOverloadBinary(BinExp e, Scope* sc, Type[2] aliasThisStop)
{
if (Expression err = binSemanticProp(e, sc))
return err;
AggregateDeclaration ad1 = isAggregate(e.e1.type);
AggregateDeclaration ad2 = isAggregate(e.e2.type);
// Try opBinary and opBinaryRight
Dsymbol s = search_function(ad1, Id.opBinary);
if (s && !s.isTemplateDeclaration())
{
error(e.e1.loc, "`%s.opBinary` isn't a template", e.e1.toChars());
return ErrorExp.get();
}
Dsymbol s_r = search_function(ad2, Id.opBinaryRight);
if (s_r && !s_r.isTemplateDeclaration())
{
error(e.e2.loc, "`%s.opBinaryRight` isn't a template", e.e2.toChars());
return ErrorExp.get();
}
if (s_r && s_r == s) // https://issues.dlang.org/show_bug.cgi?id=12778
s_r = null;
bool choseReverse;
if (auto result = pickBestBinaryOverload(sc, opToArg(sc, e.op), s, s_r, e, choseReverse))
return result;
return binAliasThis(e, sc, aliasThisStop);
}
/**
* If applicable, print an error relating to implementing / fixing `opBinary` functions.
* Params:
* e = binary operation
* sc = scope to try `opBinary!""` semantic in for error messages
* Returns: `true` when an error related to `opBinary` was printed
*/
bool suggestBinaryOverloads(BinExp e, Scope* sc)
{
if (!e.op.hasOpBinary)
return false;
AggregateDeclaration ad1 = isAggregate(e.e1.type);
AggregateDeclaration ad2 = isAggregate(e.e2.type);
if (ad1)
{
if (Dsymbol s = search_function(ad1, Id.opBinary))
{
// This expressionSemantic will fail, otherwise operator overloading would have succeeded before
dotTemplateCall(e.e1, Id.opBinary, opToArg(sc, e.op), e.e2).expressionSemantic(sc);
errorSupplemental(s.loc, "`opBinary` defined here");
return true;
}
error(e.loc, "operator `%s` is not defined for type `%s`", EXPtoString(e.op).ptr, e.e1.type.toChars);
errorSupplemental(ad1.loc, "perhaps overload the operator with `auto opBinary(string op : \"%s\")(%s rhs) {}`", EXPtoString(e.op).ptr, e.e2.type.toChars);
return true;
}
else if (ad2)
{
if (Dsymbol s_r = search_function(ad1, Id.opBinaryRight))
{
dotTemplateCall(e.e2, Id.opBinaryRight, opToArg(sc, e.op), e.e1).expressionSemantic(sc);
errorSupplemental(s_r.loc, "`opBinaryRight` defined here");
return true;
}
error(e.loc, "operator `%s` is not defined for type `%s`", EXPtoString(e.op).ptr, e.e2.type.toChars);
errorSupplemental(ad2.loc, "perhaps overload the operator with `auto opBinaryRight(string op : \"%s\")(%s rhs) {}`", EXPtoString(e.op).ptr, e.e1.type.toChars);
return true;
}
return false;
}
/**
* If applicable, print an error relating to implementing / fixing `opOpAssign` or `opUnary` functions.
* Params:
* exp = binary operation
* sc = scope to try `opOpAssign!""` semantic in for error messages
* parent = if `exp` was lowered from this `PreExp` or `PostExp`, mention `opUnary` as well
* Returns: `true` when an error related to `opOpAssign` was printed
*/
bool suggestOpOpAssign(BinAssignExp exp, Scope* sc, Expression parent)
{
auto ad = isAggregate(exp.e1.type);
if (!ad)
return false;
if (parent && (parent.isPreExp() || parent.isPostExp()))
{
error(exp.loc, "operator `%s` not supported for `%s` of type `%s`", EXPtoString(parent.op).ptr, exp.e1.toChars(), ad.toChars());
errorSupplemental(ad.loc,
"perhaps implement `auto opUnary(string op : \"%s\")() {}`"~
" or `auto opOpAssign(string op : \"%s\")(int) {}`",
EXPtoString(stripAssignOp(parent.op)).ptr,
EXPtoString(stripAssignOp(exp.op)).ptr
);
return true;
}
if (const s = search_function(ad, Id.opOpAssign))
{
// This expressionSemantic will fail, otherwise operator overloading would have succeeded before
dotTemplateCall(exp.e1, Id.opOpAssign, opToArg(sc, exp.op), exp.e2).expressionSemantic(sc);
}
else
{
error(exp.loc, "operator `%s` not supported for `%s` of type `%s`", EXPtoString(exp.op).ptr, exp.e1.toChars(), ad.toChars());
errorSupplemental(ad.loc, "perhaps implement `auto opOpAssign(string op : \"%s\")(%s) {}`",
EXPtoString(stripAssignOp(exp.op)).ptr, exp.e2.type.toChars());
}
return true;
}
// Helper to construct e.id!tiargs(args), e.g. `lhs.opBinary!"+"(rhs)`
private Expression dotTemplateCall(Expression e, Identifier id, Objects* tiargs, Expression[] args...)
{
auto ti = new DotTemplateInstanceExp(e.loc, e, id, tiargs);
auto expressions = new Expressions();
expressions.pushSlice(args);
return new CallExp(e.loc, ti, expressions);
}
Expression opOverloadEqual(EqualExp e, Scope* sc, Type[2] aliasThisStop)
{
Type t1 = e.e1.type.toBasetype();
Type t2 = e.e2.type.toBasetype();
/* Array equality is handled by expressionSemantic() potentially
* lowering to object.__equals(), which takes care of overloaded
* operators for the element types.
*/
if (t1.isStaticOrDynamicArray() && t2.isStaticOrDynamicArray())
{
return null;
}
/* Check for class equality with null literal or typeof(null).
*/
if (t1.isTypeClass() && e.e2.isNullExp() ||
t2.isTypeClass() && e.e1.isNullExp())
{
error(e.loc, "use `%s` instead of `%s` when comparing with `null`",
EXPtoString(e.op == EXP.equal ? EXP.identity : EXP.notIdentity).ptr,
EXPtoString(e.op).ptr);
return ErrorExp.get();
}
if (t1.isTypeClass() && t2.isTypeNull() ||
t1.isTypeNull() && t2.isTypeClass())
{
// Comparing a class with typeof(null) should not call opEquals
return null;
}
/* Check for class equality.
*/
if (t1.isTypeClass() && t2.isTypeClass())
{
ClassDeclaration cd1 = t1.isClassHandle();
ClassDeclaration cd2 = t2.isClassHandle();
if (!(cd1.classKind == ClassKind.cpp || cd2.classKind == ClassKind.cpp))
{
/* Rewrite as:
* .object.opEquals(e1, e2)
*/
if (!ClassDeclaration.object)
{
error(e.loc, "cannot compare classes for equality because `object.Object` was not declared");
return null;
}
Expression e1x = e.e1;
Expression e2x = e.e2;
/* The explicit cast is necessary for interfaces
* https://issues.dlang.org/show_bug.cgi?id=4088
*/
Type to = ClassDeclaration.object.getType();
if (cd1.isInterfaceDeclaration())
e1x = new CastExp(e.loc, e.e1, t1.isMutable() ? to : to.constOf());
if (cd2.isInterfaceDeclaration())
e2x = new CastExp(e.loc, e.e2, t2.isMutable() ? to : to.constOf());
Expression result = new IdentifierExp(e.loc, Id.empty);
result = new DotIdExp(e.loc, result, Id.object);
result = new DotIdExp(e.loc, result, Id.opEquals);
result = new CallExp(e.loc, result, e1x, e2x);
if (e.op == EXP.notEqual)
result = new NotExp(e.loc, result);
result = result.expressionSemantic(sc);
return result;
}
}
EXP cmpOp;
if (Expression result = compare_overload(e, sc, Id.opEquals, cmpOp, aliasThisStop))
{
if (lastComma(result).isCallExp() && e.op == EXP.notEqual)
{
result = new NotExp(result.loc, result);
result = result.expressionSemantic(sc);
}
return result;
}
/* Check for pointer equality.
*/
if (t1.isTypePointer() || t2.isTypePointer())
{
/* Rewrite:
* ptr1 == ptr2
* as:
* ptr1 is ptr2
*
* This is just a rewriting for deterministic AST representation
* as the backend input.
*/
auto op2 = e.op == EXP.equal ? EXP.identity : EXP.notIdentity;
Expression r = new IdentityExp(op2, e.loc, e.e1, e.e2);
return r.expressionSemantic(sc);
}
/* Check for struct equality without opEquals.
*/
if (t1.isTypeStruct() && t2.isTypeStruct())
{
auto sd = t1.isTypeStruct().sym;
if (sd != t2.isTypeStruct().sym)
return null;
import dmd.clone : needOpEquals;
if (!sc.previews.fieldwise && !needOpEquals(sd))
{
// Use bitwise equality.
auto op2 = e.op == EXP.equal ? EXP.identity : EXP.notIdentity;
Expression r = new IdentityExp(op2, e.loc, e.e1, e.e2);
return r.expressionSemantic(sc);
}
/* Do memberwise equality.
* https://dlang.org/spec/expression.html#equality_expressions
* Rewrite:
* e1 == e2
* as:
* e1.tupleof == e2.tupleof
*
* If sd is a nested struct, and if it's nested in a class, it will
* also compare the parent class's equality. Otherwise, compares
* the identity of parent context through void*.
*/
e = e.copy().isEqualExp();
e.e1 = new DotIdExp(e.loc, e.e1, Id._tupleof);
e.e2 = new DotIdExp(e.loc, e.e2, Id._tupleof);
auto sc2 = sc.push();
sc2.noAccessCheck = true;
Expression r = e.expressionSemantic(sc2);
sc2.pop();
return r;
}
/* Check for tuple equality.
*/
auto tup1 = e.e1.isTupleExp();
auto tup2 = e.e2.isTupleExp();
if (tup1 && tup2)
{
size_t dim = tup1.exps.length;
if (dim != tup2.exps.length)
{
error(e.loc, "mismatched sequence lengths, `%d` and `%d`",
cast(int)dim, cast(int)tup2.exps.length);
return ErrorExp.get();
}
Expression result;
if (dim == 0)
{
// zero-length tuple comparison should always return true or false.
result = IntegerExp.createBool(e.op == EXP.equal);
}
else
{
for (size_t i = 0; i < dim; i++)
{
auto ex1 = (*tup1.exps)[i];
auto ex2 = (*tup2.exps)[i];
auto eeq = new EqualExp(e.op, e.loc, ex1, ex2);
if (!result)
result = eeq;
else if (e.op == EXP.equal)
result = new LogicalExp(e.loc, EXP.andAnd, result, eeq);
else
result = new LogicalExp(e.loc, EXP.orOr, result, eeq);
}
assert(result);
}
result = Expression.combine(tup1.e0, tup2.e0, result);
result = result.expressionSemantic(sc);
return result;
}
return null;
}
Expression opOverloadCmp(CmpExp exp, Scope* sc, Type[2] aliasThisStop)
{
//printf("CmpExp:: () (%s)\n", e.toChars());
EXP cmpOp = exp.op;
auto e = compare_overload(exp, sc, Id.opCmp, cmpOp, aliasThisStop);
if (!e)
return null;
if (!e.type.isScalar() && e.type.equals(exp.e1.type))
{
error(e.loc, "recursive `opCmp` expansion");
return ErrorExp.get();
}
if (!e.isCallExp())
return e;
Type t1 = exp.e1.type.toBasetype();
Type t2 = exp.e2.type.toBasetype();
if (!t1.isTypeClass() || !t2.isTypeClass())
{
return new CmpExp(cmpOp, exp.loc, e, IntegerExp.literal!0).expressionSemantic(sc);
}
// Lower to object.__cmp(e1, e2)
Expression cl = new IdentifierExp(exp.loc, Id.empty);
cl = new DotIdExp(exp.loc, cl, Id.object);
cl = new DotIdExp(exp.loc, cl, Id.__cmp);
cl = cl.expressionSemantic(sc);
auto arguments = new Expressions();
// Check if op_overload found a better match by calling e2.opCmp(e1)
// If the operands were swapped, then the result must be reversed
// e1.opCmp(e2) == -e2.opCmp(e1)
// cmpop takes care of this
if (exp.op == cmpOp)
{
arguments.push(exp.e1);
arguments.push(exp.e2);
}
else
{
// Use better match found by op_overload
arguments.push(exp.e2);
arguments.push(exp.e1);
}
cl = new CallExp(e.loc, cl, arguments);
cl = new CmpExp(cmpOp, exp.loc, cl, new IntegerExp(0));
return cl.expressionSemantic(sc);
}
/*********************************
* Operator overloading for op=
*/
Expression opOverloadBinaryAssign(BinAssignExp e, Scope* sc, Type[2] aliasThisStop)
{
if (auto ae = e.e1.isArrayExp())
{
ae.e1 = ae.e1.expressionSemantic(sc);
ae.e1 = resolveProperties(sc, ae.e1);
Expression ae1old = ae.e1;
const(bool) maybeSlice = (ae.arguments.length == 0 || ae.arguments.length == 1 && (*ae.arguments)[0].isIntervalExp());
IntervalExp ie = null;
if (maybeSlice && ae.arguments.length)
{
ie = (*ae.arguments)[0].isIntervalExp();
}
Type att = null; // first cyclic `alias this` type
while (true)
{
if (ae.e1.isErrorExp())
return ae.e1;
Expression e0 = null;
Expression ae1save = ae.e1;
ae.lengthVar = null;
AggregateDeclaration ad = isAggregate(ae.e1.type);
if (!ad)
break;
if (search_function(ad, Id.opIndexOpAssign))
{
// Deal with $
Expression ae2 = resolveOpDollar(sc, ae, e0);
if (!ae2) // (a[i..j] op= e2) might be: a.opSliceOpAssign!(op)(e2, i, j)
goto Lfallback;
if (ae2.isErrorExp())
return ae2;
e.e2 = e.e2.expressionSemantic(sc);
if (e.e2.isErrorExp())
return e.e2;
/* Rewrite a[arguments] op= e2 as:
* a.opIndexOpAssign!(op)(e2, arguments)
*/
Expressions* a = ae.arguments.copy();
a.insert(0, e.e2);
Expression result = dotTemplateCall(ae.e1, Id.opIndexOpAssign, opToArg(sc, e.op), (*a)[]);
if (maybeSlice) // (a[] op= e2) might be: a.opSliceOpAssign!(op)(e2)
result = result.trySemantic(sc);
else
result = result.expressionSemantic(sc);
if (result)
return Expression.combine(e0, result);
}
Lfallback:
if (maybeSlice && search_function(ad, Id.opSliceOpAssign))
{
// Deal with $
Expression ae2 = resolveOpDollar(sc, ae, ie, e0);
if (ae2.isErrorExp())
return ae2;
e.e2 = e.e2.expressionSemantic(sc);
if (e.e2.isErrorExp())
return e.e2;
/* Rewrite (a[i..j] op= e2) as:
* a.opSliceOpAssign!(op)(e2, i, j)
*/
auto result = ie ?
dotTemplateCall(ae.e1, Id.opSliceOpAssign, opToArg(sc, e.op), e.e2, ie.lwr, ie.upr) :
dotTemplateCall(ae.e1, Id.opSliceOpAssign, opToArg(sc, e.op), e.e2);
return Expression.combine(e0, result.expressionSemantic(sc));
}
// Didn't find it. Forward to aliasthis
if (ad.aliasthis && !isRecursiveAliasThis(att, ae.e1.type))
{
/* Rewrite (a[arguments] op= e2) as:
* a.aliasthis[arguments] op= e2
*/
ae.e1 = resolveAliasThis(sc, ae1save, true);
if (ae.e1)
continue;
}
break;
}
ae.e1 = ae1old; // recovery
ae.lengthVar = null;
}
if (Expression result = e.binSemanticProp(sc))
return result;
// Don't attempt 'alias this' if an error occurred
if (e.e1.type.isTypeError() || e.e2.type.isTypeError())
return ErrorExp.get();
AggregateDeclaration ad1 = isAggregate(e.e1.type);