Debian Codegraph @

gcc/d/dmd/opover.d

raw
1 /**
2 * Handles operator overloading.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/operatoroverloading.html, Operator Overloading)
5 *
6 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
7 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
8 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
9 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/opover.d, _opover.d)
10 * Documentation: https://dlang.org/phobos/dmd_opover.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/opover.d
12 */
13
14 module dmd.opover;
15
16 import core.stdc.stdio;
17 import dmd.aggregate;
18 import dmd.aliasthis;
19 import dmd.arraytypes;
20 import dmd.astenums;
21 import dmd.dclass;
22 import dmd.declaration;
23 import dmd.dscope;
24 import dmd.dstruct;
25 import dmd.dsymbol;
26 import dmd.dsymbolsem;
27 import dmd.dtemplate;
28 import dmd.errors;
29 import dmd.expression;
30 import dmd.expressionsem;
31 import dmd.func;
32 import dmd.funcsem;
33 import dmd.globals;
34 import dmd.hdrgen;
35 import dmd.id;
36 import dmd.identifier;
37 import dmd.location;
38 import dmd.mtype;
39 import dmd.optimize;
40 import dmd.statement;
41 import dmd.templatesem;
42 import dmd.tokens;
43 import dmd.typesem;
44 import dmd.visitor;
45
46 /***********************************
47 * Determine if operands of binary op can be reversed
48 * to fit operator overload.
49 */
50 bool isCommutative(EXP op) @safe
51 {
52 switch (op)
53 {
54 case EXP.add:
55 case EXP.mul:
56 case EXP.and:
57 case EXP.or:
58 case EXP.xor:
59 // EqualExp
60 case EXP.equal:
61 case EXP.notEqual:
62 // CmpExp
63 case EXP.lessThan:
64 case EXP.lessOrEqual:
65 case EXP.greaterThan:
66 case EXP.greaterOrEqual:
67 return true;
68 default:
69 break;
70 }
71 return false;
72 }
73
74 /// Returns: whether `op` can be overloaded with `opBinary`
75 private bool hasOpBinary(EXP op) pure @safe
76 {
77 switch (op)
78 {
79 case EXP.add: return true;
80 case EXP.min: return true;
81 case EXP.mul: return true;
82 case EXP.div: return true;
83 case EXP.mod: return true;
84 case EXP.and: return true;
85 case EXP.or: return true;
86 case EXP.xor: return true;
87 case EXP.leftShift: return true;
88 case EXP.rightShift: return true;
89 case EXP.unsignedRightShift: return true;
90 case EXP.concatenate: return true;
91 case EXP.pow: return true;
92 case EXP.in_: return true;
93 default: return false;
94 }
95 }
96
97 /**
98 * Remove the = from op=, e.g. += becomes +
99 *
100 * Params:
101 * op = tag for a binary assign operator
102 * Returns: the corresponding binary operator, or `op` if it wasn't an assign operator
103 */
104 private EXP stripAssignOp(EXP op)
105 {
106 switch (op)
107 {
108 case EXP.addAssign: return EXP.add;
109 case EXP.minAssign: return EXP.min;
110 case EXP.mulAssign: return EXP.mul;
111 case EXP.divAssign: return EXP.div;
112 case EXP.modAssign: return EXP.mod;
113 case EXP.andAssign: return EXP.and;
114 case EXP.orAssign: return EXP.or;
115 case EXP.xorAssign: return EXP.xor;
116 case EXP.leftShiftAssign: return EXP.leftShift;
117 case EXP.rightShiftAssign: return EXP.rightShift;
118 case EXP.unsignedRightShiftAssign: return EXP.unsignedRightShift;
119 case EXP.concatenateAssign: return EXP.concatenate;
120 case EXP.powAssign: return EXP.pow;
121 default: return op;
122 }
123 }
124
125 /*******************************************
126 * Helper function to turn operator into template argument list
127 */
128 Objects* opToArg(Scope* sc, EXP op)
129 {
130 Expression e = new StringExp(Loc.initial, EXPtoString(stripAssignOp(op)));
131 e = e.expressionSemantic(sc);
132 auto tiargs = new Objects();
133 tiargs.push(e);
134 return tiargs;
135 }
136
137 // Try alias this on first operand
138 Expression checkAliasThisForLhs(AggregateDeclaration ad, Scope* sc, BinExp e, Type[2] aliasThisStop)
139 {
140 if (!ad || !ad.aliasthis)
141 return null;
142
143 /* Rewrite (e1 op e2) as:
144 * (e1.aliasthis op e2)
145 */
146 if (isRecursiveAliasThis(aliasThisStop[0], e.e1.type))
147 return null;
148 //printf("att %s e1 = %s\n", Token.toChars(e.op), e.e1.type.toChars());
149 BinExp be = cast(BinExp)e.copy();
150 // Resolve 'alias this' but in case of assigment don't resolve properties yet
151 // because 'e1 = e2' could mean 'e1(e2)' or 'e1() = e2'
152 bool findOnly = e.isAssignExp() !is null;
153 be.e1 = resolveAliasThis(sc, e.e1, true, findOnly);
154 if (!be.e1)
155 return null;
156
157 return be.trySemanticAliasThis(sc, aliasThisStop);
158 }
159
160 // Try alias this on second operand
161 Expression checkAliasThisForRhs(AggregateDeclaration ad, Scope* sc, BinExp e, Type[2] aliasThisStop)
162 {
163 if (!ad || !ad.aliasthis)
164 return null;
165 /* Rewrite (e1 op e2) as:
166 * (e1 op e2.aliasthis)
167 */
168 if (isRecursiveAliasThis(aliasThisStop[1], e.e2.type))
169 return null;
170 //printf("att %s e2 = %s\n", Token.toChars(e.op), e.e2.type.toChars());
171 BinExp be = cast(BinExp)e.copy();
172 be.e2 = resolveAliasThis(sc, e.e2, true);
173 if (!be.e2)
174 return null;
175
176 return be.trySemanticAliasThis(sc, aliasThisStop);
177 }
178
179 Expression opOverloadUnary(UnaExp e, Scope* sc)
180 {
181 if (auto ae = e.e1.isArrayExp())
182 {
183 ae.e1 = ae.e1.expressionSemantic(sc);
184 ae.e1 = resolveProperties(sc, ae.e1);
185 Expression ae1old = ae.e1;
186 const(bool) maybeSlice = (ae.arguments.length == 0 || ae.arguments.length == 1 && (*ae.arguments)[0].isIntervalExp());
187 IntervalExp ie = null;
188 if (maybeSlice && ae.arguments.length)
189 {
190 ie = (*ae.arguments)[0].isIntervalExp();
191 }
192 Type att = null; // first cyclic `alias this` type
193 while (true)
194 {
195 if (ae.e1.isErrorExp())
196 {
197 return ae.e1;
198 }
199 Expression ae1save = ae.e1;
200 ae.lengthVar = null;
201
202 AggregateDeclaration ad = isAggregate(ae.e1.type);
203 if (!ad)
204 break;
205
206 if (search_function(ad, Id.opIndexUnary))
207 {
208 Expression e0;
209 // Deal with $
210 Expression ae2 = resolveOpDollar(sc, ae, e0);
211 if (!ae2) // op(a[i..j]) might be: a.opSliceUnary!(op)(i, j)
212 goto Lfallback;
213 if (ae2.isErrorExp())
214 return ae2;
215 /* Rewrite op(a[arguments]) as:
216 * a.opIndexUnary!(op)(arguments)
217 */
218 Expression result = dotTemplateCall(ae.e1, Id.opIndexUnary, opToArg(sc, e.op), (*ae.arguments)[]);
219 if (maybeSlice) // op(a[]) might be: a.opSliceUnary!(op)()
220 result = result.trySemantic(sc);
221 else
222 result = result.expressionSemantic(sc);
223
224 if (result)
225 return Expression.combine(e0, result);
226 }
227 Lfallback:
228 if (maybeSlice && search_function(ad, Id.opSliceUnary))
229 {
230 // Deal with $
231 Expression e0;
232 auto ae2 = resolveOpDollar(sc, ae, ie, e0);
233 if (ae2.isErrorExp())
234 return ae2;
235 /* Rewrite op(a[i..j]) as:
236 * a.opSliceUnary!(op)(i, j)
237 */
238 Expression result = ie ?
239 dotTemplateCall(ae.e1, Id.opSliceUnary, opToArg(sc, e.op), ie.lwr, ie.upr) :
240 dotTemplateCall(ae.e1, Id.opSliceUnary, opToArg(sc, e.op));
241
242 return Expression.combine(e0, result.expressionSemantic(sc));
243 }
244 // Didn't find it. Forward to aliasthis
245 if (ad.aliasthis && !isRecursiveAliasThis(att, ae.e1.type))
246 {
247 /* Rewrite op(a[arguments]) as:
248 * op(a.aliasthis[arguments])
249 */
250 ae.e1 = resolveAliasThis(sc, ae1save, true);
251 if (ae.e1)
252 continue;
253 }
254 break;
255 }
256 ae.e1 = ae1old; // recovery
257 ae.lengthVar = null;
258 }
259 e.e1 = e.e1.expressionSemantic(sc);
260 e.e1 = resolveProperties(sc, e.e1);
261 Type att = null; // first cyclic `alias this` type
262 while (1)
263 {
264 if (e.e1.isErrorExp())
265 {
266 return e.e1;
267 }
268
269 AggregateDeclaration ad = isAggregate(e.e1.type);
270 if (!ad)
271 break;
272
273 /* Rewrite as:
274 * e1.opUnary!(op)()
275 */
276 if (Dsymbol fd = search_function(ad, Id.opUnary))
277 return dotTemplateCall(e.e1, Id.opUnary, opToArg(sc, e.op)).expressionSemantic(sc);
278
279 // Didn't find it. Forward to aliasthis
280 if (ad.aliasthis && !isRecursiveAliasThis(att, e.e1.type))
281 {
282 /* Rewrite op(e1) as:
283 * op(e1.aliasthis)
284 */
285 //printf("att una %s e1 = %s\n", EXPtoString(op).ptr, this.e1.type.toChars());
286 if (auto e1 = resolveAliasThis(sc, e.e1, true))
287 {
288 e.e1 = e1;
289 continue;
290 }
291 break;
292 }
293
294 // For ++ and --, rewrites to += and -= are also tried, so don't error yet
295 if (!e.isPreExp())
296 {
297 error(e.loc, "operator `%s` is not defined for `%s`", EXPtoString(e.op).ptr, ad.toChars());
298 errorSupplemental(ad.loc, "perhaps overload the operator with `auto opUnary(string op : \"%s\")() {}`",
299 EXPtoString(e.op).ptr);
300 return ErrorExp.get();
301 }
302
303 break;
304 }
305 return null;
306 }
307
308 Expression opOverloadArray(ArrayExp ae, Scope* sc)
309 {
310 ae.e1 = ae.e1.expressionSemantic(sc);
311 ae.e1 = resolveProperties(sc, ae.e1);
312 Expression ae1old = ae.e1;
313 const(bool) maybeSlice = (ae.arguments.length == 0 || ae.arguments.length == 1 && (*ae.arguments)[0].isIntervalExp());
314 IntervalExp ie = null;
315 if (maybeSlice && ae.arguments.length)
316 {
317 ie = (*ae.arguments)[0].isIntervalExp();
318 }
319 Type att = null; // first cyclic `alias this` type
320 while (true)
321 {
322 if (ae.e1.isErrorExp())
323 {
324 return ae.e1;
325 }
326 Expression e0 = null;
327 Expression ae1save = ae.e1;
328 ae.lengthVar = null;
329 Type t1b = ae.e1.type.toBasetype();
330 AggregateDeclaration ad = isAggregate(t1b);
331 if (!ad)
332 {
333 // If the non-aggregate expression ae.e1 is indexable or sliceable,
334 // convert it to the corresponding concrete expression.
335 if (isIndexableNonAggregate(t1b) || ae.e1.isTypeExp())
336 {
337 // Convert to SliceExp
338 if (maybeSlice)
339 return new SliceExp(ae.loc, ae.e1, ie).expressionSemantic(sc);
340
341 // Convert to IndexExp
342 if (ae.arguments.length == 1)
343 return new IndexExp(ae.loc, ae.e1, (*ae.arguments)[0]).expressionSemantic(sc);
344 }
345 break;
346 }
347 if (search_function(ad, Id.opIndex))
348 {
349 // Deal with $
350 auto ae2 = resolveOpDollar(sc, ae, e0);
351 if (!ae2) // a[i..j] might be: a.opSlice(i, j)
352 goto Lfallback;
353 if (ae2.isErrorExp())
354 return ae2;
355 /* Rewrite e1[arguments] as:
356 * e1.opIndex(arguments)
357 */
358 Expressions* a = ae.arguments.copy();
359 Expression result = new DotIdExp(ae.loc, ae.e1, Id.opIndex);
360 result = new CallExp(ae.loc, result, a);
361 if (maybeSlice) // a[] might be: a.opSlice()
362 result = result.trySemantic(sc);
363 else
364 result = result.expressionSemantic(sc);
365
366 if (result)
367 return Expression.combine(e0, result);
368 }
369 Lfallback:
370 if (maybeSlice && ae.e1.isTypeExp())
371 {
372 Expression result = new SliceExp(ae.loc, ae.e1, ie);
373 result = result.expressionSemantic(sc);
374 return Expression.combine(e0, result);
375 }
376 if (maybeSlice && search_function(ad, Id.opSlice))
377 {
378 // Deal with $
379 auto ae2 = resolveOpDollar(sc, ae, ie, e0);
380
381 if (ae2.isErrorExp())
382 {
383 if (!e0 && !search_function(ad, Id.dollar))
384 ad.loc.errorSupplemental("perhaps define `opDollar` for `%s`", ad.toChars());
385
386 return ae2;
387 }
388 /* Rewrite a[i..j] as:
389 * a.opSlice(i, j)
390 */
391 auto a = new Expressions();
392 if (ie)
393 {
394 a.push(ie.lwr);
395 a.push(ie.upr);
396 }
397 Expression result = new DotIdExp(ae.loc, ae.e1, Id.opSlice);
398 result = new CallExp(ae.loc, result, a);
399 result = result.expressionSemantic(sc);
400 return Expression.combine(e0, result);
401 }
402 // Didn't find it. Forward to aliasthis
403 if (ad.aliasthis && !isRecursiveAliasThis(att, ae.e1.type))
404 {
405 //printf("att arr e1 = %s\n", this.e1.type.toChars());
406 /* Rewrite op(a[arguments]) as:
407 * op(a.aliasthis[arguments])
408 */
409 ae.e1 = resolveAliasThis(sc, ae1save, true);
410 if (ae.e1)
411 continue;
412 }
413 break;
414 }
415 ae.e1 = ae1old; // recovery
416 ae.lengthVar = null;
417 return null;
418 }
419
420 /***********************************************
421 * This is mostly the same as opOverloadUnary but has
422 * a different rewrite.
423 */
424 Expression opOverloadCast(CastExp e, Scope* sc, Type att = null)
425 {
426 AggregateDeclaration ad = isAggregate(e.e1.type);
427 if (!ad)
428 return null;
429
430 // Rewrite as: e1.opCast!(T)()
431 if (Dsymbol fd = search_function(ad, Id.opCast))
432 {
433 version (all)
434 {
435 // Backwards compatibility with D1 if opCast is a function, not a template
436 if (fd.isFuncDeclaration())
437 {
438 // Rewrite as: e1.opCast()
439 return build_overload(e.loc, sc, e.e1, null, fd);
440 }
441 }
442 auto tiargs = new Objects();
443 tiargs.push(e.to);
444 return dotTemplateCall(e.e1, Id.opCast, tiargs).expressionSemantic(sc);
445 }
446 // Didn't find it. Forward to aliasthis
447 if (ad.aliasthis && !isRecursiveAliasThis(att, e.e1.type))
448 {
449 // Rewrite `e1.opCast()` as `e1.aliasthis.opCast()`
450 if (auto e1 = resolveAliasThis(sc, e.e1, true))
451 {
452 CastExp result = e.copy().isCastExp();
453 result.e1 = e1;
454 return result.opOverloadCast(sc, att);
455 }
456 }
457 return null;
458 }
459
460 // When no operator overload functions are found for `e`, recursively try with `alias this`
461 // Returns: `null` when still no overload found, otherwise resolved lowering
462 Expression binAliasThis(BinExp e, Scope* sc, Type[2] aliasThisStop)
463 {
464 AggregateDeclaration ad1 = isAggregate(e.e1.type);
465 AggregateDeclaration ad2 = isAggregate(e.e2.type);
466 Expression rewrittenLhs;
467 if (!(e.isAssignExp && ad2 && ad1 == ad2)) // https://issues.dlang.org/show_bug.cgi?id=2943
468 {
469 if (Expression result = checkAliasThisForLhs(ad1, sc, e, aliasThisStop))
470 {
471 /* https://issues.dlang.org/show_bug.cgi?id=19441
472 *
473 * alias this may not be used for partial assignment.
474 * If a struct has a single member which is aliased this
475 * directly or aliased to a ref getter function that returns
476 * the mentioned member, then alias this may be
477 * used since the object will be fully initialised.
478 * If the struct is nested, the context pointer is considered
479 * one of the members, hence the `ad1.fields.length == 2 && ad1.vthis`
480 * condition.
481 */
482 auto ae = result.isAssignExp();
483 if (!ae)
484 return result; // i.e: Rewrote `e1 = e2` -> `e1(e2)`
485
486 auto dve = ae.e1.isDotVarExp();
487 if (!dve)
488 return result; // i.e: Rewrote `e1 = e2` -> `e1() = e2`
489
490 if (auto ad = dve.var.isMember2())
491 {
492 // i.e: Rewrote `e1 = e2` -> `e1.some.var = e2`
493 // Ensure that `var` is the only field member in `ad`
494 if (ad.fields.length == 1 || (ad.fields.length == 2 && ad.vthis))
495 {
496 if (dve.var == ad.aliasthis.sym)
497 return result;
498 }
499 }
500 rewrittenLhs = ae.e1;
501 }
502 }
503 if (!(e.isAssignExp && ad1 && ad1 == ad2)) // https://issues.dlang.org/show_bug.cgi?id=2943
504 {
505 if (Expression result = checkAliasThisForRhs(ad2, sc, e, aliasThisStop))
506 return result;
507 }
508 if (rewrittenLhs)
509 {
510 error(e.loc, "cannot use `alias this` to partially initialize variable `%s` of type `%s`. Use `%s`",
511 e.e1.toChars(), ad1.toChars(), rewrittenLhs.toChars());
512 return ErrorExp.get();
513 }
514 return null;
515 }
516
517 Expression opOverloadAssign(AssignExp e, Scope* sc, Type[2] aliasThisStop)
518 {
519 AggregateDeclaration ad1 = isAggregate(e.e1.type);
520 AggregateDeclaration ad2 = isAggregate(e.e2.type);
521 if (ad1 == ad2)
522 {
523 StructDeclaration sd = ad1.isStructDeclaration();
524 if (sd &&
525 (!sd.hasIdentityAssign ||
526 /* Do a blit if we can and the rvalue is something like .init,
527 * where a postblit is not necessary.
528 */
529 (sd.hasBlitAssign && !e.e2.isLvalue())))
530 {
531 /* This is bitwise struct assignment. */
532 return null;
533 }
534 }
535 Dsymbol s = search_function(ad1, Id.opAssign);
536
537 bool choseReverse;
538 if (auto result = pickBestBinaryOverload(sc, null, s, null, e, choseReverse))
539 return result;
540
541 return binAliasThis(e, sc, aliasThisStop);
542 }
543
544 Expression opOverloadBinary(BinExp e, Scope* sc, Type[2] aliasThisStop)
545 {
546 if (Expression err = binSemanticProp(e, sc))
547 return err;
548
549 AggregateDeclaration ad1 = isAggregate(e.e1.type);
550 AggregateDeclaration ad2 = isAggregate(e.e2.type);
551
552 // Try opBinary and opBinaryRight
553 Dsymbol s = search_function(ad1, Id.opBinary);
554 if (s && !s.isTemplateDeclaration())
555 {
556 error(e.e1.loc, "`%s.opBinary` isn't a template", e.e1.toChars());
557 return ErrorExp.get();
558 }
559
560 Dsymbol s_r = search_function(ad2, Id.opBinaryRight);
561 if (s_r && !s_r.isTemplateDeclaration())
562 {
563 error(e.e2.loc, "`%s.opBinaryRight` isn't a template", e.e2.toChars());
564 return ErrorExp.get();
565 }
566 if (s_r && s_r == s) // https://issues.dlang.org/show_bug.cgi?id=12778
567 s_r = null;
568
569 bool choseReverse;
570 if (auto result = pickBestBinaryOverload(sc, opToArg(sc, e.op), s, s_r, e, choseReverse))
571 return result;
572
573 return binAliasThis(e, sc, aliasThisStop);
574 }
575
576 /**
577 * If applicable, print an error relating to implementing / fixing `opBinary` functions.
578 * Params:
579 * e = binary operation
580 * sc = scope to try `opBinary!""` semantic in for error messages
581 * Returns: `true` when an error related to `opBinary` was printed
582 */
583 bool suggestBinaryOverloads(BinExp e, Scope* sc)
584 {
585 if (!e.op.hasOpBinary)
586 return false;
587
588 AggregateDeclaration ad1 = isAggregate(e.e1.type);
589 AggregateDeclaration ad2 = isAggregate(e.e2.type);
590
591 if (ad1)
592 {
593 if (Dsymbol s = search_function(ad1, Id.opBinary))
594 {
595 // This expressionSemantic will fail, otherwise operator overloading would have succeeded before
596 dotTemplateCall(e.e1, Id.opBinary, opToArg(sc, e.op), e.e2).expressionSemantic(sc);
597 errorSupplemental(s.loc, "`opBinary` defined here");
598 return true;
599 }
600 error(e.loc, "operator `%s` is not defined for type `%s`", EXPtoString(e.op).ptr, e.e1.type.toChars);
601 errorSupplemental(ad1.loc, "perhaps overload the operator with `auto opBinary(string op : \"%s\")(%s rhs) {}`", EXPtoString(e.op).ptr, e.e2.type.toChars);
602 return true;
603 }
604 else if (ad2)
605 {
606 if (Dsymbol s_r = search_function(ad1, Id.opBinaryRight))
607 {
608 dotTemplateCall(e.e2, Id.opBinaryRight, opToArg(sc, e.op), e.e1).expressionSemantic(sc);
609 errorSupplemental(s_r.loc, "`opBinaryRight` defined here");
610 return true;
611 }
612 error(e.loc, "operator `%s` is not defined for type `%s`", EXPtoString(e.op).ptr, e.e2.type.toChars);
613 errorSupplemental(ad2.loc, "perhaps overload the operator with `auto opBinaryRight(string op : \"%s\")(%s rhs) {}`", EXPtoString(e.op).ptr, e.e1.type.toChars);
614 return true;
615 }
616 return false;
617 }
618
619 /**
620 * If applicable, print an error relating to implementing / fixing `opOpAssign` or `opUnary` functions.
621 * Params:
622 * exp = binary operation
623 * sc = scope to try `opOpAssign!""` semantic in for error messages
624 * parent = if `exp` was lowered from this `PreExp` or `PostExp`, mention `opUnary` as well
625 * Returns: `true` when an error related to `opOpAssign` was printed
626 */
627 bool suggestOpOpAssign(BinAssignExp exp, Scope* sc, Expression parent)
628 {
629 auto ad = isAggregate(exp.e1.type);
630 if (!ad)
631 return false;
632
633 if (parent && (parent.isPreExp() || parent.isPostExp()))
634 {
635 error(exp.loc, "operator `%s` not supported for `%s` of type `%s`", EXPtoString(parent.op).ptr, exp.e1.toChars(), ad.toChars());
636 errorSupplemental(ad.loc,
637 "perhaps implement `auto opUnary(string op : \"%s\")() {}`"~
638 " or `auto opOpAssign(string op : \"%s\")(int) {}`",
639 EXPtoString(stripAssignOp(parent.op)).ptr,
640 EXPtoString(stripAssignOp(exp.op)).ptr
641 );
642 return true;
643 }
644
645 if (const s = search_function(ad, Id.opOpAssign))
646 {
647 // This expressionSemantic will fail, otherwise operator overloading would have succeeded before
648 dotTemplateCall(exp.e1, Id.opOpAssign, opToArg(sc, exp.op), exp.e2).expressionSemantic(sc);
649 }
650 else
651 {
652 error(exp.loc, "operator `%s` not supported for `%s` of type `%s`", EXPtoString(exp.op).ptr, exp.e1.toChars(), ad.toChars());
653 errorSupplemental(ad.loc, "perhaps implement `auto opOpAssign(string op : \"%s\")(%s) {}`",
654 EXPtoString(stripAssignOp(exp.op)).ptr, exp.e2.type.toChars());
655 }
656 return true;
657 }
658
659 // Helper to construct e.id!tiargs(args), e.g. `lhs.opBinary!"+"(rhs)`
660 private Expression dotTemplateCall(Expression e, Identifier id, Objects* tiargs, Expression[] args...)
661 {
662 auto ti = new DotTemplateInstanceExp(e.loc, e, id, tiargs);
663 auto expressions = new Expressions();
664 expressions.pushSlice(args);
665 return new CallExp(e.loc, ti, expressions);
666 }
667
668 Expression opOverloadEqual(EqualExp e, Scope* sc, Type[2] aliasThisStop)
669 {
670 Type t1 = e.e1.type.toBasetype();
671 Type t2 = e.e2.type.toBasetype();
672
673 /* Array equality is handled by expressionSemantic() potentially
674 * lowering to object.__equals(), which takes care of overloaded
675 * operators for the element types.
676 */
677 if (t1.isStaticOrDynamicArray() && t2.isStaticOrDynamicArray())
678 {
679 return null;
680 }
681
682 /* Check for class equality with null literal or typeof(null).
683 */
684 if (t1.isTypeClass() && e.e2.isNullExp() ||
685 t2.isTypeClass() && e.e1.isNullExp())
686 {
687 error(e.loc, "use `%s` instead of `%s` when comparing with `null`",
688 EXPtoString(e.op == EXP.equal ? EXP.identity : EXP.notIdentity).ptr,
689 EXPtoString(e.op).ptr);
690 return ErrorExp.get();
691 }
692 if (t1.isTypeClass() && t2.isTypeNull() ||
693 t1.isTypeNull() && t2.isTypeClass())
694 {
695 // Comparing a class with typeof(null) should not call opEquals
696 return null;
697 }
698
699 /* Check for class equality.
700 */
701 if (t1.isTypeClass() && t2.isTypeClass())
702 {
703 ClassDeclaration cd1 = t1.isClassHandle();
704 ClassDeclaration cd2 = t2.isClassHandle();
705 if (!(cd1.classKind == ClassKind.cpp || cd2.classKind == ClassKind.cpp))
706 {
707 /* Rewrite as:
708 * .object.opEquals(e1, e2)
709 */
710 if (!ClassDeclaration.object)
711 {
712 error(e.loc, "cannot compare classes for equality because `object.Object` was not declared");
713 return null;
714 }
715
716 Expression e1x = e.e1;
717 Expression e2x = e.e2;
718
719 /* The explicit cast is necessary for interfaces
720 * https://issues.dlang.org/show_bug.cgi?id=4088
721 */
722 Type to = ClassDeclaration.object.getType();
723 if (cd1.isInterfaceDeclaration())
724 e1x = new CastExp(e.loc, e.e1, t1.isMutable() ? to : to.constOf());
725 if (cd2.isInterfaceDeclaration())
726 e2x = new CastExp(e.loc, e.e2, t2.isMutable() ? to : to.constOf());
727
728 Expression result = new IdentifierExp(e.loc, Id.empty);
729 result = new DotIdExp(e.loc, result, Id.object);
730 result = new DotIdExp(e.loc, result, Id.opEquals);
731 result = new CallExp(e.loc, result, e1x, e2x);
732 if (e.op == EXP.notEqual)
733 result = new NotExp(e.loc, result);
734 result = result.expressionSemantic(sc);
735 return result;
736 }
737 }
738
739 EXP cmpOp;
740 if (Expression result = compare_overload(e, sc, Id.opEquals, cmpOp, aliasThisStop))
741 {
742 if (lastComma(result).isCallExp() && e.op == EXP.notEqual)
743 {
744 result = new NotExp(result.loc, result);
745 result = result.expressionSemantic(sc);
746 }
747 return result;
748 }
749
750 /* Check for pointer equality.
751 */
752 if (t1.isTypePointer() || t2.isTypePointer())
753 {
754 /* Rewrite:
755 * ptr1 == ptr2
756 * as:
757 * ptr1 is ptr2
758 *
759 * This is just a rewriting for deterministic AST representation
760 * as the backend input.
761 */
762 auto op2 = e.op == EXP.equal ? EXP.identity : EXP.notIdentity;
763 Expression r = new IdentityExp(op2, e.loc, e.e1, e.e2);
764 return r.expressionSemantic(sc);
765 }
766
767 /* Check for struct equality without opEquals.
768 */
769 if (t1.isTypeStruct() && t2.isTypeStruct())
770 {
771 auto sd = t1.isTypeStruct().sym;
772 if (sd != t2.isTypeStruct().sym)
773 return null;
774
775 import dmd.clone : needOpEquals;
776 if (!sc.previews.fieldwise && !needOpEquals(sd))
777 {
778 // Use bitwise equality.
779 auto op2 = e.op == EXP.equal ? EXP.identity : EXP.notIdentity;
780 Expression r = new IdentityExp(op2, e.loc, e.e1, e.e2);
781 return r.expressionSemantic(sc);
782 }
783
784 /* Do memberwise equality.
785 * https://dlang.org/spec/expression.html#equality_expressions
786 * Rewrite:
787 * e1 == e2
788 * as:
789 * e1.tupleof == e2.tupleof
790 *
791 * If sd is a nested struct, and if it's nested in a class, it will
792 * also compare the parent class's equality. Otherwise, compares
793 * the identity of parent context through void*.
794 */
795 e = e.copy().isEqualExp();
796 e.e1 = new DotIdExp(e.loc, e.e1, Id._tupleof);
797 e.e2 = new DotIdExp(e.loc, e.e2, Id._tupleof);
798
799 auto sc2 = sc.push();
800 sc2.noAccessCheck = true;
801 Expression r = e.expressionSemantic(sc2);
802 sc2.pop();
803 return r;
804 }
805
806 /* Check for tuple equality.
807 */
808 auto tup1 = e.e1.isTupleExp();
809 auto tup2 = e.e2.isTupleExp();
810 if (tup1 && tup2)
811 {
812 size_t dim = tup1.exps.length;
813 if (dim != tup2.exps.length)
814 {
815 error(e.loc, "mismatched sequence lengths, `%d` and `%d`",
816 cast(int)dim, cast(int)tup2.exps.length);
817 return ErrorExp.get();
818 }
819
820 Expression result;
821 if (dim == 0)
822 {
823 // zero-length tuple comparison should always return true or false.
824 result = IntegerExp.createBool(e.op == EXP.equal);
825 }
826 else
827 {
828 for (size_t i = 0; i < dim; i++)
829 {
830 auto ex1 = (*tup1.exps)[i];
831 auto ex2 = (*tup2.exps)[i];
832 auto eeq = new EqualExp(e.op, e.loc, ex1, ex2);
833
834 if (!result)
835 result = eeq;
836 else if (e.op == EXP.equal)
837 result = new LogicalExp(e.loc, EXP.andAnd, result, eeq);
838 else
839 result = new LogicalExp(e.loc, EXP.orOr, result, eeq);
840 }
841 assert(result);
842 }
843 result = Expression.combine(tup1.e0, tup2.e0, result);
844 result = result.expressionSemantic(sc);
845
846 return result;
847 }
848 return null;
849 }
850
851 Expression opOverloadCmp(CmpExp exp, Scope* sc, Type[2] aliasThisStop)
852 {
853 //printf("CmpExp:: () (%s)\n", e.toChars());
854 EXP cmpOp = exp.op;
855 auto e = compare_overload(exp, sc, Id.opCmp, cmpOp, aliasThisStop);
856 if (!e)
857 return null;
858
859 if (!e.type.isScalar() && e.type.equals(exp.e1.type))
860 {
861 error(e.loc, "recursive `opCmp` expansion");
862 return ErrorExp.get();
863 }
864 if (!e.isCallExp())
865 return e;
866
867 Type t1 = exp.e1.type.toBasetype();
868 Type t2 = exp.e2.type.toBasetype();
869 if (!t1.isTypeClass() || !t2.isTypeClass())
870 {
871 return new CmpExp(cmpOp, exp.loc, e, IntegerExp.literal!0).expressionSemantic(sc);
872 }
873
874 // Lower to object.__cmp(e1, e2)
875 Expression cl = new IdentifierExp(exp.loc, Id.empty);
876 cl = new DotIdExp(exp.loc, cl, Id.object);
877 cl = new DotIdExp(exp.loc, cl, Id.__cmp);
878 cl = cl.expressionSemantic(sc);
879
880 auto arguments = new Expressions();
881 // Check if op_overload found a better match by calling e2.opCmp(e1)
882 // If the operands were swapped, then the result must be reversed
883 // e1.opCmp(e2) == -e2.opCmp(e1)
884 // cmpop takes care of this
885 if (exp.op == cmpOp)
886 {
887 arguments.push(exp.e1);
888 arguments.push(exp.e2);
889 }
890 else
891 {
892 // Use better match found by op_overload
893 arguments.push(exp.e2);
894 arguments.push(exp.e1);
895 }
896
897 cl = new CallExp(e.loc, cl, arguments);
898 cl = new CmpExp(cmpOp, exp.loc, cl, new IntegerExp(0));
899 return cl.expressionSemantic(sc);
900 }
901
902 /*********************************
903 * Operator overloading for op=
904 */
905 Expression opOverloadBinaryAssign(BinAssignExp e, Scope* sc, Type[2] aliasThisStop)
906 {
907 if (auto ae = e.e1.isArrayExp())
908 {
909 ae.e1 = ae.e1.expressionSemantic(sc);
910 ae.e1 = resolveProperties(sc, ae.e1);
911 Expression ae1old = ae.e1;
912 const(bool) maybeSlice = (ae.arguments.length == 0 || ae.arguments.length == 1 && (*ae.arguments)[0].isIntervalExp());
913 IntervalExp ie = null;
914 if (maybeSlice && ae.arguments.length)
915 {
916 ie = (*ae.arguments)[0].isIntervalExp();
917 }
918 Type att = null; // first cyclic `alias this` type
919 while (true)
920 {
921 if (ae.e1.isErrorExp())
922 return ae.e1;
923
924 Expression e0 = null;
925 Expression ae1save = ae.e1;
926 ae.lengthVar = null;
927 AggregateDeclaration ad = isAggregate(ae.e1.type);
928 if (!ad)
929 break;
930 if (search_function(ad, Id.opIndexOpAssign))
931 {
932 // Deal with $
933 Expression ae2 = resolveOpDollar(sc, ae, e0);
934 if (!ae2) // (a[i..j] op= e2) might be: a.opSliceOpAssign!(op)(e2, i, j)
935 goto Lfallback;
936 if (ae2.isErrorExp())
937 return ae2;
938 e.e2 = e.e2.expressionSemantic(sc);
939 if (e.e2.isErrorExp())
940 return e.e2;
941
942 /* Rewrite a[arguments] op= e2 as:
943 * a.opIndexOpAssign!(op)(e2, arguments)
944 */
945 Expressions* a = ae.arguments.copy();
946 a.insert(0, e.e2);
947 Expression result = dotTemplateCall(ae.e1, Id.opIndexOpAssign, opToArg(sc, e.op), (*a)[]);
948 if (maybeSlice) // (a[] op= e2) might be: a.opSliceOpAssign!(op)(e2)
949 result = result.trySemantic(sc);
950 else
951 result = result.expressionSemantic(sc);
952
953 if (result)
954 return Expression.combine(e0, result);
955 }
956 Lfallback:
957 if (maybeSlice && search_function(ad, Id.opSliceOpAssign))
958 {
959 // Deal with $
960 Expression ae2 = resolveOpDollar(sc, ae, ie, e0);
961 if (ae2.isErrorExp())
962 return ae2;
963
964 e.e2 = e.e2.expressionSemantic(sc);
965 if (e.e2.isErrorExp())
966 return e.e2;
967
968 /* Rewrite (a[i..j] op= e2) as:
969 * a.opSliceOpAssign!(op)(e2, i, j)
970 */
971 auto result = ie ?
972 dotTemplateCall(ae.e1, Id.opSliceOpAssign, opToArg(sc, e.op), e.e2, ie.lwr, ie.upr) :
973 dotTemplateCall(ae.e1, Id.opSliceOpAssign, opToArg(sc, e.op), e.e2);
974
975 return Expression.combine(e0, result.expressionSemantic(sc));
976 }
977 // Didn't find it. Forward to aliasthis
978 if (ad.aliasthis && !isRecursiveAliasThis(att, ae.e1.type))
979 {
980 /* Rewrite (a[arguments] op= e2) as:
981 * a.aliasthis[arguments] op= e2
982 */
983 ae.e1 = resolveAliasThis(sc, ae1save, true);
984 if (ae.e1)
985 continue;
986 }
987 break;
988 }
989 ae.e1 = ae1old; // recovery
990 ae.lengthVar = null;
991 }
992
993 if (Expression result = e.binSemanticProp(sc))
994 return result;
995
996 // Don't attempt 'alias this' if an error occurred
997 if (e.e1.type.isTypeError() || e.e2.type.isTypeError())
998 return ErrorExp.get();
999
1000 AggregateDeclaration ad1 = isAggregate(e.e1.type);
1001 Dsymbol s = search_function(ad1, Id.opOpAssign);
1002 if (s && !s.isTemplateDeclaration())
1003 {
1004 error(e.loc, "`%s.opOpAssign` isn't a template", e.e1.toChars());
1005 return ErrorExp.get();
1006 }
1007
1008 bool choseReverse;
1009 if (auto res = pickBestBinaryOverload(sc, opToArg(sc, e.op), s, null, e, choseReverse))
1010 return res;
1011
1012 Expression result = checkAliasThisForLhs(ad1, sc, e, aliasThisStop);
1013 if (result || !s) // no point in trying Rhs alias-this if there's no overload of any kind in lhs
1014 return result;
1015
1016 return checkAliasThisForRhs(isAggregate(e.e2.type), sc, e, aliasThisStop);
1017 }
1018
1019 /**
1020 Given symbols `s` and `s_r`, try to instantiate `e.e1.s!tiargs(e.e2)` and `e.e2.s_r!tiargs(e.e1)`,
1021 and return the one with the best match level.
1022
1023 Params:
1024 sc = scope
1025 tiargs = (optional) template arguments to instantiate symbols with
1026 s = (optional) symbol of straightforward template (e.g. opBinary)
1027 s_r = (optional) symbol of reversed template (e.g. opBinaryRight)
1028 e = binary expression being overloaded, supplying arguments to the function calls
1029 choseReverse = set to true when `s_r` was chosen instead of `s`
1030 Returns:
1031 Resulting operator overload function call, or `null` if neither symbol worked
1032 */
1033 private Expression pickBestBinaryOverload(Scope* sc, Objects* tiargs, Dsymbol s, Dsymbol s_r, BinExp e, out bool choseReverse)
1034 {
1035 if (!s && !s_r)
1036 return null;
1037
1038 Expressions* args1 = new Expressions(1);
1039 (*args1)[0] = e.e1;
1040 expandTuples(args1);
1041 Expressions* args2 = new Expressions(1);
1042 (*args2)[0] = e.e2;
1043 expandTuples(args2);
1044 MatchAccumulator m;
1045
1046 if (s)
1047 {
1048 functionResolve(m, s, e.loc, sc, tiargs, e.e1.type, ArgumentList(args2), null);
1049 if (m.lastf && (m.lastf.errors || m.lastf.hasSemantic3Errors()))
1050 return ErrorExp.get();
1051 }
1052 FuncDeclaration lastf = m.lastf;
1053 int count = m.count;
1054 if (s_r)
1055 {
1056 functionResolve(m, s_r, e.loc, sc, tiargs, e.e2.type, ArgumentList(args1), null);
1057 if (m.lastf && (m.lastf.errors || m.lastf.hasSemantic3Errors()))
1058 return ErrorExp.get();
1059 }
1060 if (m.count > 1)
1061 {
1062 /* The following if says "not ambiguous" if there's one match
1063 * from s and one from s_r, in which case we pick s.
1064 * This doesn't follow the spec, but is a workaround for the case
1065 * where opEquals was generated from templates and we cannot figure
1066 * out if both s and s_r came from the same declaration or not.
1067 * The test case is:
1068 * import std.typecons;
1069 * void main() {
1070 * assert(tuple("has a", 2u) == tuple("has a", 1));
1071 * }
1072 */
1073 if (!(m.lastf == lastf && m.count == 2 && count == 1))
1074 {
1075 // Error, ambiguous
1076 error(e.loc, "overloads `%s` and `%s` both match argument list for `%s`", m.lastf.type.toChars(), m.nextf.type.toChars(), m.lastf.toChars());
1077 }
1078 }
1079 else if (m.last == MATCH.nomatch)
1080 {
1081 if (tiargs)
1082 return null;
1083 m.lastf = null;
1084 }
1085
1086 if (lastf && m.lastf == lastf || !s_r && m.last == MATCH.nomatch)
1087 {
1088 choseReverse = false;
1089 // Rewrite (e1 op e2) as e1.opfunc(e2)
1090 return build_overload(e.loc, sc, e.e1, e.e2, m.lastf ? m.lastf : s);
1091 }
1092 else
1093 {
1094 choseReverse = true;
1095 // Rewrite (e1 op e2) as e2.opfunc_r(e1)
1096 return build_overload(e.loc, sc, e.e2, e.e1, m.lastf ? m.lastf : s_r);
1097 }
1098 }
1099
1100 /******************************************
1101 * Common code for overloading of EqualExp and CmpExp
1102 */
1103 private Expression compare_overload(BinExp e, Scope* sc, Identifier id, ref EXP cmpOp, Type[2] aliasThisStop)
1104 {
1105 //printf("BinExp::compare_overload(id = %s) %s\n", id.toChars(), e.toChars());
1106 AggregateDeclaration ad1 = isAggregate(e.e1.type);
1107 AggregateDeclaration ad2 = isAggregate(e.e2.type);
1108 Dsymbol s = search_function(ad1, id);
1109 Dsymbol s_r = search_function(ad2, id);
1110
1111 if (s == s_r)
1112 s_r = null;
1113
1114 bool choseReverse;
1115 if (auto res = pickBestBinaryOverload(sc, null, s, s_r, e, choseReverse))
1116 {
1117 if (choseReverse)
1118 cmpOp = reverseRelation(e.op);
1119 return res;
1120 }
1121
1122 /*
1123 * https://issues.dlang.org/show_bug.cgi?id=16657
1124 * at this point, no matching opEquals was found for structs,
1125 * so we should not follow the alias this comparison code.
1126 */
1127 if (e.isEqualExp() && ad1 == ad2)
1128 return null;
1129 Expression result = checkAliasThisForLhs(ad1, sc, e, aliasThisStop);
1130 if (result)
1131 return result;
1132
1133 result = checkAliasThisForRhs(isAggregate(e.e2.type), sc, e, aliasThisStop);
1134 if (result)
1135 return result;
1136
1137 if (s || s_r)
1138 return null;
1139
1140 Expression suggestOverloading(Expression other, AggregateDeclaration ad)
1141 {
1142 error(e.loc, "no operator `%s` for type `%s`", EXPtoString(e.op).ptr, ad.toChars);
1143 string op = e.isEqualExp() ? "bool" : "int";
1144 errorSupplemental(ad.loc, "perhaps overload it with `%.*s %s(%s other) const {}`", op.fTuple.expand, id.toChars, other.type.toChars);
1145 return ErrorExp.get();
1146 }
1147
1148 // Classes have opCmp and opEquals defined in `Object` to fall back on already
1149 if (ad1 && ad1.isStructDeclaration)
1150 return suggestOverloading(e.e2, ad1);
1151 if (ad2 && ad2.isStructDeclaration)
1152 return suggestOverloading(e.e1, ad2);
1153
1154 return null;
1155 }
1156
1157 /***********************************
1158 * Utility to build a function call out of this reference and argument.
1159 */
1160 Expression build_overload(Loc loc, Scope* sc, Expression ethis, Expression earg, Dsymbol d)
1161 {
1162 assert(d);
1163 Expression e;
1164 if (Declaration decl = d.isDeclaration())
1165 e = new DotVarExp(loc, ethis, decl, false);
1166 else
1167 e = new DotIdExp(loc, ethis, d.ident);
1168 e = new CallExp(loc, e, earg);
1169 e = e.expressionSemantic(sc);
1170 return e;
1171 }
1172
1173 /***************************************
1174 * Search for function funcid in aggregate ad.
1175 */
1176 Dsymbol search_function(ScopeDsymbol ad, Identifier funcid)
1177 {
1178 if (!ad)
1179 return null;
1180 if (Dsymbol s = ad.search(Loc.initial, funcid))
1181 {
1182 //printf("search_function: s = '%s'\n", s.kind());
1183 Dsymbol s2 = s.toAlias();
1184 //printf("search_function: s2 = '%s'\n", s2.kind());
1185 FuncDeclaration fd = s2.isFuncDeclaration();
1186 if (fd && fd.type.isTypeFunction())
1187 return fd;
1188 if (TemplateDeclaration td = s2.isTemplateDeclaration())
1189 return td;
1190 }
1191 return null;
1192 }
1193
1194 /**************************************
1195 * Figure out what is being foreach'd over by looking at the ForeachAggregate.
1196 * Params:
1197 * sc = context
1198 * isForeach = true for foreach, false for foreach_reverse
1199 * feaggr = ForeachAggregate
1200 * sapply = set to function opApply/opApplyReverse, or delegate, or null.
1201 * Overload resolution is not done.
1202 * Returns:
1203 * true if successfully figured it out; feaggr updated with semantic analysis.
1204 * false for failed, which is an error.
1205 */
1206 bool inferForeachAggregate(Scope* sc, bool isForeach, ref Expression feaggr, out Dsymbol sapply)
1207 {
1208 //printf("inferForeachAggregate(%s)\n", feaggr.toChars());
1209 bool sliced;
1210 Type att = null;
1211 auto aggr = feaggr;
1212 while (1)
1213 {
1214 aggr = aggr.expressionSemantic(sc);
1215 aggr = resolveProperties(sc, aggr);
1216 aggr = aggr.optimize(WANTvalue);
1217 if (!aggr.type || aggr.isErrorExp())
1218 return false;
1219 Type tab = aggr.type.toBasetype();
1220 switch (tab.ty)
1221 {
1222 case Tarray: // https://dlang.org/spec/statement.html#foreach_over_arrays
1223 case Tsarray: // https://dlang.org/spec/statement.html#foreach_over_arrays
1224 case Ttuple: // https://dlang.org/spec/statement.html#foreach_over_tuples
1225 case Taarray: // https://dlang.org/spec/statement.html#foreach_over_associative_arrays
1226 break;
1227
1228 case Tclass:
1229 case Tstruct:
1230 {
1231 AggregateDeclaration ad = isAggregate(tab);
1232 if (!sliced)
1233 {
1234 sapply = search_function(ad, isForeach ? Id.apply : Id.applyReverse);
1235 if (sapply)
1236 {
1237 // https://dlang.org/spec/statement.html#foreach_over_struct_and_classes
1238 // opApply aggregate
1239 break;
1240 }
1241 if (feaggr.op != EXP.type)
1242 {
1243 /* See if rewriting `aggr` to `aggr[]` will work
1244 */
1245 Expression rinit = new ArrayExp(aggr.loc, feaggr);
1246 rinit = rinit.trySemantic(sc);
1247 if (rinit) // if it worked
1248 {
1249 aggr = rinit;
1250 sliced = true; // only try it once
1251 continue;
1252 }
1253 }
1254 }
1255 if (ad.search(Loc.initial, isForeach ? Id.Ffront : Id.Fback))
1256 {
1257 // https://dlang.org/spec/statement.html#foreach-with-ranges
1258 // range aggregate
1259 break;
1260 }
1261 if (ad.aliasthis)
1262 {
1263 if (isRecursiveAliasThis(att, tab)) // error, circular alias this
1264 return false;
1265 aggr = resolveAliasThis(sc, aggr);
1266 continue;
1267 }
1268 return false;
1269 }
1270
1271 case Tdelegate: // https://dlang.org/spec/statement.html#foreach_over_delegates
1272 if (auto de = aggr.isDelegateExp())
1273 {
1274 sapply = de.func;
1275 }
1276 break;
1277
1278 case Terror:
1279 break;
1280
1281 default:
1282 return false;
1283 }
1284 feaggr = aggr;
1285 return true;
1286 }
1287 assert(0);
1288 }
1289
1290 /*****************************************
1291 * Given array of foreach parameters and an aggregate type,
1292 * find best opApply overload,
1293 * if any of the parameter types are missing, attempt to infer
1294 * them from the aggregate type.
1295 * Params:
1296 * fes = the foreach statement
1297 * sc = context
1298 * sapply = null or opApply or delegate, overload resolution has not been done.
1299 * Do overload resolution on sapply.
1300 * Returns:
1301 * false for errors
1302 */
1303 bool inferApplyArgTypes(ForeachStatement fes, Scope* sc, ref Dsymbol sapply)
1304 {
1305 if (!fes.parameters || !fes.parameters.length)
1306 return false;
1307 if (sapply) // prefer opApply
1308 {
1309 foreach (Parameter p; *fes.parameters)
1310 {
1311 if (p.type)
1312 {
1313 p.type = p.type.typeSemantic(fes.loc, sc);
1314 p.type = p.type.addStorageClass(p.storageClass);
1315 }
1316 }
1317
1318 // Determine ethis for sapply
1319 Expression ethis;
1320 Type tab = fes.aggr.type.toBasetype();
1321 if (tab.isTypeClass() || tab.isTypeStruct())
1322 ethis = fes.aggr;
1323 else
1324 {
1325 assert(tab.isTypeDelegate() && fes.aggr.isDelegateExp());
1326 ethis = fes.aggr.isDelegateExp().e1;
1327 }
1328
1329 /* Look for like an
1330 * int opApply(int delegate(ref Type [, ...]) dg);
1331 * overload
1332 */
1333 if (FuncDeclaration fd = sapply.isFuncDeclaration())
1334 {
1335 if (auto fdapply = findBestOpApplyMatch(ethis, fd, fes.parameters))
1336 {
1337 // Fill in any missing types on foreach parameters[]
1338 matchParamsToOpApply(fdapply.type.isTypeFunction(), fes.parameters, true);
1339 sapply = fdapply;
1340 return true;
1341 }
1342 return false;
1343 }
1344 return true; // shouldn't this be false?
1345 }
1346
1347 Parameter p = (*fes.parameters)[0];
1348 Type taggr = fes.aggr.type;
1349 assert(taggr);
1350 Type tab = taggr.toBasetype();
1351 switch (tab.ty)
1352 {
1353 case Tarray:
1354 case Tsarray:
1355 case Ttuple:
1356 if (fes.parameters.length == 2)
1357 {
1358 if (!p.type)
1359 {
1360 p.type = Type.tsize_t; // key type
1361 p.type = p.type.addStorageClass(p.storageClass);
1362 }
1363 p = (*fes.parameters)[1];
1364 }
1365 if (!p.type && !tab.isTypeTuple())
1366 {
1367 p.type = tab.nextOf(); // value type
1368 p.type = p.type.addStorageClass(p.storageClass);
1369 }
1370 break;
1371
1372 case Taarray:
1373 {
1374 TypeAArray taa = tab.isTypeAArray();
1375 if (fes.parameters.length == 2)
1376 {
1377 if (!p.type)
1378 {
1379 p.type = taa.index; // key type
1380 p.type = p.type.addStorageClass(p.storageClass);
1381 if (p.storageClass & STC.ref_) // key must not be mutated via ref
1382 p.type = p.type.addMod(MODFlags.const_);
1383 }
1384 p = (*fes.parameters)[1];
1385 }
1386 if (!p.type)
1387 {
1388 p.type = taa.next; // value type
1389 p.type = p.type.addStorageClass(p.storageClass);
1390 }
1391 break;
1392 }
1393
1394 case Tclass:
1395 case Tstruct:
1396 {
1397 AggregateDeclaration ad = isAggregate(tab);
1398 if (fes.parameters.length == 1)
1399 {
1400 if (!p.type)
1401 {
1402 /* Look for a front() or back() overload
1403 */
1404 Identifier id = (fes.op == TOK.foreach_) ? Id.Ffront : Id.Fback;
1405 Dsymbol s = ad.search(Loc.initial, id);
1406 FuncDeclaration fd = s ? s.isFuncDeclaration() : null;
1407 if (fd)
1408 {
1409 // Resolve inout qualifier of front type
1410 p.type = fd.type.nextOf();
1411 if (p.type)
1412 {
1413 p.type = p.type.substWildTo(tab.mod);
1414 p.type = p.type.addStorageClass(p.storageClass);
1415 }
1416 }
1417 else if (s && s.isTemplateDeclaration())
1418 {
1419 }
1420 else if (s && s.isDeclaration())
1421 p.type = s.isDeclaration().type;
1422 else
1423 break;
1424 }
1425 break;
1426 }
1427 break;
1428 }
1429
1430 case Tdelegate:
1431 {
1432 auto td = tab.isTypeDelegate();
1433 if (!matchParamsToOpApply(td.next.isTypeFunction(), fes.parameters, true))
1434 return false;
1435 break;
1436 }
1437
1438 default:
1439 break; // ignore error, caught later
1440 }
1441 return true;
1442 }
1443
1444 /*********************************************
1445 * Find best overload match on fstart given ethis and parameters[].
1446 * Params:
1447 * ethis = expression to use for `this`
1448 * fstart = opApply or foreach delegate
1449 * parameters = ForeachTypeList (i.e. foreach parameters)
1450 * Returns:
1451 * best match if there is one, null if error
1452 */
1453 private FuncDeclaration findBestOpApplyMatch(Expression ethis, FuncDeclaration fstart, Parameters* parameters)
1454 {
1455 MOD mod = ethis.type.mod;
1456 MATCH match = MATCH.nomatch;
1457 FuncDeclaration fd_best;
1458 FuncDeclaration fd_ambig;
1459
1460 overloadApply(fstart, (Dsymbol s)
1461 {
1462 auto f = s.isFuncDeclaration();
1463 if (!f)
1464 return 0; // continue
1465 auto tf = f.type.isTypeFunction();
1466 MATCH m = MATCH.exact;
1467 if (f.isThis())
1468 {
1469 if (!MODimplicitConv(mod, tf.mod))
1470 m = MATCH.nomatch;
1471 else if (mod != tf.mod)
1472 m = MATCH.constant;
1473 }
1474 if (!matchParamsToOpApply(tf, parameters, false))
1475 m = MATCH.nomatch;
1476 if (m > match)
1477 {
1478 fd_best = f;
1479 fd_ambig = null;
1480 match = m;
1481 }
1482 else if (m == match && m > MATCH.nomatch)
1483 {
1484 assert(fd_best);
1485 auto bestTf = fd_best.type.isTypeFunction();
1486 assert(bestTf);
1487
1488 // Found another overload with different attributes?
1489 // e.g. @system vs. @safe opApply
1490 // @@@DEPRECATED_2.112@@@
1491 // See semantic2.d Semantic2Visitor.visit(FuncDeclaration):
1492 // Remove `false` after deprecation period is over.
1493 bool ambig = tf.attributesEqual(bestTf, false);
1494
1495 // opApplies with identical attributes could still accept
1496 // different function bodies as delegate
1497 // => different parameters or attributes
1498 if (ambig)
1499 {
1500 // Fetch the delegates that receive the function body
1501 auto tfBody = tf.parameterList[0].type.isTypeDelegate().next;
1502 assert(tfBody);
1503
1504 auto bestBody = bestTf.parameterList[0].type.isTypeDelegate().next;
1505 assert(bestBody);
1506
1507 // Ignore covariant matches, as later on it can be redone
1508 // after the opApply delegate has its attributes inferred.
1509 ambig = !(tfBody.covariant(bestBody) == Covariant.yes || bestBody.covariant(tfBody) == Covariant.yes);
1510 }
1511
1512 if (ambig)
1513 fd_ambig = f; // not covariant, so ambiguous
1514 }
1515 return 0; // continue
1516 });
1517
1518 if (fd_ambig)
1519 {
1520 .error(ethis.loc, "`%s.%s` matches more than one declaration:",
1521 ethis.toChars(), fstart.ident.toChars());
1522 .errorSupplemental(fd_best.loc, "`%s`\nand:", fd_best.type.toChars());
1523 .errorSupplemental(fd_ambig.loc, "`%s`", fd_ambig.type.toChars());
1524 return null;
1525 }
1526
1527 return fd_best;
1528 }
1529
1530 /******************************
1531 * Determine if foreach parameters match opApply parameters.
1532 * Infer missing foreach parameter types from type of opApply delegate.
1533 * Params:
1534 * tf = type of opApply or delegate
1535 * parameters = foreach parameters
1536 * infer = infer missing parameter types
1537 * Returns:
1538 * true for match for this function
1539 * false for no match for this function
1540 */
1541 private bool matchParamsToOpApply(TypeFunction tf, Parameters* parameters, bool infer)
1542 {
1543 enum nomatch = false;
1544
1545 /* opApply/delegate has exactly one parameter, and that parameter
1546 * is a delegate that looks like:
1547 * int opApply(int delegate(ref Type [, ...]) dg);
1548 */
1549 if (tf.parameterList.length != 1)
1550 return nomatch;
1551
1552 /* Get the type of opApply's dg parameter
1553 */
1554 Parameter p0 = tf.parameterList[0];
1555 auto de = p0.type.isTypeDelegate();
1556 if (!de)
1557 return nomatch;
1558 TypeFunction tdg = de.next.isTypeFunction();
1559
1560 /* We now have tdg, the type of the delegate.
1561 * tdg's parameters must match that of the foreach arglist (i.e. parameters).
1562 * Fill in missing types in parameters.
1563 */
1564 const nparams = tdg.parameterList.length;
1565 if (nparams == 0 || nparams != parameters.length || tdg.parameterList.varargs != VarArg.none)
1566 return nomatch; // parameter mismatch
1567
1568 foreach (u, p; *parameters)
1569 {
1570 Parameter param = tdg.parameterList[u];
1571 if (p.type)
1572 {
1573 if (!p.type.equals(param.type))
1574 return nomatch;
1575 }
1576 else if (infer)
1577 {
1578 p.type = param.type;
1579 p.type = p.type.addStorageClass(p.storageClass);
1580 }
1581 }
1582 return true;
1583 }
1584
1585 /**
1586 * Reverse relational operator, eg >= becomes <=
1587 * Note this is not negation.
1588 * Params:
1589 * op = comparison operator to reverse
1590 * Returns:
1591 * reverse of op
1592 */
1593 private EXP reverseRelation(EXP op) pure @safe
1594 {
1595 switch (op)
1596 {
1597 case EXP.greaterOrEqual: op = EXP.lessOrEqual; break;
1598 case EXP.greaterThan: op = EXP.lessThan; break;
1599 case EXP.lessOrEqual: op = EXP.greaterOrEqual; break;
1600 case EXP.lessThan: op = EXP.greaterThan; break;
1601 default: break;
1602 }
1603 return op;
1604 }