Debian Codegraph @

gcc/d/dmd/funcsem.d

raw
1 /**
2 * Does semantic analysis for functions.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/function.html, Functions)
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/funcsem.d, _funcsem.d)
10 * Documentation: https://dlang.org/phobos/dmd_funcsem.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/funcsem.d
12 */
13
14 module dmd.funcsem;
15
16 import core.stdc.stdio;
17
18 import dmd.aggregate;
19 import dmd.arraytypes;
20 import dmd.astenums;
21 import dmd.attrib;
22 import dmd.blockexit;
23 import dmd.gluelayer;
24 import dmd.dcast;
25 import dmd.dclass;
26 import dmd.declaration;
27 import dmd.delegatize;
28 import dmd.dinterpret;
29 import dmd.dmodule;
30 import dmd.dscope;
31 import dmd.dstruct;
32 import dmd.dsymbol;
33 import dmd.dsymbolsem;
34 import dmd.dtemplate;
35 import dmd.errors;
36 import dmd.escape;
37 import dmd.expression;
38 import dmd.func;
39 import dmd.globals;
40 import dmd.hdrgen;
41 import dmd.id;
42 import dmd.identifier;
43 import dmd.importc;
44 import dmd.init;
45 import dmd.location;
46 import dmd.mtype;
47 import dmd.mustuse;
48 import dmd.objc;
49 import dmd.opover;
50 import dmd.pragmasem;
51 import dmd.root.aav;
52 import dmd.common.outbuffer;
53 import dmd.rootobject;
54 import dmd.root.filename;
55 import dmd.root.string;
56 import dmd.root.stringtable;
57 import dmd.safe;
58 import dmd.semantic2;
59 import dmd.semantic3;
60 import dmd.statement;
61 import dmd.statementsem;
62 import dmd.target;
63 import dmd.templatesem;
64 import dmd.tokens;
65 import dmd.typesem;
66 import dmd.visitor;
67 import dmd.visitor.statement_rewrite_walker;
68
69 version (IN_GCC) {}
70 else version (IN_LLVM) {}
71 else version = MARS;
72
73 /* Tweak all return statements and dtor call for nrvo_var, for correct NRVO.
74 */
75 extern (C++) final class NrvoWalker : StatementRewriteWalker
76 {
77 alias visit = typeof(super).visit;
78 public:
79 FuncDeclaration fd;
80 Scope* sc;
81
82 override void visit(ReturnStatement s)
83 {
84 // See if all returns are instead to be replaced with a goto returnLabel;
85 if (fd.returnLabel)
86 {
87 /* Rewrite:
88 * return exp;
89 * as:
90 * vresult = exp; goto Lresult;
91 */
92 auto gs = new GotoStatement(s.loc, Id.returnLabel);
93 gs.label = fd.returnLabel;
94
95 Statement s1 = gs;
96 if (s.exp)
97 s1 = new CompoundStatement(s.loc, new ExpStatement(s.loc, s.exp), gs);
98
99 replaceCurrent(s1);
100 }
101 }
102
103 override void visit(TryFinallyStatement s)
104 {
105 DtorExpStatement des;
106 if (fd.isNRVO() && s.finalbody && (des = s.finalbody.isDtorExpStatement()) !is null &&
107 fd.nrvo_var == des.var)
108 {
109 if (!(global.params.useExceptions && ClassDeclaration.throwable))
110 {
111 /* Don't need to call destructor at all, since it is nrvo
112 */
113 replaceCurrent(s._body);
114 s._body.accept(this);
115 return;
116 }
117
118 /* Normally local variable dtors are called regardless exceptions.
119 * But for nrvo_var, its dtor should be called only when exception is thrown.
120 *
121 * Rewrite:
122 * try { s.body; } finally { nrvo_var.edtor; }
123 * // equivalent with:
124 * // s.body; scope(exit) nrvo_var.edtor;
125 * as:
126 * try { s.body; } catch(Throwable __o) { nrvo_var.edtor; throw __o; }
127 * // equivalent with:
128 * // s.body; scope(failure) nrvo_var.edtor;
129 */
130 Statement sexception = new DtorExpStatement(Loc.initial, fd.nrvo_var.edtor, fd.nrvo_var);
131 Identifier id = Identifier.generateId("__o");
132
133 Statement handler = new PeelStatement(sexception);
134 if (sexception.blockExit(fd, null) & BE.fallthru)
135 {
136 auto ts = new ThrowStatement(Loc.initial, new IdentifierExp(Loc.initial, id));
137 ts.internalThrow = true;
138 handler = new CompoundStatement(Loc.initial, handler, ts);
139 }
140
141 auto catches = new Catches();
142 auto ctch = new Catch(Loc.initial, getThrowable(), id, handler);
143 ctch.internalCatch = true;
144 ctch.catchSemantic(sc); // Run semantic to resolve identifier '__o'
145 catches.push(ctch);
146
147 Statement s2 = new TryCatchStatement(Loc.initial, s._body, catches);
148 fd.hasNoEH = false;
149 replaceCurrent(s2);
150 s2.accept(this);
151 }
152 else
153 StatementRewriteWalker.visit(s);
154 }
155 }
156
157 /****************************************
158 * Only one entry point function is allowed. Print error if more than one.
159 * Params:
160 * fd = a "main" function
161 * Returns:
162 * true if haven't seen "main" before
163 */
164 extern (C++) bool onlyOneMain(FuncDeclaration fd)
165 {
166 if (auto lastMain = FuncDeclaration.lastMain)
167 {
168 const format = (target.os == Target.OS.Windows)
169 ? "only one entry point `main`, `WinMain` or `DllMain` is allowed"
170 : "only one entry point `main` is allowed";
171 error(fd.loc, format.ptr);
172 errorSupplemental(lastMain.loc, "previously found `%s` here", lastMain.toFullSignature());
173 return false;
174 }
175 FuncDeclaration.lastMain = fd;
176 return true;
177 }
178
179 /**********************************
180 * Main semantic routine for functions.
181 */
182 void funcDeclarationSemantic(Scope* sc, FuncDeclaration funcdecl)
183 {
184 version (none)
185 {
186 printf("FuncDeclaration::semantic(sc = %p, this = %p, '%s', linkage = %d)\n", sc, funcdecl, funcdecl.toPrettyChars(), sc.linkage);
187 if (funcdecl.isFuncLiteralDeclaration())
188 printf("\tFuncLiteralDeclaration()\n");
189 printf("sc.parent = %s, parent = %s\n", sc.parent.toChars(), funcdecl.parent ? funcdecl.parent.toChars() : "");
190 printf("type: %p, %s\n", funcdecl.type, funcdecl.type.toChars());
191 }
192
193 if (funcdecl.semanticRun != PASS.initial && funcdecl.isFuncLiteralDeclaration())
194 {
195 /* Member functions that have return types that are
196 * forward references can have semantic() run more than
197 * once on them.
198 * See test\interface2.d, test20
199 */
200 return;
201 }
202
203 if (funcdecl.semanticRun >= PASS.semanticdone)
204 return;
205 assert(funcdecl.semanticRun <= PASS.semantic);
206 funcdecl.semanticRun = PASS.semantic;
207
208 if (funcdecl._scope)
209 {
210 sc = funcdecl._scope;
211 funcdecl._scope = null;
212 }
213
214 if (!sc || funcdecl.errors)
215 return;
216
217 funcdecl.cppnamespace = sc.namespace;
218 funcdecl.parent = sc.parent;
219 Dsymbol parent = funcdecl.toParent();
220
221 funcdecl.foverrides.setDim(0); // reset in case semantic() is being retried for this function
222
223 funcdecl.storage_class |= sc.stc & ~STC.ref_;
224 AggregateDeclaration ad = funcdecl.isThis();
225 // Don't nest structs b/c of generated methods which should not access the outer scopes.
226 // https://issues.dlang.org/show_bug.cgi?id=16627
227 if (ad && !funcdecl.isGenerated())
228 {
229 funcdecl.storage_class |= ad.storage_class & (STC.TYPECTOR | STC.synchronized_);
230 ad.makeNested();
231 }
232 if (sc.func)
233 funcdecl.storage_class |= sc.func.storage_class & STC.disable;
234 // Remove prefix storage classes silently.
235 if ((funcdecl.storage_class & STC.TYPECTOR) && !(ad || funcdecl.isNested()))
236 funcdecl.storage_class &= ~STC.TYPECTOR;
237
238 //printf("function storage_class = x%llx, sc.stc = x%llx, %x\n", storage_class, sc.stc, Declaration.isFinal());
239
240 if (sc.traitsCompiles)
241 funcdecl.skipCodegen = true;
242
243 funcdecl._linkage = sc.linkage;
244 if (sc.inCfile && funcdecl.isFuncLiteralDeclaration())
245 funcdecl._linkage = LINK.d; // so they are uniquely mangled
246
247 if (auto fld = funcdecl.isFuncLiteralDeclaration())
248 {
249 if (fld.treq)
250 {
251 Type treq = fld.treq;
252 assert(treq.nextOf().ty == Tfunction);
253 if (treq.ty == Tdelegate)
254 fld.tok = TOK.delegate_;
255 else if (treq.isPtrToFunction())
256 fld.tok = TOK.function_;
257 else
258 assert(0);
259 funcdecl._linkage = treq.nextOf().toTypeFunction().linkage;
260 }
261 }
262
263 // evaluate pragma(inline)
264 if (auto pragmadecl = sc.inlining)
265 funcdecl.inlining = evalPragmaInline(pragmadecl.loc, sc, pragmadecl.args);
266
267 funcdecl.visibility = sc.visibility;
268 funcdecl.userAttribDecl = sc.userAttribDecl;
269 checkGNUABITag(funcdecl, funcdecl._linkage);
270 checkMustUseReserved(funcdecl);
271
272 if (!funcdecl.originalType)
273 funcdecl.originalType = funcdecl.type.syntaxCopy();
274
275 static TypeFunction getFunctionType(FuncDeclaration fd)
276 {
277 if (auto tf = fd.type.isTypeFunction())
278 return tf;
279
280 if (!fd.type.isTypeError())
281 {
282 .error(fd.loc, "%s `%s` `%s` must be a function instead of `%s`", fd.kind, fd.toPrettyChars, fd.toChars(), fd.type.toChars());
283 fd.type = Type.terror;
284 }
285 fd.errors = true;
286 return null;
287 }
288
289 if (sc.inCfile)
290 {
291 /* C11 allows a function to be declared with a typedef, D does not.
292 */
293 if (auto ti = funcdecl.type.isTypeIdentifier())
294 {
295 auto tj = ti.typeSemantic(funcdecl.loc, sc);
296 if (auto tjf = tj.isTypeFunction())
297 {
298 /* Copy the type instead of just pointing to it,
299 * as we don't merge function types
300 */
301 auto tjf2 = new TypeFunction(tjf.parameterList, tjf.next, tjf.linkage);
302 funcdecl.type = tjf2;
303 funcdecl.originalType = tjf2;
304 }
305 }
306 }
307
308 if (!getFunctionType(funcdecl))
309 return;
310
311 if (!funcdecl.type.deco)
312 {
313 sc = sc.push();
314 sc.stc |= funcdecl.storage_class & (STC.disable | STC.deprecated_); // forward to function type
315
316 TypeFunction tf = funcdecl.type.toTypeFunction();
317 if (sc.func)
318 {
319 /* If the nesting parent is pure without inference,
320 * then this function defaults to pure too.
321 *
322 * auto foo() pure {
323 * auto bar() {} // become a weak purity function
324 * class C { // nested class
325 * auto baz() {} // become a weak purity function
326 * }
327 *
328 * static auto boo() {} // typed as impure
329 * // Even though, boo cannot call any impure functions.
330 * // See also Expression::checkPurity().
331 * }
332 */
333 if (tf.purity == PURE.impure && (funcdecl.isNested() || funcdecl.isThis()))
334 {
335 FuncDeclaration fd = null;
336 for (Dsymbol p = funcdecl.toParent2(); p; p = p.toParent2())
337 {
338 if (AggregateDeclaration adx = p.isAggregateDeclaration())
339 {
340 if (adx.isNested())
341 continue;
342 break;
343 }
344 if ((fd = p.isFuncDeclaration()) !is null)
345 break;
346 }
347
348 /* If the parent's purity is inferred, then this function's purity needs
349 * to be inferred first.
350 */
351 if (fd && fd.isPureBypassingInference() >= PURE.weak && !funcdecl.isInstantiated())
352 {
353 tf.purity = PURE.fwdref; // default to pure
354 }
355 }
356 }
357
358 if (tf.isRef)
359 sc.stc |= STC.ref_;
360 if (tf.isScopeQual)
361 sc.stc |= STC.scope_;
362 if (tf.isNothrow)
363 sc.stc |= STC.nothrow_;
364 if (tf.isNogc)
365 sc.stc |= STC.nogc;
366 if (tf.isProperty)
367 sc.stc |= STC.property;
368 if (tf.purity == PURE.fwdref)
369 sc.stc |= STC.pure_;
370
371 if (tf.trust != TRUST.default_)
372 {
373 sc.stc &= ~STC.safeGroup;
374 if (tf.trust == TRUST.safe)
375 sc.stc |= STC.safe;
376 else if (tf.trust == TRUST.system)
377 sc.stc |= STC.system;
378 else if (tf.trust == TRUST.trusted)
379 sc.stc |= STC.trusted;
380 }
381
382 if (funcdecl.isCtorDeclaration())
383 {
384 tf.isCtor = true;
385 Type tret = ad.handleType();
386 assert(tret);
387 tret = tret.addStorageClass(funcdecl.storage_class | sc.stc);
388 tret = tret.addMod(funcdecl.type.mod);
389 tf.next = tret;
390 if (ad.isStructDeclaration())
391 sc.stc |= STC.ref_;
392 }
393
394 // 'return' on a non-static class member function implies 'scope' as well
395 if (ad && ad.isClassDeclaration() && (tf.isReturn || sc.stc & STC.return_) && !(sc.stc & STC.static_))
396 sc.stc |= STC.scope_;
397
398 // If 'this' has no pointers, remove 'scope' as it has no meaning
399 // Note: this is already covered by semantic of `VarDeclaration` and `TypeFunction`,
400 // but existing code relies on `hasPointers()` being called here to resolve forward references:
401 // https://github.com/dlang/dmd/pull/14232#issuecomment-1162906573
402 if (sc.stc & STC.scope_ && ad && ad.isStructDeclaration() && !ad.type.hasPointers())
403 {
404 sc.stc &= ~STC.scope_;
405 tf.isScopeQual = false;
406 if (tf.isReturnScope)
407 {
408 sc.stc &= ~(STC.return_ | STC.returnScope);
409 tf.isReturn = false;
410 tf.isReturnScope = false;
411 }
412 }
413
414 sc.linkage = funcdecl._linkage;
415
416 if (!tf.isNaked() && !(funcdecl.isThis() || funcdecl.isNested()))
417 {
418 import core.bitop : popcnt;
419 auto mods = MODtoChars(tf.mod);
420 .error(funcdecl.loc, "%s `%s` without `this` cannot be `%s`", funcdecl.kind, funcdecl.toPrettyChars, mods);
421 if (tf.next && tf.next.ty != Tvoid && popcnt(tf.mod) == 1)
422 .errorSupplemental(funcdecl.loc,
423 "did you mean to use `%s(%s)` as the return type?", mods, tf.next.toChars());
424
425 tf.mod = 0; // remove qualifiers
426 }
427
428 /* Apply const, immutable, wild and shared storage class
429 * to the function type. Do this before type semantic.
430 */
431 auto stc = funcdecl.storage_class;
432 if (funcdecl.type.isImmutable())
433 stc |= STC.immutable_;
434 if (funcdecl.type.isConst())
435 stc |= STC.const_;
436 if (funcdecl.type.isShared() || funcdecl.storage_class & STC.synchronized_)
437 stc |= STC.shared_;
438 if (funcdecl.type.isWild())
439 stc |= STC.wild;
440 funcdecl.type = funcdecl.type.addSTC(stc);
441
442 funcdecl.type = funcdecl.type.typeSemantic(funcdecl.loc, sc);
443 sc = sc.pop();
444 }
445
446 auto f = getFunctionType(funcdecl);
447 if (!f)
448 return; // funcdecl's type is not a function
449
450 {
451 // Merge back function attributes into 'originalType'.
452 // It's used for mangling, ddoc, and json output.
453 TypeFunction tfo = funcdecl.originalType.toTypeFunction();
454 tfo.mod = f.mod;
455 tfo.isScopeQual = f.isScopeQual;
456 tfo.isReturnInferred = f.isReturnInferred;
457 tfo.isScopeInferred = f.isScopeInferred;
458 tfo.isRef = f.isRef;
459 tfo.isNothrow = f.isNothrow;
460 tfo.isNogc = f.isNogc;
461 tfo.isProperty = f.isProperty;
462 tfo.purity = f.purity;
463 tfo.trust = f.trust;
464
465 funcdecl.storage_class &= ~(STC.TYPECTOR | STC.FUNCATTR);
466 }
467
468 // check pragma(crt_constructor) signature
469 if (funcdecl.isCrtCtor || funcdecl.isCrtDtor)
470 {
471 const idStr = funcdecl.isCrtCtor ? "crt_constructor" : "crt_destructor";
472 if (f.nextOf().ty != Tvoid)
473 .error(funcdecl.loc, "%s `%s` must return `void` for `pragma(%s)`", funcdecl.kind, funcdecl.toPrettyChars, idStr.ptr);
474 if (funcdecl._linkage != LINK.c && f.parameterList.length != 0)
475 .error(funcdecl.loc, "%s `%s` must be `extern(C)` for `pragma(%s)` when taking parameters", funcdecl.kind, funcdecl.toPrettyChars, idStr.ptr);
476 if (funcdecl.isThis())
477 .error(funcdecl.loc, "%s `%s` cannot be a non-static member function for `pragma(%s)`", funcdecl.kind, funcdecl.toPrettyChars, idStr.ptr);
478 }
479
480 if (funcdecl.overnext && funcdecl.isCsymbol())
481 {
482 /* C does not allow function overloading, but it does allow
483 * redeclarations of the same function. If .overnext points
484 * to a redeclaration, ok. Error if it is an overload.
485 */
486 auto fnext = funcdecl.overnext.isFuncDeclaration();
487 funcDeclarationSemantic(sc, fnext);
488 auto fn = fnext.type.isTypeFunction();
489 if (!fn || !cFuncEquivalence(f, fn))
490 {
491 .error(funcdecl.loc, "%s `%s` redeclaration with different type", funcdecl.kind, funcdecl.toPrettyChars);
492 //printf("t1: %s\n", f.toChars());
493 //printf("t2: %s\n", fn.toChars());
494 }
495 funcdecl.overnext = null; // don't overload the redeclarations
496 }
497
498 if ((funcdecl.storage_class & STC.auto_) && !f.isRef && !funcdecl.inferRetType)
499 .error(funcdecl.loc, "%s `%s` storage class `auto` has no effect if return type is not inferred", funcdecl.kind, funcdecl.toPrettyChars);
500
501 if (f.isReturn && !funcdecl.needThis() && !funcdecl.isNested())
502 {
503 /* Non-static nested functions have a hidden 'this' pointer to which
504 * the 'return' applies
505 */
506 if (sc.scopesym && sc.scopesym.isAggregateDeclaration())
507 .error(funcdecl.loc, "%s `%s` `static` member has no `this` to which `return` can apply", funcdecl.kind, funcdecl.toPrettyChars);
508 else
509 error(funcdecl.loc, "top-level function `%s` has no `this` to which `return` can apply", funcdecl.toChars());
510 }
511
512 if (funcdecl.isAbstract() && !funcdecl.isVirtual())
513 {
514 const(char)* sfunc;
515 if (funcdecl.isStatic())
516 sfunc = "static";
517 else if (funcdecl.visibility.kind == Visibility.Kind.private_ || funcdecl.visibility.kind == Visibility.Kind.package_)
518 sfunc = visibilityToChars(funcdecl.visibility.kind);
519 else
520 sfunc = "final";
521 .error(funcdecl.loc, "%s `%s` `%s` functions cannot be `abstract`", funcdecl.kind, funcdecl.toPrettyChars, sfunc);
522 }
523
524 if (funcdecl.isOverride() && !funcdecl.isVirtual() && !funcdecl.isFuncLiteralDeclaration())
525 {
526 Visibility.Kind kind = funcdecl.visible().kind;
527 if ((kind == Visibility.Kind.private_ || kind == Visibility.Kind.package_) && funcdecl.isMember())
528 .error(funcdecl.loc, "%s `%s` `%s` method is not virtual and cannot override", funcdecl.kind, funcdecl.toPrettyChars, visibilityToChars(kind));
529 else
530 .error(funcdecl.loc, "%s `%s` cannot override a non-virtual function", funcdecl.kind, funcdecl.toPrettyChars);
531 }
532
533 if (funcdecl.isAbstract() && funcdecl.isFinalFunc())
534 .error(funcdecl.loc, "%s `%s` cannot be both `final` and `abstract`", funcdecl.kind, funcdecl.toPrettyChars);
535
536 if (funcdecl.printf || funcdecl.scanf)
537 {
538 checkPrintfScanfSignature(funcdecl, f, sc);
539 }
540
541 if (auto id = parent.isInterfaceDeclaration())
542 {
543 funcdecl.storage_class |= STC.abstract_;
544 if (funcdecl.isCtorDeclaration() || funcdecl.isPostBlitDeclaration() || funcdecl.isDtorDeclaration() || funcdecl.isInvariantDeclaration() || funcdecl.isNewDeclaration() || funcdecl.isDelete())
545 .error(funcdecl.loc, "%s `%s` constructors, destructors, postblits, invariants, new and delete functions are not allowed in interface `%s`", funcdecl.kind, funcdecl.toPrettyChars, id.toChars());
546 if (funcdecl.fbody && funcdecl.isVirtual())
547 .error(funcdecl.loc, "%s `%s` function body only allowed in `final` functions in interface `%s`", funcdecl.kind, funcdecl.toPrettyChars, id.toChars());
548 }
549
550 if (UnionDeclaration ud = parent.isUnionDeclaration())
551 {
552 if (funcdecl.isPostBlitDeclaration() || funcdecl.isDtorDeclaration() || funcdecl.isInvariantDeclaration())
553 .error(funcdecl.loc, "%s `%s` destructors, postblits and invariants are not allowed in union `%s`", funcdecl.kind, funcdecl.toPrettyChars, ud.toChars());
554 }
555
556 if (StructDeclaration sd = parent.isStructDeclaration())
557 {
558 if (funcdecl.isCtorDeclaration())
559 {
560 goto Ldone;
561 }
562 }
563
564 if (ClassDeclaration cd = parent.isClassDeclaration())
565 {
566 parent = cd = objc.getParent(funcdecl, cd);
567
568 if (funcdecl.isCtorDeclaration())
569 {
570 goto Ldone;
571 }
572
573 if (funcdecl.storage_class & STC.abstract_)
574 cd.isabstract = ThreeState.yes;
575
576 // if static function, do not put in vtbl[]
577 if (!funcdecl.isVirtual())
578 {
579 //printf("\tnot virtual\n");
580 goto Ldone;
581 }
582 // Suppress further errors if the return type is an error
583 if (funcdecl.type.nextOf() == Type.terror)
584 goto Ldone;
585
586 bool may_override = false;
587 for (size_t i = 0; i < cd.baseclasses.length; i++)
588 {
589 BaseClass* b = (*cd.baseclasses)[i];
590 ClassDeclaration cbd = b.type.toBasetype().isClassHandle();
591 if (!cbd)
592 continue;
593 for (size_t j = 0; j < cbd.vtbl.length; j++)
594 {
595 FuncDeclaration f2 = cbd.vtbl[j].isFuncDeclaration();
596 if (!f2 || f2.ident != funcdecl.ident)
597 continue;
598 if (cbd.parent && cbd.parent.isTemplateInstance())
599 {
600 if (!functionSemantic(f2))
601 goto Ldone;
602 }
603 may_override = true;
604 }
605 }
606 if (may_override && funcdecl.type.nextOf() is null)
607 {
608 /* If same name function exists in base class but 'this' is auto return,
609 * cannot find index of base class's vtbl[] to override.
610 */
611 .error(funcdecl.loc, "%s `%s` return type inference is not supported if may override base class function", funcdecl.kind, funcdecl.toPrettyChars);
612 }
613
614 /* Find index of existing function in base class's vtbl[] to override
615 * (the index will be the same as in cd's current vtbl[])
616 */
617 int vi = cd.baseClass ? findVtblIndex(funcdecl, cd.baseClass.vtbl[]) : -1;
618
619 bool doesoverride = false;
620 switch (vi)
621 {
622 case -1:
623 Lintro:
624 /* Didn't find one, so
625 * This is an 'introducing' function which gets a new
626 * slot in the vtbl[].
627 */
628
629 // Verify this doesn't override previous final function
630 if (cd.baseClass)
631 {
632 Dsymbol s = cd.baseClass.search(funcdecl.loc, funcdecl.ident);
633 if (s)
634 {
635 if (auto f2 = s.isFuncDeclaration())
636 {
637 f2 = f2.overloadExactMatch(funcdecl.type);
638 if (f2 && f2.isFinalFunc() && f2.visible().kind != Visibility.Kind.private_)
639 .error(funcdecl.loc, "%s `%s` cannot override `final` function `%s`", funcdecl.kind, funcdecl.toPrettyChars, f2.toPrettyChars());
640 }
641 }
642 }
643
644 /* These quirky conditions mimic what happens when virtual
645 inheritance is implemented by producing a virtual base table
646 with offsets to each of the virtual bases.
647 */
648 if (target.cpp.splitVBasetable && cd.classKind == ClassKind.cpp &&
649 cd.baseClass && cd.baseClass.vtbl.length)
650 {
651 /* if overriding an interface function, then this is not
652 * introducing and don't put it in the class vtbl[]
653 */
654 funcdecl.interfaceVirtual = overrideInterface(funcdecl);
655 if (funcdecl.interfaceVirtual)
656 {
657 //printf("\tinterface function %s\n", toChars());
658 cd.vtblFinal.push(funcdecl);
659 goto Linterfaces;
660 }
661 }
662
663 if (funcdecl.isFinalFunc())
664 {
665 // Don't check here, as it may override an interface function
666 //if (isOverride())
667 // error("is marked as override, but does not override any function");
668 cd.vtblFinal.push(funcdecl);
669 }
670 else
671 {
672 //printf("\tintroducing function %s\n", funcdecl.toChars());
673 funcdecl.isIntroducing = true;
674 if (cd.classKind == ClassKind.cpp && target.cpp.reverseOverloads)
675 {
676 /* Overloaded functions with same name are grouped and in reverse order.
677 * Search for first function of overload group, and insert
678 * funcdecl into vtbl[] immediately before it.
679 */
680 funcdecl.vtblIndex = cast(int)cd.vtbl.length;
681 bool found;
682 foreach (const i, s; cd.vtbl)
683 {
684 if (found)
685 // the rest get shifted forward
686 ++s.isFuncDeclaration().vtblIndex;
687 else if (s.ident == funcdecl.ident && s.parent == parent)
688 {
689 // found first function of overload group
690 funcdecl.vtblIndex = cast(int)i;
691 found = true;
692 ++s.isFuncDeclaration().vtblIndex;
693 }
694 }
695 cd.vtbl.insert(funcdecl.vtblIndex, funcdecl);
696
697 debug foreach (const i, s; cd.vtbl)
698 {
699 // a C++ dtor gets its vtblIndex later (and might even be added twice to the vtbl),
700 // e.g. when compiling druntime with a debug compiler, namely with core.stdcpp.exception.
701 if (auto fd = s.isFuncDeclaration())
702 assert(fd.vtblIndex == i ||
703 (cd.classKind == ClassKind.cpp && fd.isDtorDeclaration) ||
704 funcdecl.parent.isInterfaceDeclaration); // interface functions can be in multiple vtbls
705 }
706 }
707 else
708 {
709 // Append to end of vtbl[]
710 vi = cast(int)cd.vtbl.length;
711 cd.vtbl.push(funcdecl);
712 funcdecl.vtblIndex = vi;
713 }
714 }
715 break;
716
717 case -2:
718 // can't determine because of forward references
719 funcdecl.errors = true;
720 return;
721
722 default:
723 {
724 if (vi >= cd.vtbl.length)
725 {
726 /* the derived class cd doesn't have its vtbl[] allocated yet.
727 * https://issues.dlang.org/show_bug.cgi?id=21008
728 */
729 .error(funcdecl.loc, "%s `%s` circular reference to class `%s`", funcdecl.kind, funcdecl.toPrettyChars, cd.toChars());
730 funcdecl.errors = true;
731 return;
732 }
733 FuncDeclaration fdv = cd.baseClass.vtbl[vi].isFuncDeclaration();
734 FuncDeclaration fdc = cd.vtbl[vi].isFuncDeclaration();
735 // This function is covariant with fdv
736
737 if (fdc == funcdecl)
738 {
739 doesoverride = true;
740 break;
741 }
742
743 auto vtf = getFunctionType(fdv);
744 if (vtf.trust > TRUST.system && f.trust == TRUST.system)
745 .error(funcdecl.loc, "%s `%s` cannot override `@safe` method `%s` with a `@system` attribute", funcdecl.kind, funcdecl.toPrettyChars,
746 fdv.toPrettyChars);
747
748 if (fdc.toParent() == parent)
749 {
750 //printf("vi = %d,\tthis = %p %s %s @ [%s]\n\tfdc = %p %s %s @ [%s]\n\tfdv = %p %s %s @ [%s]\n",
751 // vi, this, this.toChars(), this.type.toChars(), this.loc.toChars(),
752 // fdc, fdc .toChars(), fdc .type.toChars(), fdc .loc.toChars(),
753 // fdv, fdv .toChars(), fdv .type.toChars(), fdv .loc.toChars());
754
755 // fdc overrides fdv exactly, then this introduces new function.
756 if (fdc.type.mod == fdv.type.mod && funcdecl.type.mod != fdv.type.mod)
757 goto Lintro;
758 }
759
760 if (fdv.isDeprecated && !funcdecl.isDeprecated)
761 deprecation(funcdecl.loc, "`%s` is overriding the deprecated method `%s`",
762 funcdecl.toPrettyChars, fdv.toPrettyChars);
763
764 // This function overrides fdv
765 if (fdv.isFinalFunc())
766 .error(funcdecl.loc, "%s `%s` cannot override `final` function `%s`", funcdecl.kind, funcdecl.toPrettyChars, fdv.toPrettyChars());
767
768 if (!funcdecl.isOverride())
769 {
770 if (fdv.isFuture())
771 {
772 deprecation(funcdecl.loc, "method `%s` implicitly overrides `@__future` base class method; rename the former",
773 funcdecl.toPrettyChars());
774 deprecationSupplemental(fdv.loc, "base method `%s` defined here",
775 fdv.toPrettyChars());
776 // Treat 'this' as an introducing function, giving it a separate hierarchy in the vtbl[]
777 goto Lintro;
778 }
779 else
780 {
781 // https://issues.dlang.org/show_bug.cgi?id=17349
782 error(funcdecl.loc, "cannot implicitly override base class method `%s` with `%s`; add `override` attribute",
783 fdv.toPrettyChars(), funcdecl.toPrettyChars());
784 }
785 }
786 doesoverride = true;
787 if (fdc.toParent() == parent)
788 {
789 // If both are mixins, or both are not, then error.
790 // If either is not, the one that is not overrides the other.
791 bool thismixin = funcdecl.parent.isClassDeclaration() !is null;
792 bool fdcmixin = fdc.parent.isClassDeclaration() !is null;
793 if (thismixin == fdcmixin)
794 {
795 .error(funcdecl.loc, "%s `%s` multiple overrides of same function", funcdecl.kind, funcdecl.toPrettyChars);
796 }
797 /*
798 * https://issues.dlang.org/show_bug.cgi?id=711
799 *
800 * If an overriding method is introduced through a mixin,
801 * we need to update the vtbl so that both methods are
802 * present.
803 */
804 else if (thismixin)
805 {
806 /* if the mixin introduced the overriding method, then reintroduce it
807 * in the vtbl. The initial entry for the mixined method
808 * will be updated at the end of the enclosing `if` block
809 * to point to the current (non-mixined) function.
810 */
811 auto vitmp = cast(int)cd.vtbl.length;
812 cd.vtbl.push(fdc);
813 fdc.vtblIndex = vitmp;
814 }
815 else if (fdcmixin)
816 {
817 /* if the current overriding function is coming from a
818 * mixined block, then push the current function in the
819 * vtbl, but keep the previous (non-mixined) function as
820 * the overriding one.
821 */
822 auto vitmp = cast(int)cd.vtbl.length;
823 cd.vtbl.push(funcdecl);
824 funcdecl.vtblIndex = vitmp;
825 break;
826 }
827 else // fdc overrides fdv
828 {
829 // this doesn't override any function
830 break;
831 }
832 }
833 cd.vtbl[vi] = funcdecl;
834 funcdecl.vtblIndex = vi;
835
836 /* Remember which functions this overrides
837 */
838 funcdecl.foverrides.push(fdv);
839
840 /* This works by whenever this function is called,
841 * it actually returns tintro, which gets dynamically
842 * cast to type. But we know that tintro is a base
843 * of type, so we could optimize it by not doing a
844 * dynamic cast, but just subtracting the isBaseOf()
845 * offset if the value is != null.
846 */
847
848 if (fdv.tintro)
849 funcdecl.tintro = fdv.tintro;
850 else if (!funcdecl.type.equals(fdv.type))
851 {
852 auto tnext = funcdecl.type.nextOf();
853 if (auto handle = tnext.isClassHandle())
854 {
855 if (handle.semanticRun < PASS.semanticdone && !handle.isBaseInfoComplete())
856 handle.dsymbolSemantic(null);
857 }
858 /* Only need to have a tintro if the vptr
859 * offsets differ
860 */
861 int offset;
862 if (fdv.type.nextOf().isBaseOf(tnext, &offset))
863 {
864 funcdecl.tintro = fdv.type;
865 }
866 }
867 break;
868 }
869 }
870
871 /* Go through all the interface bases.
872 * If this function is covariant with any members of those interface
873 * functions, set the tintro.
874 */
875 Linterfaces:
876 bool foundVtblMatch = false;
877
878 for (ClassDeclaration bcd = cd; !foundVtblMatch && bcd; bcd = bcd.baseClass)
879 {
880 foreach (b; bcd.interfaces)
881 {
882 vi = findVtblIndex(funcdecl, b.sym.vtbl[]);
883 switch (vi)
884 {
885 case -1:
886 break;
887
888 case -2:
889 // can't determine because of forward references
890 funcdecl.errors = true;
891 return;
892
893 default:
894 {
895 auto fdv = cast(FuncDeclaration)b.sym.vtbl[vi];
896 Type ti = null;
897
898 foundVtblMatch = true;
899
900 /* Remember which functions this overrides
901 */
902 funcdecl.foverrides.push(fdv);
903
904 if (fdv.tintro)
905 ti = fdv.tintro;
906 else if (!funcdecl.type.equals(fdv.type))
907 {
908 /* Only need to have a tintro if the vptr
909 * offsets differ
910 */
911 int offset;
912 if (fdv.type.nextOf().isBaseOf(funcdecl.type.nextOf(), &offset))
913 {
914 ti = fdv.type;
915 }
916 }
917 if (ti)
918 {
919 if (funcdecl.tintro)
920 {
921 if (!funcdecl.tintro.nextOf().equals(ti.nextOf()) && !funcdecl.tintro.nextOf().isBaseOf(ti.nextOf(), null) && !ti.nextOf().isBaseOf(funcdecl.tintro.nextOf(), null))
922 {
923 .error(funcdecl.loc, "%s `%s` incompatible covariant types `%s` and `%s`", funcdecl.kind, funcdecl.toPrettyChars, funcdecl.tintro.toChars(), ti.toChars());
924 }
925 }
926 else
927 {
928 funcdecl.tintro = ti;
929 }
930 }
931 }
932 }
933 }
934 }
935 if (foundVtblMatch)
936 {
937 goto L2;
938 }
939
940 if (!doesoverride && funcdecl.isOverride() && (funcdecl.type.nextOf() || !may_override))
941 {
942 BaseClass* bc = null;
943 Dsymbol s = null;
944 for (size_t i = 0; i < cd.baseclasses.length; i++)
945 {
946 bc = (*cd.baseclasses)[i];
947 s = bc.sym.search_correct(funcdecl.ident);
948 if (s)
949 break;
950 }
951
952 if (s)
953 {
954 HdrGenState hgs;
955 OutBuffer buf;
956
957 auto fd = s.isFuncDeclaration();
958 functionToBufferFull(cast(TypeFunction)(funcdecl.type), buf,
959 new Identifier(funcdecl.toPrettyChars()), hgs, null);
960 const(char)* funcdeclToChars = buf.peekChars();
961
962 if (fd)
963 {
964 OutBuffer buf1;
965
966 if (fd.ident == funcdecl.ident)
967 hgs.fullQual = true;
968
969 // https://issues.dlang.org/show_bug.cgi?id=23745
970 // If the potentially overridden function contains errors,
971 // inform the user to fix that one first
972 if (fd.errors)
973 {
974 error(funcdecl.loc, "function `%s` does not override any function, did you mean to override `%s`?",
975 funcdecl.toChars(), fd.toPrettyChars());
976 errorSupplemental(fd.loc, "Function `%s` contains errors in its declaration, therefore it cannot be correctly overridden",
977 fd.toPrettyChars());
978 }
979 else
980 {
981 functionToBufferFull(cast(TypeFunction)(fd.type), buf1,
982 new Identifier(fd.toPrettyChars()), hgs, null);
983
984 error(funcdecl.loc, "function `%s` does not override any function, did you mean to override `%s`?",
985 funcdeclToChars, buf1.peekChars());
986 }
987 }
988 else
989 {
990 error(funcdecl.loc, "function `%s` does not override any function, did you mean to override %s `%s`?",
991 funcdeclToChars, s.kind, s.toPrettyChars());
992 errorSupplemental(funcdecl.loc, "Functions are the only declarations that may be overridden");
993 }
994 }
995 else
996 .error(funcdecl.loc, "%s `%s` does not override any function", funcdecl.kind, funcdecl.toPrettyChars);
997 }
998
999 L2:
1000 objc.setSelector(funcdecl, sc);
1001 objc.checkLinkage(funcdecl);
1002 objc.addToClassMethodList(funcdecl, cd);
1003 objc.setAsOptional(funcdecl, sc);
1004
1005 /* Go through all the interface bases.
1006 * Disallow overriding any final functions in the interface(s).
1007 */
1008 foreach (b; cd.interfaces)
1009 {
1010 if (b.sym)
1011 {
1012 if (auto s = search_function(b.sym, funcdecl.ident))
1013 {
1014 if (auto f2 = s.isFuncDeclaration())
1015 {
1016 f2 = f2.overloadExactMatch(funcdecl.type);
1017 if (f2 && f2.isFinalFunc() && f2.visible().kind != Visibility.Kind.private_)
1018 .error(funcdecl.loc, "%s `%s` cannot override `final` function `%s.%s`", funcdecl.kind, funcdecl.toPrettyChars, b.sym.toChars(), f2.toPrettyChars());
1019 }
1020 }
1021 }
1022 }
1023
1024 if (funcdecl.isOverride)
1025 {
1026 if (funcdecl.storage_class & STC.disable)
1027 deprecation(funcdecl.loc,
1028 "`%s` cannot be annotated with `@disable` because it is overriding a function in the base class",
1029 funcdecl.toPrettyChars);
1030
1031 if (funcdecl.isDeprecated && !(funcdecl.foverrides.length && funcdecl.foverrides[0].isDeprecated))
1032 deprecation(funcdecl.loc,
1033 "`%s` cannot be marked as `deprecated` because it is overriding a function in the base class",
1034 funcdecl.toPrettyChars);
1035 }
1036
1037 }
1038 else if (funcdecl.isOverride() && !parent.isTemplateInstance())
1039 .error(funcdecl.loc, "%s `%s` `override` only applies to class member functions", funcdecl.kind, funcdecl.toPrettyChars);
1040
1041 if (auto ti = parent.isTemplateInstance)
1042 {
1043 objc.setSelector(funcdecl, sc);
1044 objc.setAsOptional(funcdecl, sc);
1045 }
1046
1047 objc.validateSelector(funcdecl);
1048 objc.validateOptional(funcdecl);
1049 // Reflect this.type to f because it could be changed by findVtblIndex
1050 f = funcdecl.type.toTypeFunction();
1051
1052 Ldone:
1053 if (!funcdecl.fbody && !funcdecl.allowsContractWithoutBody())
1054 .error(funcdecl.loc, "%s `%s` `in` and `out` contracts can only appear without a body when they are virtual interface functions or abstract", funcdecl.kind, funcdecl.toPrettyChars);
1055
1056 /* Do not allow template instances to add virtual functions
1057 * to a class.
1058 */
1059 if (funcdecl.isVirtual())
1060 {
1061 if (auto ti = parent.isTemplateInstance())
1062 {
1063 // Take care of nested templates
1064 while (1)
1065 {
1066 TemplateInstance ti2 = ti.tempdecl.parent.isTemplateInstance();
1067 if (!ti2)
1068 break;
1069 ti = ti2;
1070 }
1071
1072 // If it's a member template
1073 if (ClassDeclaration cd = ti.tempdecl.isClassMember())
1074 {
1075 .error(funcdecl.loc, "%s `%s` cannot use template to add virtual function to class `%s`", funcdecl.kind, funcdecl.toPrettyChars, cd.toChars());
1076 }
1077 }
1078 }
1079
1080 funcdecl.checkMain(); // Check main() parameters and return type
1081
1082 /* Purity and safety can be inferred for some functions by examining
1083 * the function body.
1084 */
1085 if (funcdecl.canInferAttributes(sc))
1086 funcdecl.initInferAttributes();
1087
1088 funcdecl.semanticRun = PASS.semanticdone;
1089
1090 /* Save scope for possible later use (if we need the
1091 * function internals)
1092 */
1093 funcdecl._scope = sc.copy();
1094 funcdecl._scope.setNoFree();
1095
1096 __gshared bool printedMain = false; // semantic might run more than once
1097 if (global.params.v.verbose && !printedMain)
1098 {
1099 const(char)* type = funcdecl.isMain() ? "main" : funcdecl.isWinMain() ? "winmain" : funcdecl.isDllMain() ? "dllmain" : cast(const(char)*)null;
1100 Module mod = sc._module;
1101
1102 if (type && mod)
1103 {
1104 printedMain = true;
1105 auto name = mod.srcfile.toChars();
1106 auto path = FileName.searchPath(global.importPaths, name, true);
1107 message("entry %-10s\t%s", type, path ? path : name);
1108 }
1109 }
1110
1111 if (funcdecl.fbody && sc._module.isRoot() &&
1112 (funcdecl.isMain() || funcdecl.isWinMain() || funcdecl.isDllMain() || funcdecl.isCMain()))
1113 global.hasMainFunction = true;
1114
1115 if (funcdecl.fbody && funcdecl.isMain() && sc._module.isRoot())
1116 {
1117 // check if `_d_cmain` is defined
1118 bool cmainTemplateExists()
1119 {
1120 Dsymbol pscopesym;
1121 auto rootSymbol = sc.search(funcdecl.loc, Id.empty, pscopesym);
1122 if (auto moduleSymbol = rootSymbol.search(funcdecl.loc, Id.object))
1123 if (moduleSymbol.search(funcdecl.loc, Id.CMain))
1124 return true;
1125
1126 return false;
1127 }
1128
1129 // Only mixin `_d_cmain` if it is defined
1130 if (cmainTemplateExists())
1131 {
1132 // add `mixin _d_cmain!();` to the declaring module
1133 auto tqual = new TypeIdentifier(funcdecl.loc, Id.CMain);
1134 auto tm = new TemplateMixin(funcdecl.loc, null, tqual, null);
1135 sc._module.members.push(tm);
1136 }
1137 }
1138
1139 assert(funcdecl.type.ty != Terror || funcdecl.errors);
1140
1141 // semantic for parameters' UDAs
1142 foreach (i, param; f.parameterList)
1143 {
1144 if (param && param.userAttribDecl)
1145 param.userAttribDecl.dsymbolSemantic(sc);
1146 }
1147 }
1148
1149 /*****************************************
1150 * Initialize for inferring the attributes of this function.
1151 */
1152 private void initInferAttributes(FuncDeclaration fd)
1153 {
1154 //printf("initInferAttributes() for %s (%s)\n", toPrettyChars(), ident.toChars());
1155 TypeFunction tf = fd.type.toTypeFunction();
1156 if (tf.purity == PURE.impure) // purity not specified
1157 fd.purityInprocess = true;
1158
1159 if (tf.trust == TRUST.default_)
1160 fd.safetyInprocess = true;
1161
1162 if (!tf.isNothrow)
1163 fd.nothrowInprocess = true;
1164
1165 if (!tf.isNogc)
1166 fd.nogcInprocess = true;
1167
1168 // Initialize for inferring STC.scope_
1169 fd.scopeInprocess = true;
1170 }
1171
1172 /****************************************************
1173 * Resolve forward reference of function signature -
1174 * parameter types, return type, and attributes.
1175 * Params:
1176 * fd = function declaration
1177 * Returns:
1178 * false if any errors exist in the signature.
1179 */
1180 public
1181 bool functionSemantic(FuncDeclaration fd)
1182 {
1183 //printf("functionSemantic() %p %s\n", this, toChars());
1184 if (!fd._scope)
1185 return !fd.errors;
1186
1187 fd.cppnamespace = fd._scope.namespace;
1188
1189 if (!fd.originalType) // semantic not yet run
1190 {
1191 TemplateInstance spec = fd.isSpeculative();
1192 const olderrs = global.errors;
1193 const oldgag = global.gag;
1194 if (global.gag && !spec)
1195 global.gag = 0;
1196 dsymbolSemantic(fd, fd._scope);
1197 global.gag = oldgag;
1198 if (spec && global.errors != olderrs)
1199 spec.errors = (global.errors - olderrs != 0);
1200 if (olderrs != global.errors) // if errors compiling this function
1201 return false;
1202 }
1203
1204 // if inferring return type, sematic3 needs to be run
1205 // - When the function body contains any errors, we cannot assume
1206 // the inferred return type is valid.
1207 // So, the body errors should become the function signature error.
1208 if (fd.inferRetType && fd.type && !fd.type.nextOf())
1209 return fd.functionSemantic3();
1210
1211 TemplateInstance ti;
1212 if (fd.isInstantiated() && !fd.isVirtualMethod() &&
1213 ((ti = fd.parent.isTemplateInstance()) is null || ti.isTemplateMixin() || ti.tempdecl.ident == fd.ident))
1214 {
1215 AggregateDeclaration ad = fd.isMemberLocal();
1216 if (ad && ad.sizeok != Sizeok.done)
1217 {
1218 /* Currently dmd cannot resolve forward references per methods,
1219 * then setting SIZOKfwd is too conservative and would break existing code.
1220 * So, just stop method attributes inference until ad.dsymbolSemantic() done.
1221 */
1222 //ad.sizeok = Sizeok.fwd;
1223 }
1224 else
1225 return fd.functionSemantic3() || !fd.errors;
1226 }
1227
1228 if (fd.storage_class & STC.inference)
1229 return fd.functionSemantic3() || !fd.errors;
1230
1231 return !fd.errors;
1232 }
1233
1234 /****************************************************
1235 * Resolve forward reference of function body.
1236 * Returns false if any errors exist in the body.
1237 */
1238 public
1239 bool functionSemantic3(FuncDeclaration fd)
1240 {
1241 if (fd.semanticRun < PASS.semantic3 && fd._scope)
1242 {
1243 /* Forward reference - we need to run semantic3 on this function.
1244 * If errors are gagged, and it's not part of a template instance,
1245 * we need to temporarily ungag errors.
1246 */
1247 TemplateInstance spec = fd.isSpeculative();
1248 const olderrs = global.errors;
1249 const oldgag = global.gag;
1250 if (global.gag && !spec)
1251 global.gag = 0;
1252 semantic3(fd, fd._scope);
1253 global.gag = oldgag;
1254
1255 // If it is a speculatively-instantiated template, and errors occur,
1256 // we need to mark the template as having errors.
1257 if (spec && global.errors != olderrs)
1258 spec.errors = (global.errors - olderrs != 0);
1259 if (olderrs != global.errors) // if errors compiling this function
1260 return false;
1261 }
1262
1263 return !fd.errors && !fd.hasSemantic3Errors();
1264 }
1265
1266 // called from semantic3
1267 /**
1268 * Creates and returns the hidden parameters for this function declaration.
1269 *
1270 * Hidden parameters include the `this` parameter of a class, struct or
1271 * nested function and the selector parameter for Objective-C methods.
1272 */
1273 extern (D) void declareThis(FuncDeclaration fd, Scope* sc)
1274 {
1275 const bool dualCtx = (fd.toParent2() != fd.toParentLocal());
1276 if (dualCtx)
1277 fd.hasDualContext = true;
1278
1279 auto ad = fd.isThis();
1280 if (!dualCtx && !ad && !fd.isNested())
1281 {
1282 fd.vthis = null;
1283 fd.objc.selectorParameter = null;
1284 return;
1285 }
1286
1287 Type addModStc(Type t)
1288 {
1289 return t.addMod(fd.type.mod).addStorageClass(fd.storage_class);
1290 }
1291
1292 if (dualCtx || fd.isNested())
1293 {
1294 /* The 'this' for a nested function is the link to the
1295 * enclosing function's stack frame.
1296 * Note that nested functions and member functions are disjoint.
1297 */
1298 Type tthis = addModStc(dualCtx ?
1299 Type.tvoidptr.sarrayOf(2).pointerTo() :
1300 Type.tvoid.pointerTo());
1301 fd.vthis = new VarDeclaration(fd.loc, tthis, dualCtx ? Id.this2 : Id.capture, null);
1302 fd.vthis.storage_class |= STC.parameter | STC.nodtor;
1303 }
1304 else if (ad)
1305 {
1306 Type thandle = addModStc(ad.handleType());
1307 fd.vthis = new ThisDeclaration(fd.loc, thandle);
1308 fd.vthis.storage_class |= STC.parameter;
1309 if (thandle.ty == Tstruct)
1310 {
1311 fd.vthis.storage_class |= STC.ref_;
1312 }
1313 }
1314
1315 if (auto tf = fd.type.isTypeFunction())
1316 {
1317 if (tf.isReturn)
1318 fd.vthis.storage_class |= STC.return_;
1319 if (tf.isScopeQual)
1320 fd.vthis.storage_class |= STC.scope_;
1321 if (tf.isReturnScope)
1322 fd.vthis.storage_class |= STC.returnScope;
1323 }
1324
1325 fd.vthis.dsymbolSemantic(sc);
1326 if (!sc.insert(fd.vthis))
1327 assert(0);
1328 fd.vthis.parent = fd;
1329 if (ad)
1330 fd.objc.selectorParameter = .objc.createSelectorParameter(fd, sc);
1331 }
1332
1333 /****************************************************
1334 * Check that this function type is properly resolved.
1335 * If not, report "forward reference error" and return true.
1336 */
1337 extern (D) bool checkForwardRef(FuncDeclaration fd, Loc loc)
1338 {
1339 if (!functionSemantic(fd))
1340 return true;
1341
1342 /* No deco means the functionSemantic() call could not resolve
1343 * forward referenes in the type of this function.
1344 */
1345 if (!fd.type.deco)
1346 {
1347 bool inSemantic3 = (fd.inferRetType && fd.semanticRun >= PASS.semantic3);
1348 .error(loc, "forward reference to %s`%s`",
1349 (inSemantic3 ? "inferred return type of function " : "").ptr,
1350 fd.toChars());
1351 return true;
1352 }
1353 return false;
1354 }
1355
1356 /*************************************************
1357 * Find index of function in vtbl[0..length] that
1358 * this function overrides.
1359 * Prefer an exact match to a covariant one.
1360 * Params:
1361 * fd = function
1362 * vtbl = vtable to use
1363 * Returns:
1364 * -1 didn't find one
1365 * -2 can't determine because of forward references
1366 */
1367 int findVtblIndex(FuncDeclaration fd, Dsymbol[] vtbl)
1368 {
1369 //printf("findVtblIndex() %s\n", toChars());
1370 import dmd.typesem : covariant;
1371
1372 FuncDeclaration mismatch = null;
1373 STC mismatchstc = STC.none;
1374 int mismatchvi = -1;
1375 int exactvi = -1;
1376 int bestvi = -1;
1377 for (int vi = 0; vi < cast(int)vtbl.length; vi++)
1378 {
1379 FuncDeclaration fdv = vtbl[vi].isFuncDeclaration();
1380 if (!fdv || fdv.ident != fd.ident)
1381 continue;
1382
1383 if (fd.type.equals(fdv.type)) // if exact match
1384 {
1385 if (fdv.parent.isClassDeclaration())
1386 {
1387 if (fdv.isFuture())
1388 {
1389 bestvi = vi;
1390 continue; // keep looking
1391 }
1392 return vi; // no need to look further
1393 }
1394
1395 if (exactvi >= 0)
1396 {
1397 .error(fd.loc, "%s `%s` cannot determine overridden function", fd.kind, fd.toPrettyChars);
1398 return exactvi;
1399 }
1400 exactvi = vi;
1401 bestvi = vi;
1402 continue;
1403 }
1404
1405 STC stc = STC.none;
1406 const cov = fd.type.covariant(fdv.type, &stc);
1407 //printf("\tbaseclass cov = %d\n", cov);
1408 final switch (cov)
1409 {
1410 case Covariant.distinct:
1411 // types are distinct
1412 break;
1413
1414 case Covariant.yes:
1415 bestvi = vi; // covariant, but not identical
1416 break;
1417 // keep looking for an exact match
1418
1419 case Covariant.no:
1420 mismatchvi = vi;
1421 mismatchstc = stc;
1422 mismatch = fdv; // overrides, but is not covariant
1423 break;
1424 // keep looking for an exact match
1425
1426 case Covariant.fwdref:
1427 return -2; // forward references
1428 }
1429 }
1430 if (fd._linkage == LINK.cpp && bestvi != -1)
1431 {
1432 STC stc = STC.none;
1433 FuncDeclaration fdv = vtbl[bestvi].isFuncDeclaration();
1434 assert(fdv && fdv.ident == fd.ident);
1435 if (fd.type.covariant(fdv.type, &stc, /*cppCovariant=*/true) == Covariant.no)
1436 {
1437 /* https://issues.dlang.org/show_bug.cgi?id=22351
1438 * Under D rules, `type` and `fdv.type` are covariant, but under C++ rules, they are not.
1439 * For now, continue to allow D covariant rules to apply when `override` has been used,
1440 * but issue a deprecation warning that this behaviour will change in the future.
1441 * Otherwise, follow the C++ covariant rules, which will create a new vtable entry.
1442 */
1443 if (fd.isOverride())
1444 {
1445 /* @@@DEPRECATED_2.110@@@
1446 * After deprecation period has ended, be sure to remove this entire `LINK.cpp` branch,
1447 * but also the `cppCovariant` parameter from Type.covariant, and update the function
1448 * so that both `LINK.cpp` covariant conditions within are always checked.
1449 */
1450 .deprecation(fd.loc, "overriding `extern(C++)` function `%s%s` with `const` qualified function `%s%s%s` is deprecated",
1451 fdv.toPrettyChars(), fdv.type.toTypeFunction().parameterList.parametersTypeToChars(),
1452 fd.toPrettyChars(), fd.type.toTypeFunction().parameterList.parametersTypeToChars(), fd.type.modToChars());
1453
1454 const char* where = fd.type.isNaked() ? "parameters" : "type";
1455 deprecationSupplemental(fd.loc, "Either remove `override`, or adjust the `const` qualifiers of the "
1456 ~ "overriding function %s", where);
1457 }
1458 else
1459 {
1460 // Treat as if Covariant.no
1461 mismatchvi = bestvi;
1462 mismatchstc = stc;
1463 mismatch = fdv;
1464 bestvi = -1;
1465 }
1466 }
1467 }
1468 if (bestvi == -1 && mismatch)
1469 {
1470 //type.print();
1471 //mismatch.type.print();
1472 //printf("%s %s\n", type.deco, mismatch.type.deco);
1473 //printf("stc = %llx\n", mismatchstc);
1474 if (mismatchstc)
1475 {
1476 // Fix it by modifying the type to add the storage classes
1477 fd.type = fd.type.addStorageClass(mismatchstc);
1478 bestvi = mismatchvi;
1479 }
1480 }
1481 return bestvi;
1482 }
1483
1484 /*********************************
1485 * If function is a function in a base class,
1486 * return that base class.
1487 * Params:
1488 * fd = function
1489 * Returns:
1490 * base class if overriding, null if not
1491 */
1492 BaseClass* overrideInterface(FuncDeclaration fd)
1493 {
1494 for (ClassDeclaration cd = fd.toParent2().isClassDeclaration(); cd; cd = cd.baseClass)
1495 {
1496 foreach (b; cd.interfaces)
1497 {
1498 auto v = findVtblIndex(fd, b.sym.vtbl[]);
1499 if (v >= 0)
1500 return b;
1501 }
1502 }
1503 return null;
1504 }
1505
1506 /// Flag used by $(LREF resolveFuncCall).
1507 enum FuncResolveFlag : ubyte
1508 {
1509 standard = 0, /// issue error messages, solve the call.
1510 quiet = 1, /// do not issue error message on no match, just return `null`.
1511 overloadOnly = 2, /// only resolve overloads, i.e. do not issue error on ambiguous
1512 /// matches and need explicit this.
1513 ufcs = 4, /// trying to resolve UFCS call
1514 }
1515
1516 /*******************************************
1517 * Given a symbol that could be either a FuncDeclaration or
1518 * a function template, resolve it to a function symbol.
1519 * Params:
1520 * loc = instantiation location
1521 * sc = instantiation scope
1522 * s = instantiation symbol
1523 * tiargs = initial list of template arguments
1524 * tthis = if !NULL, the `this` argument type
1525 * argumentList = arguments to function
1526 * flags = see $(LREF FuncResolveFlag).
1527 * Returns:
1528 * if match is found, then function symbol, else null
1529 */
1530 FuncDeclaration resolveFuncCall(Loc loc, Scope* sc, Dsymbol s,
1531 Objects* tiargs, Type tthis, ArgumentList argumentList, FuncResolveFlag flags)
1532 {
1533 //printf("resolveFuncCall() %s\n", s.toChars());
1534 auto fargs = argumentList.arguments;
1535 if (!s)
1536 return null; // no match
1537
1538 version (none)
1539 {
1540 printf("resolveFuncCall() %s)\n", s.toChars());
1541 if (tthis)
1542 printf("\tthis: %s\n", tthis.toChars());
1543 if (fargs)
1544 {
1545 for (size_t i = 0; i < fargs.length; i++)
1546 {
1547 Expression arg = (*fargs)[i];
1548 assert(arg.type);
1549 printf("\t%s: %s\n", arg.toChars(), arg.type.toChars());
1550 }
1551 }
1552 }
1553
1554 if (tiargs && arrayObjectIsError(*tiargs))
1555 return null;
1556 if (fargs !is null)
1557 foreach (arg; *fargs)
1558 if (isError(arg))
1559 return null;
1560
1561 MatchAccumulator m;
1562 functionResolve(m, s, loc, sc, tiargs, tthis, argumentList);
1563 auto orig_s = s;
1564
1565 if (m.last > MATCH.nomatch && m.lastf)
1566 {
1567 if (m.count == 1) // exactly one match
1568 {
1569 if (!(flags & FuncResolveFlag.quiet))
1570 functionSemantic(m.lastf);
1571 return m.lastf;
1572 }
1573 if ((flags & FuncResolveFlag.overloadOnly) && !tthis && m.lastf.needThis())
1574 {
1575 return m.lastf;
1576 }
1577 }
1578
1579 /* Failed to find a best match.
1580 * Do nothing or print error.
1581 */
1582 if (m.last == MATCH.nomatch)
1583 {
1584 // error was caused on matched function, not on the matching itself,
1585 // so return the function to produce a better diagnostic
1586 if (m.count == 1)
1587 return m.lastf;
1588 }
1589
1590 // We are done at this point, as the rest of this function generate
1591 // a diagnostic on invalid match
1592 if (flags & FuncResolveFlag.quiet)
1593 return null;
1594
1595 auto fd = s.isFuncDeclaration();
1596 auto od = s.isOverDeclaration();
1597 auto td = s.isTemplateDeclaration();
1598 if (td && td.funcroot)
1599 s = fd = td.funcroot;
1600
1601 OutBuffer tiargsBuf;
1602 arrayObjectsToBuffer(tiargsBuf, tiargs);
1603
1604 OutBuffer fargsBuf;
1605 fargsBuf.writeByte('(');
1606 argExpTypesToCBuffer(fargsBuf, fargs);
1607 fargsBuf.writeByte(')');
1608 if (tthis)
1609 tthis.modToBuffer(fargsBuf);
1610
1611 // The call is ambiguous
1612 if (m.lastf && m.nextf)
1613 {
1614 TypeFunction tf1 = m.lastf.type.toTypeFunction();
1615 TypeFunction tf2 = m.nextf.type.toTypeFunction();
1616 const(char)* lastprms = parametersTypeToChars(tf1.parameterList);
1617 const(char)* nextprms = parametersTypeToChars(tf2.parameterList);
1618
1619 string match = "";
1620 final switch (m.last)
1621 {
1622 case MATCH.convert:
1623 match = "after implicit conversions";
1624 break;
1625 case MATCH.constant:
1626 match = "after qualifier conversion";
1627 break;
1628 case MATCH.exact:
1629 match = "exactly";
1630 break;
1631 case MATCH.nomatch:
1632 assert(0);
1633 }
1634
1635 .error(loc, "`%s.%s` called with argument types `%s` matches multiple overloads %.*s:\n%s: `%s%s%s`\nand:\n%s: `%s%s%s`",
1636 s.parent.toPrettyChars(), s.ident.toChars(),
1637 fargsBuf.peekChars(),
1638 match.fTuple.expand,
1639 m.lastf.loc.toChars(), m.lastf.toPrettyChars(), lastprms, tf1.modToChars(),
1640 m.nextf.loc.toChars(), m.nextf.toPrettyChars(), nextprms, tf2.modToChars());
1641 return null;
1642 }
1643
1644 // no match, generate an error messages
1645 if (flags & FuncResolveFlag.ufcs)
1646 {
1647 auto arg = (*fargs)[0];
1648 .error(loc, "no property `%s` for `%s` of type `%s`", s.ident.toChars(), arg.toChars(), arg.type.toChars());
1649 .errorSupplemental(loc, "the following error occured while looking for a UFCS match");
1650 }
1651
1652 if (!fd)
1653 {
1654 // all of overloads are templates
1655 if (td)
1656 {
1657 if (!od && !td.overnext)
1658 {
1659 .error(loc, "%s `%s` is not callable using argument types `!(%s)%s`",
1660 td.kind(), td.ident.toChars(), tiargsBuf.peekChars(), fargsBuf.peekChars());
1661 }
1662 else
1663 {
1664 .error(loc, "none of the overloads of %s `%s.%s` are callable using argument types `!(%s)%s`",
1665 td.kind(), td.parent.toPrettyChars(), td.ident.toChars(),
1666 tiargsBuf.peekChars(), fargsBuf.peekChars());
1667 }
1668
1669
1670 if (!global.gag || global.params.v.showGaggedErrors)
1671 printCandidates(loc, td, sc.isDeprecated());
1672 return null;
1673 }
1674 /* This case used to happen when several ctors are mixed in an agregate.
1675 A (bad) error message is already generated in overloadApply().
1676 see https://issues.dlang.org/show_bug.cgi?id=19729
1677 and https://issues.dlang.org/show_bug.cgi?id=17259
1678 */
1679 if (!od)
1680 return null;
1681 }
1682
1683 if (od)
1684 {
1685 .error(loc, "none of the overloads of `%s` are callable using argument types `!(%s)%s`",
1686 od.ident.toChars(), tiargsBuf.peekChars(), fargsBuf.peekChars());
1687 if (!global.gag || global.params.v.showGaggedErrors)
1688 printCandidates(loc, od, sc.isDeprecated());
1689 return null;
1690 }
1691
1692 import dmd.expressionsem : checkDisabled;
1693 // remove when deprecation period of class allocators and deallocators is over
1694 if (fd.isNewDeclaration() && fd.checkDisabled(loc, sc))
1695 return null;
1696
1697 bool hasOverloads = fd.overnext !is null;
1698 auto tf = fd.type.isTypeFunction();
1699 // if type is an error, the original type should be there for better diagnostics
1700 if (!tf)
1701 tf = fd.originalType.toTypeFunction();
1702
1703 // modifier mismatch
1704 if (tthis && (fd.isCtorDeclaration() ?
1705 !MODimplicitConv(tf.mod, tthis.mod) :
1706 !MODimplicitConv(tthis.mod, tf.mod)))
1707 {
1708 OutBuffer thisBuf, funcBuf;
1709 MODMatchToBuffer(&thisBuf, tthis.mod, tf.mod);
1710 auto mismatches = MODMatchToBuffer(&funcBuf, tf.mod, tthis.mod);
1711 if (hasOverloads)
1712 {
1713 OutBuffer buf;
1714 buf.argExpTypesToCBuffer(fargs);
1715 if (fd.isCtorDeclaration())
1716 .error(loc, "none of the overloads of `%s` can construct a %sobject with argument types `(%s)`",
1717 fd.toChars(), thisBuf.peekChars(), buf.peekChars());
1718 else
1719 .error(loc, "none of the overloads of `%s` are callable using a %sobject with argument types `(%s)`",
1720 fd.toChars(), thisBuf.peekChars(), buf.peekChars());
1721
1722 if (!global.gag || global.params.v.showGaggedErrors)
1723 printCandidates(loc, fd, sc.isDeprecated());
1724 return null;
1725 }
1726
1727 bool calledHelper;
1728 void errorHelper(const(char)* failMessage) scope
1729 {
1730 .error(loc, "%s `%s%s%s` is not callable using argument types `%s`",
1731 fd.kind(), fd.toPrettyChars(), parametersTypeToChars(tf.parameterList),
1732 tf.modToChars(), fargsBuf.peekChars());
1733 errorSupplemental(loc, failMessage);
1734 calledHelper = true;
1735 }
1736
1737 functionResolve(m, orig_s, loc, sc, tiargs, tthis, argumentList, &errorHelper);
1738 if (calledHelper)
1739 return null;
1740
1741 if (fd.isCtorDeclaration())
1742 .error(loc, "%s%s `%s` cannot construct a %sobject",
1743 funcBuf.peekChars(), fd.kind(), fd.toPrettyChars(), thisBuf.peekChars());
1744 else
1745 .error(loc, "%smethod `%s` is not callable using a %sobject",
1746 funcBuf.peekChars(), fd.toPrettyChars(), thisBuf.peekChars());
1747
1748 if (mismatches.isNotShared)
1749 .errorSupplemental(fd.loc, "Consider adding `shared` here");
1750 else if (mismatches.isMutable)
1751 .errorSupplemental(fd.loc, "Consider adding `const` or `inout` here");
1752 return null;
1753 }
1754
1755 //printf("tf = %s, args = %s\n", tf.deco, (*fargs)[0].type.deco);
1756 if (hasOverloads)
1757 {
1758 .error(loc, "none of the overloads of `%s` are callable using argument types `%s`",
1759 fd.toChars(), fargsBuf.peekChars());
1760 if (!global.gag || global.params.v.showGaggedErrors)
1761 printCandidates(loc, fd, sc.isDeprecated());
1762 return null;
1763 }
1764
1765 .error(loc, "%s `%s%s%s` is not callable using argument types `%s`",
1766 fd.kind(), fd.toPrettyChars(), parametersTypeToChars(tf.parameterList),
1767 tf.modToChars(), fargsBuf.peekChars());
1768
1769 if (global.gag && !global.params.v.showGaggedErrors)
1770 return null;
1771
1772 // re-resolve to check for supplemental message
1773 if (tthis)
1774 {
1775 if (auto classType = tthis.isTypeClass())
1776 {
1777 if (auto baseClass = classType.sym.baseClass)
1778 {
1779 if (auto baseFunction = baseClass.search(baseClass.loc, fd.ident))
1780 {
1781 MatchAccumulator mErr;
1782 functionResolve(mErr, baseFunction, loc, sc, tiargs, baseClass.type, argumentList);
1783 if (mErr.last > MATCH.nomatch && mErr.lastf)
1784 {
1785 errorSupplemental(loc, "%s `%s` hides base class function `%s`",
1786 fd.kind, fd.toPrettyChars(), mErr.lastf.toPrettyChars());
1787 errorSupplemental(loc, "add `alias %s = %s` to `%s`'s body to merge the overload sets",
1788 fd.toChars(), mErr.lastf.toPrettyChars(), tthis.toChars());
1789 return null;
1790 }
1791 }
1792 }
1793 }
1794 }
1795
1796 void errorHelper2(const(char)* failMessage) scope
1797 {
1798 errorSupplemental(loc, failMessage);
1799 }
1800
1801 functionResolve(m, orig_s, loc, sc, tiargs, tthis, argumentList, &errorHelper2);
1802
1803 return null;
1804 }
1805
1806 /*******************************************
1807 * Prints template and function overload candidates as supplemental errors.
1808 * Params:
1809 * loc = instantiation location
1810 * declaration = the declaration to print overload candidates for
1811 * showDeprecated = If `false`, `deprecated` function won't be shown
1812 */
1813 private void printCandidates(Decl)(Loc loc, Decl declaration, bool showDeprecated)
1814 {
1815 // max num of overloads to print (-v or -verror-supplements overrides this).
1816 const uint DisplayLimit = global.params.v.errorSupplementCount();
1817 const(char)* constraintsTip;
1818
1819 int printed = 0; // number of candidates printed
1820 int count = 0; // total candidates
1821 bool child; // true if inside an eponymous template
1822 const(char)* errorPrefix() @safe
1823 {
1824 if (child)
1825 return " - Containing: ";
1826
1827 // align with blank spaces after first message
1828 enum plural = "Candidates are: ";
1829 enum spaces = " ";
1830 if (printed)
1831 return spaces;
1832
1833 return (count == 1) ? "Candidate is: " : plural;
1834 }
1835 bool matchSymbol(Dsymbol s, bool print)
1836 {
1837 if (auto fd = s.isFuncDeclaration())
1838 {
1839 // Don't print overloads which have errors.
1840 // Not that if the whole overload set has errors, we'll never reach
1841 // this point so there's no risk of printing no candidate
1842 if (fd.errors || fd.type.ty == Terror)
1843 return false;
1844 // Don't print disabled functions, or `deprecated` outside of deprecated scope
1845 if (fd.storage_class & STC.disable || (fd.isDeprecated() && !showDeprecated))
1846 return false;
1847 if (!print)
1848 return true;
1849 auto tf = cast(TypeFunction) fd.type;
1850 OutBuffer buf;
1851 buf.writestring(child ? fd.toChars() : fd.toPrettyChars());
1852 buf.writestring(parametersTypeToChars(tf.parameterList));
1853 if (tf.mod)
1854 {
1855 buf.writeByte(' ');
1856 buf.MODtoBuffer(tf.mod);
1857 }
1858 .errorSupplemental(fd.loc, "%s`%s`", errorPrefix(), buf.peekChars());
1859 }
1860 else if (auto td = s.isTemplateDeclaration())
1861 {
1862 import dmd.staticcond;
1863
1864 if (!print)
1865 return true;
1866
1867 // if td.onemember is a function, toCharsMaybeConstraints can print it
1868 // without us recursing, otherwise we have to handle it.
1869 // td.onemember may not have overloads set
1870 // (see fail_compilation/onemember_overloads.d)
1871 // assume if more than one member it is overloaded internally
1872 bool recurse = td.onemember && (!td.onemember.isFuncDeclaration ||
1873 td.members.length > 1);
1874 OutBuffer buf;
1875 HdrGenState hgs;
1876 hgs.skipConstraints = true; // failing constraint should get printed below
1877 hgs.showOneMember = !recurse;
1878 toCharsMaybeConstraints(td, buf, hgs);
1879 const tmsg = buf.peekChars();
1880 const cmsg = child ? null : td.getConstraintEvalError(constraintsTip);
1881
1882 if (cmsg)
1883 .errorSupplemental(td.loc, "%s`%s`\n%s", errorPrefix(), tmsg, cmsg);
1884 else
1885 .errorSupplemental(td.loc, "%s`%s`", errorPrefix(), tmsg);
1886
1887 if (recurse)
1888 {
1889 child = true;
1890 foreach (d; *td.members)
1891 {
1892 if (d.ident != td.ident)
1893 continue;
1894
1895 if (auto fd2 = d.isFuncDeclaration())
1896 matchSymbol(fd2, print);
1897 else if (auto td2 = d.isTemplateDeclaration())
1898 matchSymbol(td2, print);
1899 }
1900 child = false;
1901 }
1902 }
1903 return true;
1904 }
1905 // determine if there's > 1 candidate
1906 overloadApply(declaration, (s) {
1907 if (matchSymbol(s, false))
1908 count++;
1909 return count > 1;
1910 });
1911 int skipped = 0;
1912 overloadApply(declaration, (s) {
1913 if (global.params.v.verbose || printed < DisplayLimit)
1914 {
1915 if (matchSymbol(s, true))
1916 printed++;
1917 }
1918 else
1919 {
1920 // Too many overloads to sensibly display.
1921 // Just show count of remaining overloads.
1922 if (matchSymbol(s, false))
1923 skipped++;
1924 }
1925 return 0;
1926 });
1927 if (skipped > 0)
1928 .errorSupplemental(loc, "... (%d more, -v to show) ...", skipped);
1929
1930 // Nothing was displayed, all overloads are either disabled or deprecated
1931 if (!printed)
1932 .errorSupplemental(loc, "All possible candidates are marked as `deprecated` or `@disable`");
1933 // should be only in verbose mode
1934 if (constraintsTip)
1935 .tip(constraintsTip);
1936 }
1937
1938 /********************************************************
1939 * Generate Expression to call the invariant.
1940 * Input:
1941 * ad aggregate with the invariant
1942 * vthis variable with 'this'
1943 * Returns:
1944 * void expression that calls the invariant
1945 */
1946 Expression addInvariant(AggregateDeclaration ad, VarDeclaration vthis)
1947 {
1948 Expression e = null;
1949 // Call invariant directly only if it exists
1950 FuncDeclaration inv = ad.inv;
1951 ClassDeclaration cd = ad.isClassDeclaration();
1952
1953 while (!inv && cd)
1954 {
1955 cd = cd.baseClass;
1956 if (!cd)
1957 break;
1958 inv = cd.inv;
1959 }
1960 if (!inv)
1961 return e;
1962
1963 version (all)
1964 {
1965 // Workaround for https://issues.dlang.org/show_bug.cgi?id=13394
1966 // For the correct mangling,
1967 // run attribute inference on inv if needed.
1968 functionSemantic(inv);
1969 }
1970
1971 //e = new DsymbolExp(Loc.initial, inv);
1972 //e = new CallExp(Loc.initial, e);
1973 //e = e.semantic(sc2);
1974
1975 /* https://issues.dlang.org/show_bug.cgi?id=13113
1976 * Currently virtual invariant calls completely
1977 * bypass attribute enforcement.
1978 * Change the behavior of pre-invariant call by following it.
1979 */
1980 e = new ThisExp(Loc.initial);
1981 e.type = ad.type.addMod(vthis.type.mod);
1982 e = new DotVarExp(Loc.initial, e, inv, false);
1983 e.type = inv.type;
1984 e = new CallExp(Loc.initial, e);
1985 e.type = Type.tvoid;
1986 return e;
1987 }
1988
1989 /********************************************
1990 * Find function in overload list that exactly matches t.
1991 */
1992 FuncDeclaration overloadExactMatch(FuncDeclaration thisfd, Type t)
1993 {
1994 FuncDeclaration fd;
1995 overloadApply(thisfd, (Dsymbol s)
1996 {
1997 auto f = s.isFuncDeclaration();
1998 if (!f)
1999 return 0;
2000 if (f.storage_class & STC.disable)
2001 return 0;
2002 if (t.equals(f.type))
2003 {
2004 fd = f;
2005 return 1;
2006 }
2007 /* Allow covariant matches, as long as the return type
2008 * is just a const conversion.
2009 * This allows things like pure functions to match with an impure function type.
2010 */
2011 if (t.ty == Tfunction)
2012 {
2013 auto tf = cast(TypeFunction)f.type;
2014 if (tf.covariant(t) == Covariant.yes &&
2015 tf.nextOf().implicitConvTo(t.nextOf()) >= MATCH.constant)
2016 {
2017 fd = f;
2018 return 1;
2019 }
2020 }
2021 return 0;
2022 });
2023 return fd;
2024 }
2025
2026 /****************************************************
2027 * Determine if fd1 overrides fd2.
2028 * Return !=0 if it does.
2029 */
2030 int overrides(FuncDeclaration fd1, FuncDeclaration fd2)
2031 {
2032 if (fd1.ident != fd2.ident)
2033 return 0;
2034
2035 const cov = fd1.type.covariant(fd2.type);
2036 if (cov == Covariant.distinct)
2037 return 0;
2038
2039 ClassDeclaration cd1 = fd1.toParent().isClassDeclaration();
2040 ClassDeclaration cd2 = fd2.toParent().isClassDeclaration();
2041
2042 if (cd1 && cd2 && cd2.isBaseOf(cd1, null))
2043 return 1;
2044 return 0;
2045 }
2046
2047 /*************************************
2048 * Determine partial specialization order of functions `f` vs `g`.
2049 * This is very similar to TemplateDeclaration::leastAsSpecialized().
2050 * Params:
2051 * f = first function
2052 * g = second function
2053 * names = names of parameters
2054 * Returns:
2055 * match 'this' is at least as specialized as g
2056 * 0 g is more specialized than 'this'
2057 */
2058 MATCH leastAsSpecialized(FuncDeclaration f, FuncDeclaration g, Identifiers* names)
2059 {
2060 enum LOG_LEASTAS = 0;
2061 static if (LOG_LEASTAS)
2062 {
2063 import core.stdc.stdio : printf;
2064 printf("leastAsSpecialized(%s, %s, %s)\n", f.toChars(), g.toChars(), names ? names.toChars() : "null");
2065 printf("%s, %s\n", f.type.toChars(), g.type.toChars());
2066 }
2067
2068 /* This works by calling g() with f()'s parameters, and
2069 * if that is possible, then f() is at least as specialized
2070 * as g() is.
2071 */
2072
2073 TypeFunction tf = f.type.toTypeFunction();
2074 TypeFunction tg = g.type.toTypeFunction();
2075
2076 /* If both functions have a 'this' pointer, and the mods are not
2077 * the same and g's is not const, then this is less specialized.
2078 */
2079 if (f.needThis() && g.needThis() && tf.mod != tg.mod)
2080 {
2081 if (f.isCtorDeclaration())
2082 {
2083 if (!MODimplicitConv(tg.mod, tf.mod))
2084 return MATCH.nomatch;
2085 }
2086 else
2087 {
2088 if (!MODimplicitConv(tf.mod, tg.mod))
2089 return MATCH.nomatch;
2090 }
2091 }
2092
2093 /* Create a dummy array of arguments out of the parameters to f()
2094 */
2095 Expressions args;
2096 foreach (u, p; tf.parameterList)
2097 {
2098 Expression e;
2099 if (p.isReference())
2100 {
2101 e = new IdentifierExp(Loc.initial, p.ident);
2102 e.type = p.type;
2103 }
2104 else
2105 e = p.type.defaultInitLiteral(Loc.initial);
2106 args.push(e);
2107 }
2108
2109 MATCH m = callMatch(g, tg, null, ArgumentList(&args, names), 1);
2110 if (m > MATCH.nomatch)
2111 {
2112 /* A variadic parameter list is less specialized than a
2113 * non-variadic one.
2114 */
2115 if (tf.parameterList.varargs && !tg.parameterList.varargs)
2116 goto L1; // less specialized
2117
2118 static if (LOG_LEASTAS)
2119 {
2120 printf(" matches %d, so is least as specialized\n", m);
2121 }
2122 return m;
2123 }
2124 L1:
2125 static if (LOG_LEASTAS)
2126 {
2127 printf(" doesn't match, so is not as specialized\n");
2128 }
2129 return MATCH.nomatch;
2130 }
2131
2132 /********************************************
2133 * Find function in overload list that matches to the 'this' modifier.
2134 * There's four result types.
2135 *
2136 * 1. If the 'tthis' matches only one candidate, it's an "exact match".
2137 * Returns the function and 'hasOverloads' is set to false.
2138 * eg. If 'tthis" is mutable and there's only one mutable method.
2139 * 2. If there's two or more match candidates, but a candidate function will be
2140 * a "better match".
2141 * Returns the better match function but 'hasOverloads' is set to true.
2142 * eg. If 'tthis' is mutable, and there's both mutable and const methods,
2143 * the mutable method will be a better match.
2144 * 3. If there's two or more match candidates, but there's no better match,
2145 * Returns null and 'hasOverloads' is set to true to represent "ambiguous match".
2146 * eg. If 'tthis' is mutable, and there's two or more mutable methods.
2147 * 4. If there's no candidates, it's "no match" and returns null with error report.
2148 * e.g. If 'tthis' is const but there's no const methods.
2149 */
2150 FuncDeclaration overloadModMatch(FuncDeclaration thisfd, Loc loc, Type tthis, ref bool hasOverloads)
2151 {
2152 //printf("FuncDeclaration::overloadModMatch('%s')\n", toChars());
2153 MatchAccumulator m;
2154 overloadApply(thisfd, (Dsymbol s)
2155 {
2156 auto f = s.isFuncDeclaration();
2157 if (!f || f == m.lastf) // skip duplicates
2158 return 0;
2159 auto tf = f.type.toTypeFunction();
2160 //printf("tf = %s\n", tf.toChars());
2161 MATCH match;
2162 int lastIsBetter()
2163 {
2164 //printf("\tlastbetter\n");
2165 m.count++; // count up
2166 return 0;
2167 }
2168 int currIsBetter()
2169 {
2170 //printf("\tisbetter\n");
2171 if (m.last <= MATCH.convert)
2172 {
2173 // clear last secondary matching
2174 m.nextf = null;
2175 m.count = 0;
2176 }
2177 m.last = match;
2178 m.lastf = f;
2179 m.count++; // count up
2180 return 0;
2181 }
2182 if (tthis) // non-static functions are preferred than static ones
2183 {
2184 if (f.needThis())
2185 match = f.isCtorDeclaration() ? MATCH.exact : MODmethodConv(tthis.mod, tf.mod);
2186 else
2187 match = MATCH.constant; // keep static function in overload candidates
2188 }
2189 else // static functions are preferred than non-static ones
2190 {
2191 if (f.needThis())
2192 match = MATCH.convert;
2193 else
2194 match = MATCH.exact;
2195 }
2196 if (match == MATCH.nomatch)
2197 return 0;
2198 if (match > m.last) return currIsBetter();
2199 if (match < m.last) return lastIsBetter();
2200 // See if one of the matches overrides the other.
2201 if (m.lastf.overrides(f)) return lastIsBetter();
2202 if (f.overrides(m.lastf)) return currIsBetter();
2203 //printf("\tambiguous\n");
2204 m.nextf = f;
2205 m.count++;
2206 return 0;
2207 });
2208 if (m.count == 1) // exact match
2209 {
2210 hasOverloads = false;
2211 }
2212 else if (m.count > 1) // better or ambiguous match
2213 {
2214 hasOverloads = true;
2215 }
2216 else // no match
2217 {
2218 hasOverloads = true;
2219 auto tf = thisfd.type.toTypeFunction();
2220 assert(tthis);
2221 assert(!MODimplicitConv(tthis.mod, tf.mod)); // modifier mismatch
2222 {
2223 OutBuffer thisBuf, funcBuf;
2224 MODMatchToBuffer(&thisBuf, tthis.mod, tf.mod);
2225 MODMatchToBuffer(&funcBuf, tf.mod, tthis.mod);
2226 .error(loc, "%smethod %s is not callable using a %sobject", thisfd.kind, thisfd.toPrettyChars,
2227 funcBuf.peekChars(), thisfd.toPrettyChars(), thisBuf.peekChars());
2228 }
2229 }
2230 return m.lastf;
2231 }
2232
2233 /***********************************
2234 * Determine lexical level difference from `fd` to nested function `target`.
2235 * Issue error if `fd` cannot call `target`.
2236 *
2237 * Params:
2238 * fd = function
2239 * loc = location for error messages
2240 * sc = context
2241 * target = target of call
2242 * decl = The `Declaration` that triggered this check.
2243 * Used to provide a better error message only.
2244 * Returns:
2245 * 0 same level
2246 * >0 decrease nesting by number
2247 * -1 increase nesting by 1 (`target` is nested within 'fd')
2248 * LevelError error
2249 */
2250 int getLevelAndCheck(FuncDeclaration fd, Loc loc, Scope* sc, FuncDeclaration target,
2251 Declaration decl)
2252 {
2253 int level = fd.getLevel(target, sc.intypeof);
2254 if (level != fd.LevelError)
2255 return level;
2256 // Don't give error if in template constraint
2257 if (!sc.inTemplateConstraint)
2258 {
2259 const(char)* xstatic = fd.isStatic() ? "`static` " : "";
2260 // better diagnostics for static functions
2261 .error(loc, "%s%s `%s` cannot access %s `%s` in frame of function `%s`",
2262 xstatic, fd.kind(), fd.toPrettyChars(), decl.kind(), decl.toChars(),
2263 target.toPrettyChars());
2264 .errorSupplemental(decl.loc, "`%s` declared here", decl.toChars());
2265 return fd.LevelError;
2266 }
2267 return 1;
2268 }
2269
2270 /**********************************
2271 * Decide if attributes for this function can be inferred from examining
2272 * the function body.
2273 * Params:
2274 * fd = function to infer attributes for
2275 * sc = context
2276 * Returns:
2277 * true if can
2278 */
2279 bool canInferAttributes(FuncDeclaration fd, Scope* sc)
2280 {
2281 if (!fd.fbody)
2282 return false;
2283 if (fd.isVirtualMethod() &&
2284 /*
2285 * https://issues.dlang.org/show_bug.cgi?id=21719
2286 *
2287 * If we have an auto virtual function we can infer
2288 * the attributes.
2289 */
2290 !(fd.inferRetType && !fd.isCtorDeclaration()))
2291 return false; // since they may be overridden
2292 if (sc.func &&
2293 /********** this is for backwards compatibility for the moment ********/
2294 (!fd.isMember() || sc.func.isSafeBypassingInference() && !fd.isInstantiated()))
2295 return true;
2296 if (fd.isFuncLiteralDeclaration() || // externs are not possible with literals
2297 (fd.storage_class & STC.inference) || // do attribute inference
2298 fd.isGenerated || // compiler generated function
2299 (fd.inferRetType && !fd.isCtorDeclaration()))
2300 return true;
2301 if (fd.isInstantiated())
2302 {
2303 auto ti = fd.parent.isTemplateInstance();
2304 if (ti is null || ti.isTemplateMixin() || ti.tempdecl.ident == fd.ident)
2305 return true;
2306 }
2307 return false;
2308 }
2309
2310 /*********************************************
2311 * In the current function 'sc.func', we are calling 'fd'.
2312 * 1. Check to see if the current function can call 'fd' , issue error if not.
2313 * 2. If the current function is not the parent of 'fd' , then add
2314 * the current function to the list of siblings of 'fd' .
2315 * 3. If the current function is a literal, and it's accessing an uplevel scope,
2316 * then mark it as a delegate.
2317 * Returns true if error occurs.
2318 */
2319 bool checkNestedFuncReference(FuncDeclaration fd, Scope* sc, Loc loc)
2320 {
2321 //printf("FuncDeclaration::checkNestedFuncReference() %s\n", toPrettyChars());
2322 if (auto fld = fd.isFuncLiteralDeclaration())
2323 {
2324 if (fld.tok == TOK.reserved)
2325 {
2326 fld.tok = TOK.function_;
2327 fld.vthis = null;
2328 }
2329 }
2330 if (!fd.parent || fd.parent == sc.parent)
2331 return false;
2332 if (fd.ident == Id.require || fd.ident == Id.ensure)
2333 return false;
2334 if (!fd.isThis() && !fd.isNested())
2335 return false;
2336 // The current function
2337 FuncDeclaration fdthis = sc.parent.isFuncDeclaration();
2338 if (!fdthis)
2339 return false; // out of function scope
2340 Dsymbol p = fd.toParentLocal();
2341 Dsymbol p2 = fd.toParent2();
2342 // Function literals from fdthis to p must be delegates
2343 ensureStaticLinkTo(fdthis, p);
2344 if (p != p2)
2345 ensureStaticLinkTo(fdthis, p2);
2346 if (!fd.isNested())
2347 return false;
2348
2349 // The function that this function is in
2350 bool checkEnclosing(FuncDeclaration fdv)
2351 {
2352 if (!fdv)
2353 return false;
2354 if (fdv == fdthis)
2355 return false;
2356 //printf("this = %s in [%s]\n", this.toChars(), this.loc.toChars());
2357 //printf("fdv = %s in [%s]\n", fdv .toChars(), fdv .loc.toChars());
2358 //printf("fdthis = %s in [%s]\n", fdthis.toChars(), fdthis.loc.toChars());
2359 // Add this function to the list of those which called us
2360 if (fdthis != fd)
2361 {
2362 bool found = false;
2363 for (size_t i = 0; i < fd.siblingCallers.length; ++i)
2364 {
2365 if (fd.siblingCallers[i] == fdthis)
2366 found = true;
2367 }
2368 if (!found)
2369 {
2370 //printf("\tadding sibling %s to %s\n", fdthis.toPrettyChars(), toPrettyChars());
2371 if (!sc.intypeof && !sc.traitsCompiles)
2372 {
2373 fd.siblingCallers.push(fdthis);
2374 fd.computedEscapingSiblings = false;
2375 }
2376 }
2377 }
2378 const lv = fdthis.getLevelAndCheck(loc, sc, fdv, fd);
2379 if (lv == fd.LevelError)
2380 return true; // error
2381 if (lv == -1)
2382 return false; // downlevel call
2383 if (lv == 0)
2384 return false; // same level call
2385 return false; // Uplevel call
2386 }
2387 if (checkEnclosing(p.isFuncDeclaration()))
2388 return true;
2389 if (checkEnclosing(p == p2 ? null : p2.isFuncDeclaration()))
2390 return true;
2391 return false;
2392 }
2393
2394 /****************************************************
2395 * Check whether result variable can be built.
2396 * Returns:
2397 * `true` if the function has a return type that
2398 * is different from `void`.
2399 */
2400 private bool canBuildResultVar(FuncDeclaration fd)
2401 {
2402 auto f = cast(TypeFunction)fd.type;
2403 return f && f.nextOf() && f.nextOf().toBasetype().ty != Tvoid;
2404 }
2405
2406 /****************************************************
2407 * Declare result variable lazily.
2408 */
2409 void buildResultVar(FuncDeclaration fd, Scope* sc, Type tret)
2410 {
2411 if (!fd.vresult)
2412 {
2413 Loc loc = fd.fensure ? fd.fensure.loc : fd.loc;
2414 /* If inferRetType is true, tret may not be a correct return type yet.
2415 * So, in here it may be a temporary type for vresult, and after
2416 * fbody.dsymbolSemantic() running, vresult.type might be modified.
2417 */
2418 fd.vresult = new VarDeclaration(loc, tret, Id.result, null);
2419 fd.vresult.storage_class |= STC.nodtor | STC.temp;
2420 if (!fd.isVirtual())
2421 fd.vresult.storage_class |= STC.const_;
2422 fd.vresult.storage_class |= STC.result;
2423 // set before the semantic() for checkNestedReference()
2424 fd.vresult.parent = fd;
2425 }
2426 if (sc && fd.vresult.semanticRun == PASS.initial)
2427 {
2428 TypeFunction tf = fd.type.toTypeFunction();
2429 if (tf.isRef)
2430 fd.vresult.storage_class |= STC.ref_;
2431 fd.vresult.type = tret;
2432 fd.vresult.dsymbolSemantic(sc);
2433 if (!sc.insert(fd.vresult))
2434 .error(fd.loc, "%s `%s` out result %s is already defined", fd.kind, fd.toPrettyChars, fd.vresult.toChars());
2435 assert(fd.vresult.parent == fd);
2436 }
2437 }
2438
2439 /****************************************************
2440 * Merge into this function the 'in' contracts of all it overrides.
2441 * 'in's are OR'd together, i.e. only one of them needs to pass.
2442 */
2443 Statement mergeFrequire(FuncDeclaration fd, Statement sf, Expressions* params)
2444 {
2445 /* If a base function and its override both have an IN contract, then
2446 * only one of them needs to succeed. This is done by generating:
2447 *
2448 * void derived.in() {
2449 * try {
2450 * base.in();
2451 * }
2452 * catch () {
2453 * ... body of derived.in() ...
2454 * }
2455 * }
2456 *
2457 * So if base.in() doesn't throw, derived.in() need not be executed, and the contract is valid.
2458 * If base.in() throws, then derived.in()'s body is executed.
2459 */
2460 foreach (fdv; fd.foverrides)
2461 {
2462 /* The semantic pass on the contracts of the overridden functions must
2463 * be completed before code generation occurs.
2464 * https://issues.dlang.org/show_bug.cgi?id=3602
2465 */
2466 if (fdv.frequires && fdv.semanticRun != PASS.semantic3done)
2467 {
2468 assert(fdv._scope);
2469 Scope* sc = fdv._scope.push();
2470 sc.stc &= ~STC.override_;
2471 fdv.semantic3(sc);
2472 sc.pop();
2473 }
2474 sf = fdv.mergeFrequire(sf, params);
2475 if (!sf || !fdv.fdrequire)
2476 return null;
2477 //printf("fdv.frequire: %s\n", fdv.frequire.toChars());
2478 /* Make the call:
2479 * try { __require(params); }
2480 * catch (Throwable) { frequire; }
2481 */
2482 params = Expression.arraySyntaxCopy(params);
2483 Expression e = new CallExp(fd.loc, new VarExp(fd.loc, fdv.fdrequire, false), params);
2484 Statement s2 = new ExpStatement(fd.loc, e);
2485 auto c = new Catch(fd.loc, getThrowable(), null, sf);
2486 c.internalCatch = true;
2487 auto catches = new Catches();
2488 catches.push(c);
2489 sf = new TryCatchStatement(fd.loc, s2, catches);
2490 }
2491 return sf;
2492 }
2493
2494 /****************************************************
2495 * Merge into this function the 'in' contracts of all it overrides.
2496 */
2497 Statement mergeFrequireInclusivePreview(FuncDeclaration fd, Statement sf, Expressions* params)
2498 {
2499 /* If a base function and its override both have an IN contract, then
2500 * the override in contract must widen the guarantee of the base contract.
2501 * This is checked by generating:
2502 *
2503 * void derived.in() {
2504 * try {
2505 * ... body of derived.in() ...
2506 * }
2507 * catch () {
2508 * // derived in rejected this argument. so parent must also reject it, or we've tightened the contract.
2509 * base.in();
2510 * assert(false, "Logic error: " ~ thr.msg);
2511 * }
2512 * }
2513 */
2514 foreach (fdv; fd.foverrides)
2515 {
2516 /* The semantic pass on the contracts of the overridden functions must
2517 * be completed before code generation occurs.
2518 * https://issues.dlang.org/show_bug.cgi?id=3602
2519 */
2520 if (fdv.frequires && fdv.semanticRun != PASS.semantic3done)
2521 {
2522 assert(fdv._scope);
2523 Scope* sc = fdv._scope.push();
2524 sc.stc &= ~STC.override_;
2525 fdv.semantic3(sc);
2526 sc.pop();
2527 }
2528 sf = fdv.mergeFrequireInclusivePreview(sf, params);
2529 if (!sf || !fdv.fdrequire)
2530 return null;
2531
2532 const loc = fd.fdrequire.loc;
2533 //printf("fdv.frequire: %s\n", fdv.frequire.toChars());
2534 /* Make the call:
2535 * try { frequire; }
2536 * catch (Throwable thr) { __require(params); assert(false, "Logic error: " ~ thr.msg); }
2537 */
2538 Identifier id = Identifier.generateId("thr");
2539 params = Expression.arraySyntaxCopy(params);
2540 Expression e = new CallExp(loc, new VarExp(loc, fdv.fdrequire, false), params);
2541 Statement s2 = new ExpStatement(loc, e);
2542 // assert(false, ...)
2543 // TODO make this a runtime helper to allow:
2544 // - chaining the original expression
2545 // - nogc concatenation
2546 Expression msg = new StringExp(loc, "Logic error: in-contract was tighter than parent in-contract");
2547 Statement fail = new ExpStatement(loc, new AssertExp(loc, IntegerExp.literal!0, msg));
2548 Statement s3 = new CompoundStatement(loc, s2, fail);
2549 auto c = new Catch(loc, getThrowable(), id, s3);
2550 c.internalCatch = true;
2551 auto catches = new Catches();
2552 catches.push(c);
2553 sf = new TryCatchStatement(loc, sf, catches);
2554 }
2555 return sf;
2556 }
2557
2558 /****************************************************
2559 * Rewrite contracts as statements.
2560 */
2561 void buildEnsureRequire(FuncDeclaration thisfd)
2562 {
2563 if (thisfd.frequires)
2564 {
2565 /* in { statements1... }
2566 * in { statements2... }
2567 * ...
2568 * becomes:
2569 * in { { statements1... } { statements2... } ... }
2570 */
2571 assert(thisfd.frequires.length);
2572 auto loc = (*thisfd.frequires)[0].loc;
2573 auto s = new Statements;
2574 foreach (r; *thisfd.frequires)
2575 {
2576 s.push(new ScopeStatement(r.loc, r, r.loc));
2577 }
2578 thisfd.frequire = new CompoundStatement(loc, s);
2579 }
2580 if (thisfd.fensures)
2581 {
2582 /* out(id1) { statements1... }
2583 * out(id2) { statements2... }
2584 * ...
2585 * becomes:
2586 * out(__result) { { ref id1 = __result; { statements1... } }
2587 * { ref id2 = __result; { statements2... } } ... }
2588 */
2589 assert(thisfd.fensures.length);
2590 auto loc = (*thisfd.fensures)[0].ensure.loc;
2591 auto s = new Statements;
2592 foreach (r; *thisfd.fensures)
2593 {
2594 if (r.id && thisfd.canBuildResultVar())
2595 {
2596 auto rloc = r.ensure.loc;
2597 auto resultId = new IdentifierExp(rloc, Id.result);
2598 auto init = new ExpInitializer(rloc, resultId);
2599 auto stc = STC.ref_ | STC.temp | STC.result;
2600 auto decl = new VarDeclaration(rloc, null, r.id, init, stc);
2601 auto sdecl = new ExpStatement(rloc, decl);
2602 s.push(new ScopeStatement(rloc, new CompoundStatement(rloc, sdecl, r.ensure), rloc));
2603 }
2604 else
2605 {
2606 s.push(r.ensure);
2607 }
2608 }
2609 thisfd.fensure = new CompoundStatement(loc, s);
2610 }
2611 if (!thisfd.isVirtual())
2612 return;
2613 /* Rewrite contracts as nested functions, then call them. Doing it as nested
2614 * functions means that overriding functions can call them.
2615 */
2616 auto f = cast(TypeFunction) thisfd.type;
2617 /* Make a copy of the parameters and make them all ref */
2618 static Parameters* toRefCopy(ParameterList parameterList)
2619 {
2620 auto result = new Parameters();
2621 foreach (n, p; parameterList)
2622 {
2623 p = p.syntaxCopy();
2624 if (!p.isLazy())
2625 p.storageClass = (p.storageClass | STC.ref_) & ~STC.out_;
2626 p.defaultArg = null; // won't be the same with ref
2627 result.push(p);
2628 }
2629 return result;
2630 }
2631 if (thisfd.frequire)
2632 {
2633 /* in { ... }
2634 * becomes:
2635 * void __require(ref params) { ... }
2636 * __require(params);
2637 */
2638 Loc loc = thisfd.frequire.loc;
2639 thisfd.fdrequireParams = new Expressions();
2640 if (thisfd.parameters)
2641 {
2642 foreach (vd; *thisfd.parameters)
2643 thisfd.fdrequireParams.push(new VarExp(loc, vd));
2644 }
2645 auto fo = cast(TypeFunction)(thisfd.originalType ? thisfd.originalType : f);
2646 auto fparams = toRefCopy(fo.parameterList);
2647 auto tf = new TypeFunction(ParameterList(fparams), Type.tvoid, LINK.d);
2648 tf.isNothrow = f.isNothrow;
2649 tf.isNogc = f.isNogc;
2650 tf.purity = f.purity;
2651 tf.trust = f.trust;
2652 auto fd = new FuncDeclaration(loc, loc, Id.require, STC.none, tf);
2653 fd.fbody = thisfd.frequire;
2654 Statement s1 = new ExpStatement(loc, fd);
2655 Expression e = new CallExp(loc, new VarExp(loc, fd, false), thisfd.fdrequireParams);
2656 Statement s2 = new ExpStatement(loc, e);
2657 thisfd.frequire = new CompoundStatement(loc, s1, s2);
2658 thisfd.fdrequire = fd;
2659 }
2660 /* We need to set fdensureParams here and not in the block below to
2661 * have the parameters available when calling a base class ensure(),
2662 * even if this function doesn't have an out contract.
2663 */
2664 thisfd.fdensureParams = new Expressions();
2665 if (thisfd.canBuildResultVar())
2666 thisfd.fdensureParams.push(new IdentifierExp(thisfd.loc, Id.result));
2667 if (thisfd.parameters)
2668 {
2669 foreach (vd; *thisfd.parameters)
2670 thisfd.fdensureParams.push(new VarExp(thisfd.loc, vd));
2671 }
2672 if (thisfd.fensure)
2673 {
2674 /* out (result) { ... }
2675 * becomes:
2676 * void __ensure(ref tret result, ref params) { ... }
2677 * __ensure(result, params);
2678 */
2679 Loc loc = thisfd.fensure.loc;
2680 auto fparams = new Parameters();
2681 if (thisfd.canBuildResultVar())
2682 {
2683 Parameter p = new Parameter(loc, STC.ref_ | STC.const_, f.nextOf(), Id.result, null, null);
2684 fparams.push(p);
2685 }
2686 auto fo = cast(TypeFunction)(thisfd.originalType ? thisfd.originalType : f);
2687 fparams.pushSlice((*toRefCopy(fo.parameterList))[]);
2688 auto tf = new TypeFunction(ParameterList(fparams), Type.tvoid, LINK.d);
2689 tf.isNothrow = f.isNothrow;
2690 tf.isNogc = f.isNogc;
2691 tf.purity = f.purity;
2692 tf.trust = f.trust;
2693 auto fd = new FuncDeclaration(loc, loc, Id.ensure, STC.none, tf);
2694 fd.fbody = thisfd.fensure;
2695 Statement s1 = new ExpStatement(loc, fd);
2696 Expression e = new CallExp(loc, new VarExp(loc, fd, false), thisfd.fdensureParams);
2697 Statement s2 = new ExpStatement(loc, e);
2698 thisfd.fensure = new CompoundStatement(loc, s1, s2);
2699 thisfd.fdensure = fd;
2700 }
2701 }
2702
2703 /****************************************************
2704 * Determine whether an 'out' contract is declared inside
2705 * the given function or any of its overrides.
2706 * Params:
2707 * fd = the function to search
2708 * Returns:
2709 * true found an 'out' contract
2710 */
2711 bool needsFensure(FuncDeclaration fd) @safe
2712 {
2713 if (fd.fensures)
2714 return true;
2715
2716 foreach (fdv; fd.foverrides)
2717 {
2718 if (needsFensure(fdv))
2719 return true;
2720 }
2721 return false;
2722 }
2723
2724 /****************************************************
2725 * Merge into this function the 'out' contracts of all it overrides.
2726 * 'out's are AND'd together, i.e. all of them need to pass.
2727 */
2728 Statement mergeFensure(FuncDeclaration fd, Statement sf, Identifier oid, Expressions* params)
2729 {
2730 /* Same comments as for mergeFrequire(), except that we take care
2731 * of generating a consistent reference to the 'result' local by
2732 * explicitly passing 'result' to the nested function as a reference
2733 * argument.
2734 * This won't work for the 'this' parameter as it would require changing
2735 * the semantic code for the nested function so that it looks on the parameter
2736 * list for the 'this' pointer, something that would need an unknown amount
2737 * of tweaking of various parts of the compiler that I'd rather leave alone.
2738 */
2739 foreach (fdv; fd.foverrides)
2740 {
2741 /* The semantic pass on the contracts of the overridden functions must
2742 * be completed before code generation occurs.
2743 * https://issues.dlang.org/show_bug.cgi?id=3602 and
2744 * https://issues.dlang.org/show_bug.cgi?id=5230
2745 */
2746 if (needsFensure(fdv) && fdv.semanticRun != PASS.semantic3done)
2747 {
2748 assert(fdv._scope);
2749 Scope* sc = fdv._scope.push();
2750 sc.stc &= ~STC.override_;
2751 fdv.semantic3(sc);
2752 sc.pop();
2753 }
2754 sf = fdv.mergeFensure(sf, oid, params);
2755 if (!fdv.fdensure)
2756 continue;
2757
2758 //printf("fdv.fensure: %s\n", fdv.fensure.toChars());
2759 // Make the call: __ensure(result, params)
2760 params = Expression.arraySyntaxCopy(params);
2761 if (fd.canBuildResultVar())
2762 {
2763 Type t1 = fdv.type.nextOf().toBasetype();
2764 Type t2 = fd.type.nextOf().toBasetype();
2765 if (t1.isBaseOf(t2, null))
2766 {
2767 /* Making temporary reference variable is necessary
2768 * in covariant return.
2769 * https://issues.dlang.org/show_bug.cgi?id=5204
2770 * https://issues.dlang.org/show_bug.cgi?id=10479
2771 */
2772 Expression* eresult = &(*params)[0];
2773 auto ei = new ExpInitializer(Loc.initial, *eresult);
2774 auto v = new VarDeclaration(Loc.initial, t1, Identifier.generateId("__covres"), ei);
2775 v.storage_class |= STC.temp;
2776 auto de = new DeclarationExp(Loc.initial, v);
2777 auto ve = new VarExp(Loc.initial, v);
2778 *eresult = new CommaExp(Loc.initial, de, ve);
2779 }
2780 }
2781 Expression e = new CallExp(fd.loc, new VarExp(fd.loc, fdv.fdensure, false), params);
2782 Statement s2 = new ExpStatement(fd.loc, e);
2783 if (sf)
2784 {
2785 sf = new CompoundStatement(sf.loc, s2, sf);
2786 }
2787 else
2788 sf = s2;
2789 }
2790 return sf;
2791 }
2792
2793 /*******************************
2794 * Modify all expression type of return statements to tret.
2795 *
2796 * On function literals, return type may be modified based on the context type
2797 * after its semantic3 is done, in FuncExp::implicitCastTo.
2798 *
2799 * A function() dg = (){ return new B(); } // OK if is(B : A) == true
2800 *
2801 * If B to A conversion is convariant that requires offseet adjusting,
2802 * all return statements should be adjusted to return expressions typed A.
2803 */
2804 void modifyReturns(FuncLiteralDeclaration fld, Scope* sc, Type tret)
2805 {
2806 extern (C++) final class RetWalker : StatementRewriteWalker
2807 {
2808 alias visit = typeof(super).visit;
2809 public:
2810 Scope* sc;
2811 Type tret;
2812 FuncLiteralDeclaration fld;
2813 override void visit(ReturnStatement s)
2814 {
2815 Expression exp = s.exp;
2816 if (exp && !exp.type.equals(tret))
2817 s.exp = exp.implicitCastTo(sc, tret);
2818 }
2819 }
2820 if (fld.semanticRun < PASS.semantic3done)
2821 return;
2822 if (fld.fes)
2823 return;
2824 scope RetWalker w = new RetWalker();
2825 w.sc = sc;
2826 w.tret = tret;
2827 w.fld = fld;
2828 fld.fbody.accept(w);
2829 // Also update the inferred function type to match the new return type.
2830 // This is required so the code generator does not try to cast the
2831 // modified returns back to the original type.
2832 if (fld.inferRetType && fld.type.nextOf() != tret)
2833 fld.type.toTypeFunction().next = tret;
2834 }
2835
2836 /**************************************
2837 * When a traits(compiles) is used on a function literal call
2838 * we need to take into account if the body of the function
2839 * violates any attributes, however, we must not affect the
2840 * attribute inference on the outer function. The attributes
2841 * of the function literal still need to be inferred, therefore
2842 * we need a way to check for the scope that the traits compiles
2843 * introduces.
2844 *
2845 * Params:
2846 * sc = scope to be checked for
2847 *
2848 * Returns: `true` if the provided scope is the root
2849 * of the traits compiles list of scopes.
2850 */
2851 bool isRootTraitsCompilesScope(Scope* sc) @safe
2852 {
2853 return (sc.traitsCompiles) && !sc.func.skipCodegen;
2854 }
2855
2856 /+
2857 + Checks the parameter and return types iff this is a `main` function.
2858 +
2859 + The following signatures are allowed for a `D main`:
2860 + - Either no or a single parameter of type `string[]`
2861 + - Return type is either `void`, `int` or `noreturn`
2862 +
2863 + The following signatures are standard C:
2864 + - `int main()`
2865 + - `int main(int, char**)`
2866 +
2867 + This function accepts the following non-standard extensions:
2868 + - `char** envp` as a third parameter
2869 + - `void` / `noreturn` as return type
2870 +
2871 + This function will issue errors for unexpected arguments / return types.
2872 +/
2873 extern (D) void checkMain(FuncDeclaration fd)
2874 {
2875 if (fd.ident != Id.main || fd.isMember() || fd.isNested())
2876 return; // Not a main function
2877
2878 TypeFunction tf = fd.type.toTypeFunction();
2879
2880 Type retType = tf.nextOf();
2881 if (!retType)
2882 {
2883 // auto main(), check after semantic
2884 assert(fd.inferRetType);
2885 return;
2886 }
2887
2888 /// Checks whether `t` is equivalent to `char**`
2889 /// Ignores qualifiers and treats enums according to their base type
2890 static bool isCharPtrPtr(Type t)
2891 {
2892 auto tp = t.toBasetype().isTypePointer();
2893 if (!tp)
2894 return false;
2895
2896 tp = tp.next.toBasetype().isTypePointer();
2897 if (!tp)
2898 return false;
2899
2900 return tp.next.toBasetype().ty == Tchar;
2901 }
2902
2903 // Neither of these qualifiers is allowed because they affect the ABI
2904 enum invalidSTC = STC.out_ | STC.ref_ | STC.lazy_;
2905
2906 const nparams = tf.parameterList.length;
2907 bool argerr;
2908
2909 const linkage = fd.resolvedLinkage();
2910 if (linkage == LINK.d)
2911 {
2912 if (nparams == 1)
2913 {
2914 auto fparam0 = tf.parameterList[0];
2915 auto t = fparam0.type.toBasetype();
2916 if (t.ty != Tarray ||
2917 t.nextOf().ty != Tarray ||
2918 t.nextOf().nextOf().ty != Tchar ||
2919 fparam0.storageClass & invalidSTC)
2920 {
2921 argerr = true;
2922 }
2923 }
2924
2925 if (tf.parameterList.varargs || nparams >= 2 || argerr)
2926 .error(fd.loc, "%s `%s` parameter list must be empty or accept one parameter of type `string[]`", fd.kind, fd.toPrettyChars);
2927 }
2928
2929 else if (linkage == LINK.c)
2930 {
2931 if (nparams == 2 || nparams == 3)
2932 {
2933 // Argument count must be int
2934 auto argCount = tf.parameterList[0];
2935 argerr |= !!(argCount.storageClass & invalidSTC);
2936 argerr |= argCount.type.toBasetype().ty != Tint32;
2937
2938 // Argument pointer must be char**
2939 auto argPtr = tf.parameterList[1];
2940 argerr |= !!(argPtr.storageClass & invalidSTC);
2941 argerr |= !isCharPtrPtr(argPtr.type);
2942
2943 // `char** environ` is a common extension, see J.5.1 of the C standard
2944 if (nparams == 3)
2945 {
2946 auto envPtr = tf.parameterList[2];
2947 argerr |= !!(envPtr.storageClass & invalidSTC);
2948 argerr |= !isCharPtrPtr(envPtr.type);
2949 }
2950 }
2951 else
2952 argerr = nparams != 0;
2953
2954 // Disallow variadic main() - except for K&R declarations in C files.
2955 // E.g. int main(), int main(argc, argv) int argc, char** argc { ... }
2956 if (tf.parameterList.varargs && (!fd.isCsymbol() || (!tf.parameterList.hasIdentifierList && nparams)))
2957 argerr |= true;
2958
2959 if (argerr)
2960 {
2961 .error(fd.loc, "%s `%s` parameters must match one of the following signatures", fd.kind, fd.toPrettyChars);
2962 fd.loc.errorSupplemental("`main()`");
2963 fd.loc.errorSupplemental("`main(int argc, char** argv)`");
2964 fd.loc.errorSupplemental("`main(int argc, char** argv, char** environ)` [POSIX extension]");
2965 }
2966 }
2967 else
2968 return; // Neither C nor D main, ignore (should probably be an error)
2969
2970 // Allow enums with appropriate base types (same ABI)
2971 retType = retType.toBasetype();
2972
2973 if (retType.ty != Tint32 && retType.ty != Tvoid && retType.ty != Tnoreturn)
2974 .error(fd.loc, "%s `%s` must return `int`, `void` or `noreturn`, not `%s`", fd.kind, fd.toPrettyChars, tf.nextOf().toChars());
2975 }
2976
2977 /***********************************************
2978 * Check all return statements for a function to verify that returning
2979 * using NRVO is possible.
2980 *
2981 * Returns:
2982 * `false` if the result cannot be returned by hidden reference.
2983 */
2984 extern (D) bool checkNRVO(FuncDeclaration fd)
2985 {
2986 //printf("checkNRVO*() %s\n", fd.ident.toChars());
2987 if (!fd.isNRVO() || fd.returns is null)
2988 return false;
2989
2990 auto tf = fd.type.toTypeFunction();
2991 if (tf.isRef)
2992 return false;
2993
2994 foreach (rs; *fd.returns)
2995 {
2996 if (auto ve = rs.exp.isVarExp())
2997 {
2998 auto v = ve.var.isVarDeclaration();
2999 if (!v || v.isReference())
3000 return false;
3001 if (fd.nrvo_var is null)
3002 {
3003 // Variables in the data segment (e.g. globals, TLS or not),
3004 // parameters and closure variables cannot be NRVOed.
3005 if (v.isDataseg() || v.isParameter() || v.toParent2() != fd)
3006 return false;
3007 if (v.nestedrefs.length && fd.needsClosure())
3008 return false;
3009 // don't know if the return storage is aligned
3010 version (MARS)
3011 {
3012 if (fd.alignSectionVars && (*fd.alignSectionVars).contains(v))
3013 return false;
3014 }
3015 // The variable type needs to be equivalent to the return type.
3016 if (!v.type.equivalent(tf.next))
3017 return false;
3018 //printf("Setting nrvo to %s\n", v.toChars());
3019 fd.nrvo_var = v;
3020 }
3021 else if (fd.nrvo_var != v)
3022 return false;
3023 }
3024 else //if (!exp.isLvalue()) // keep NRVO-ability
3025 return false;
3026 }
3027 return true;
3028 }
3029
3030 /**************************************
3031 * The function is doing something impure, so mark it as impure.
3032 *
3033 * Params:
3034 * fd = function declaration to mark
3035 * loc = location of impure action
3036 * fmt = format string for error message
3037 * args = argument to format string
3038 *
3039 * Returns: `true` if there's a purity error
3040 */
3041 extern (D) bool setImpure(FuncDeclaration fd, Loc loc, const(char)* fmt, RootObject[] args...)
3042 {
3043 if (fd.purityInprocess)
3044 {
3045 fd.purityInprocess = false;
3046 if (fmt)
3047 fd.pureViolation = new AttributeViolation(loc, fmt, args); // impure action
3048 else if (args.length > 0)
3049 {
3050 if (auto sa = args[0].isDsymbol())
3051 {
3052 if (FuncDeclaration fd2 = sa.isFuncDeclaration())
3053 {
3054 fd.pureViolation = new AttributeViolation(loc, fd2); // call to impure function
3055 }
3056 }
3057 }
3058
3059 if (fd.fes)
3060 fd.fes.func.setImpure(loc, fmt, args);
3061 }
3062 else if (fd.isPure())
3063 return true;
3064 return false;
3065 }
3066
3067 PURE isPure(FuncDeclaration fd)
3068 {
3069 //printf("FuncDeclaration::isPure() '%s'\n", toChars());
3070
3071
3072 TypeFunction tf = fd.type.toTypeFunction();
3073 if (fd.purityInprocess)
3074 fd.setImpure(Loc.initial, null);
3075 if (tf.purity == PURE.fwdref)
3076 tf.purityLevel();
3077 PURE purity = tf.purity;
3078 if (purity > PURE.weak && fd.isNested())
3079 purity = PURE.weak;
3080 if (purity > PURE.weak && fd.needThis())
3081 {
3082 // The attribute of the 'this' reference affects purity strength
3083 if (fd.type.mod & MODFlags.immutable_)
3084 {
3085 }
3086 else if (fd.type.mod & (MODFlags.const_ | MODFlags.wild) && purity >= PURE.const_)
3087 purity = PURE.const_;
3088 else
3089 purity = PURE.weak;
3090 }
3091 tf.purity = purity;
3092 // ^ This rely on the current situation that every FuncDeclaration has a
3093 // unique TypeFunction.
3094 return purity;
3095 }
3096
3097 extern (D) PURE isPureBypassingInference(FuncDeclaration fd)
3098 {
3099 if (fd.purityInprocess)
3100 return PURE.fwdref;
3101 else
3102 return fd.isPure();
3103 }
3104
3105 /**************************************
3106 * Performs type-based alias analysis between a newly created value and a pre-
3107 * existing memory reference:
3108 *
3109 * Assuming that a reference A to a value of type `ta` was available to the code
3110 * that created a reference B to a value of type `tb`, it returns whether B
3111 * might alias memory reachable from A based on the types involved (either
3112 * directly or via any number of indirections in either A or B).
3113 *
3114 * This relation is not symmetric in the two arguments. For example, a
3115 * a `const(int)` reference can point to a pre-existing `int`, but not the other
3116 * way round.
3117 *
3118 * Examples:
3119 *
3120 * ta, tb, result
3121 * `const(int)`, `int`, `false`
3122 * `int`, `const(int)`, `true`
3123 * `int`, `immutable(int)`, `false`
3124 * const(immutable(int)*), immutable(int)*, false // BUG: returns true
3125 *
3126 * Params:
3127 * ta = value type being referred to
3128 * tb = referred to value type that could be constructed from ta
3129 *
3130 * Returns:
3131 * true if reference to `tb` is isolated from reference to `ta`
3132 */
3133 bool traverseIndirections(Type ta, Type tb)
3134 {
3135 //printf("traverseIndirections(%s, %s)\n", ta.toChars(), tb.toChars());
3136
3137 static bool traverse(Type ta, Type tb, ref scope AssocArray!(const(char)*, bool) table, bool reversePass)
3138 {
3139 //printf("traverse(%s, %s)\n", ta.toChars(), tb.toChars());
3140 ta = ta.baseElemOf();
3141 tb = tb.baseElemOf();
3142
3143 // First, check if the pointed-to types are convertible to each other such
3144 // that they might alias directly.
3145 static bool mayAliasDirect(Type source, Type target)
3146 {
3147 return
3148 // if source is the same as target or can be const-converted to target
3149 source.constConv(target) != MATCH.nomatch ||
3150 // if target is void and source can be const-converted to target
3151 (target.ty == Tvoid && MODimplicitConv(source.mod, target.mod));
3152 }
3153
3154 if (mayAliasDirect(reversePass ? tb : ta, reversePass ? ta : tb))
3155 {
3156 //printf(" true mayalias %s %s %d\n", ta.toChars(), tb.toChars(), reversePass);
3157 return false;
3158 }
3159 if (ta.nextOf() && ta.nextOf() == tb.nextOf())
3160 {
3161 //printf(" next==next %s %s %d\n", ta.toChars(), tb.toChars(), reversePass);
3162 return true;
3163 }
3164
3165 if (tb.ty == Tclass || tb.ty == Tstruct)
3166 {
3167 /* Traverse the type of each field of the aggregate
3168 */
3169 bool* found = table.getLvalue(tb.deco);
3170 if (*found == true)
3171 return true; // We have already seen this symbol, break the cycle
3172 else
3173 *found = true;
3174
3175 AggregateDeclaration sym = tb.toDsymbol(null).isAggregateDeclaration();
3176 foreach (v; sym.fields)
3177 {
3178 Type tprmi = v.type.addMod(tb.mod);
3179 //printf("\ttb = %s, tprmi = %s\n", tb.toChars(), tprmi.toChars());
3180 if (!traverse(ta, tprmi, table, reversePass))
3181 return false;
3182 }
3183 }
3184 else if (tb.ty == Tarray || tb.ty == Taarray || tb.ty == Tpointer)
3185 {
3186 Type tind = tb.nextOf();
3187 if (!traverse(ta, tind, table, reversePass))
3188 return false;
3189 }
3190 else if (tb.hasPointers())
3191 {
3192 // BUG: consider the context pointer of delegate types
3193 return false;
3194 }
3195
3196 // Still no match, so try breaking up ta if we have not done so yet.
3197 if (!reversePass)
3198 {
3199 scope newTable = AssocArray!(const(char)*, bool)();
3200 return traverse(tb, ta, newTable, true);
3201 }
3202
3203 return true;
3204 }
3205
3206 // To handle arbitrary levels of indirections in both parameters, we
3207 // recursively descend into aggregate members/levels of indirection in both
3208 // `ta` and `tb` while avoiding cycles. Start with the original types.
3209 scope table = AssocArray!(const(char)*, bool)();
3210 const result = traverse(ta, tb, table, false);
3211 //printf(" returns %d\n", result);
3212 return result;
3213 }
3214
3215 /********************************************
3216 * Params:
3217 * fd = function declaration to check
3218 * t = type of object to test one level of indirection down
3219 * Returns:
3220 * true if an object typed `t` has no indirections
3221 * which could have come from the function's parameters, mutable
3222 * globals, or uplevel functions.
3223 */
3224 bool isTypeIsolatedIndirect(FuncDeclaration fd, Type t)
3225 {
3226 //printf("isTypeIsolatedIndirect(t: %s)\n", t.toChars());
3227 assert(t);
3228
3229 /* Since `t` is one level down from an indirection, it could pick
3230 * up a reference to a mutable global or an outer function, so
3231 * return false.
3232 */
3233 if (!fd.isPureBypassingInference() || fd.isNested())
3234 return false;
3235
3236 TypeFunction tf = fd.type.toTypeFunction();
3237
3238 //printf("isTypeIsolatedIndirect(%s) t = %s\n", tf.toChars(), t.toChars());
3239
3240 foreach (i, fparam; tf.parameterList)
3241 {
3242 Type tp = fparam.type;
3243 if (!tp)
3244 continue;
3245
3246 if (fparam.isLazy() || fparam.isReference())
3247 {
3248 if (!traverseIndirections(tp, t))
3249 return false;
3250 continue;
3251 }
3252
3253 /* Goes down one level of indirection, then calls traverseIndirection() on
3254 * the result.
3255 * Returns:
3256 * true if t is isolated from tp
3257 */
3258 static bool traverse(Type tp, Type t)
3259 {
3260 tp = tp.baseElemOf();
3261 switch (tp.ty)
3262 {
3263 case Tarray:
3264 case Tpointer:
3265 return traverseIndirections(tp.nextOf(), t);
3266
3267 case Taarray:
3268 case Tclass:
3269 return traverseIndirections(tp, t);
3270
3271 case Tstruct:
3272 /* Drill down and check the struct's fields
3273 */
3274 auto sym = tp.toDsymbol(null).isStructDeclaration();
3275 foreach (v; sym.fields)
3276 {
3277 Type tprmi = v.type.addMod(tp.mod);
3278 //printf("\ttp = %s, tprmi = %s\n", tp.toChars(), tprmi.toChars());
3279 if (!traverse(tprmi, t))
3280 return false;
3281 }
3282 return true;
3283
3284 default:
3285 return true;
3286 }
3287 }
3288
3289 if (!traverse(tp, t))
3290 return false;
3291 }
3292 // The 'this' reference is a parameter, too
3293 if (AggregateDeclaration ad = fd.isCtorDeclaration() ? null : fd.isThis())
3294 {
3295 Type tthis = ad.getType().addMod(tf.mod);
3296 //printf("\ttthis = %s\n", tthis.toChars());
3297 if (!traverseIndirections(tthis, t))
3298 return false;
3299 }
3300
3301 return true;
3302 }
3303
3304 /********************************************
3305 * See if pointers from function parameters, mutable globals, or uplevel functions
3306 * could leak into return value.
3307 * Returns:
3308 * true if the function return value is isolated from
3309 * any inputs to the function
3310 */
3311 extern (D) bool isReturnIsolated(FuncDeclaration fd)
3312 {
3313 //printf("isReturnIsolated(this: %s)\n", this.toChars);
3314 TypeFunction tf = fd.type.toTypeFunction();
3315 assert(tf.next);
3316
3317 Type treti = tf.next;
3318 if (tf.isRef)
3319 return fd.isTypeIsolatedIndirect(treti); // check influence from parameters
3320
3321 return fd.isTypeIsolated(treti);
3322 }
3323
3324 /********************
3325 * See if pointers from function parameters, mutable globals, or uplevel functions
3326 * could leak into type `t`.
3327 * Params:
3328 * t = type to check if it is isolated
3329 * Returns:
3330 * true if `t` is isolated from
3331 * any inputs to the function
3332 */
3333 extern (D) bool isTypeIsolated(FuncDeclaration fd, Type t)
3334 {
3335 StringTable!Type parentTypes;
3336 const uniqueTypeID = t.getUniqueID();
3337 if (uniqueTypeID)
3338 {
3339 const cacheResultPtr = uniqueTypeID in fd.isTypeIsolatedCache;
3340 if (cacheResultPtr !is null)
3341 return *cacheResultPtr;
3342
3343 parentTypes._init();
3344 const isIsolated = fd.isTypeIsolated(t, parentTypes);
3345 fd.isTypeIsolatedCache[uniqueTypeID] = isIsolated;
3346 return isIsolated;
3347 }
3348 else
3349 {
3350 parentTypes._init();
3351 return fd.isTypeIsolated(t, parentTypes);
3352 }
3353 }
3354
3355 ///ditto
3356 extern (D) bool isTypeIsolated(FuncDeclaration fd, Type t, ref StringTable!Type parentTypes)
3357 {
3358 //printf("this: %s, isTypeIsolated(t: %s)\n", this.toChars(), t.toChars());
3359
3360 t = t.baseElemOf();
3361 switch (t.ty)
3362 {
3363 case Tarray:
3364 case Tpointer:
3365 return fd.isTypeIsolatedIndirect(t.nextOf()); // go down one level
3366
3367 case Taarray:
3368 case Tclass:
3369 return fd.isTypeIsolatedIndirect(t);
3370
3371 case Tstruct:
3372 /* Drill down and check the struct's fields
3373 */
3374 auto sym = t.toDsymbol(null).isStructDeclaration();
3375 const tName = t.toChars.toDString;
3376 const entry = parentTypes.insert(tName, t);
3377 if (entry == null)
3378 {
3379 //we've already seen this type in a parent, not isolated
3380 return false;
3381 }
3382 foreach (v; sym.fields)
3383 {
3384 Type tmi = v.type.addMod(t.mod);
3385 //printf("\tt = %s, v: %s, vtype: %s, tmi = %s\n",
3386 // t.toChars(), v.toChars(), v.type.toChars(), tmi.toChars());
3387 if (!fd.isTypeIsolated(tmi, parentTypes))
3388 return false;
3389 }
3390 return true;
3391
3392 default:
3393 return true;
3394 }
3395 }
3396
3397 /**
3398 * Check signature of `pragma(printf)` function, print error if invalid.
3399 *
3400 * printf/scanf-like functions must be of the form:
3401 * extern (C/C++) T printf([parameters...], const(char)* format, ...);
3402 * or:
3403 * extern (C/C++) T vprintf([parameters...], const(char)* format, va_list);
3404 *
3405 * Params:
3406 * funcdecl = function to check
3407 * f = function type
3408 * sc = scope
3409 */
3410 private void checkPrintfScanfSignature(FuncDeclaration funcdecl, TypeFunction f, Scope* sc)
3411 {
3412 static bool isPointerToChar(Parameter p)
3413 {
3414 if (auto tptr = p.type.isTypePointer())
3415 {
3416 return tptr.next.ty == Tchar;
3417 }
3418 return false;
3419 }
3420
3421 bool isVa_list(Parameter p)
3422 {
3423 return p.type.equals(target.va_listType(funcdecl.loc, sc));
3424 }
3425
3426 const nparams = f.parameterList.length;
3427 const p = (funcdecl.printf ? Id.printf : Id.scanf).toChars();
3428 if (!(f.linkage == LINK.c || f.linkage == LINK.cpp))
3429 {
3430 .error(funcdecl.loc, "`pragma(%s)` function `%s` must have `extern(C)` or `extern(C++)` linkage,"
3431 ~" not `extern(%s)`",
3432 p, funcdecl.toChars(), f.linkage.linkageToChars());
3433 }
3434 if (f.parameterList.varargs == VarArg.variadic)
3435 {
3436 if (!(nparams >= 1 && isPointerToChar(f.parameterList[nparams - 1])))
3437 {
3438 .error(funcdecl.loc, "`pragma(%s)` function `%s` must have"
3439 ~ " signature `%s %s([parameters...], const(char)*, ...)` not `%s`",
3440 p, funcdecl.toChars(), f.next.toChars(), funcdecl.toChars(), funcdecl.type.toChars());
3441 }
3442 }
3443 else if (f.parameterList.varargs == VarArg.none)
3444 {
3445 if(!(nparams >= 2 && isPointerToChar(f.parameterList[nparams - 2]) &&
3446 isVa_list(f.parameterList[nparams - 1])))
3447 .error(funcdecl.loc, "`pragma(%s)` function `%s` must have"~
3448 " signature `%s %s([parameters...], const(char)*, va_list)`",
3449 p, funcdecl.toChars(), f.next.toChars(), funcdecl.toChars());
3450 }
3451 else
3452 {
3453 .error(funcdecl.loc, "`pragma(%s)` function `%s` must have C-style variadic `...` or `va_list` parameter",
3454 p, funcdecl.toChars());
3455 }
3456 }
3457
3458 /***************************************************
3459 * Visit each overloaded function/template in turn, and call dg(s) on it.
3460 * Exit when no more, or dg(s) returns nonzero.
3461 *
3462 * Params:
3463 * fstart = symbol to start from
3464 * dg = the delegate to be called on the overload
3465 * sc = context used to check if symbol is accessible (and therefore visible),
3466 * can be null
3467 *
3468 * Returns:
3469 * ==0 continue
3470 * !=0 done (and the return value from the last dg() call)
3471 */
3472 extern (D) int overloadApply(Dsymbol fstart, scope int delegate(Dsymbol) dg, Scope* sc = null)
3473 {
3474 Dsymbols visited;
3475
3476 int overloadApplyRecurse(Dsymbol fstart, scope int delegate(Dsymbol) dg, Scope* sc)
3477 {
3478 // Detect cyclic calls.
3479 if (visited.contains(fstart))
3480 return 0;
3481 visited.push(fstart);
3482
3483 Dsymbol next;
3484 for (auto d = fstart; d; d = next)
3485 {
3486 import dmd.access : checkSymbolAccess;
3487 if (auto od = d.isOverDeclaration())
3488 {
3489 /* The scope is needed here to check whether a function in
3490 an overload set was added by means of a private alias (or a
3491 selective import). If the scope where the alias is created
3492 is imported somewhere, the overload set is visible, but the private
3493 alias is not.
3494 */
3495 if (sc)
3496 {
3497 if (checkSymbolAccess(sc, od))
3498 {
3499 if (int r = overloadApplyRecurse(od.aliassym, dg, sc))
3500 return r;
3501 }
3502 }
3503 else if (int r = overloadApplyRecurse(od.aliassym, dg, sc))
3504 return r;
3505 next = od.overnext;
3506 }
3507 else if (auto fa = d.isFuncAliasDeclaration())
3508 {
3509 if (fa.hasOverloads)
3510 {
3511 if (int r = overloadApplyRecurse(fa.funcalias, dg, sc))
3512 return r;
3513 }
3514 else if (auto fd = fa.toAliasFunc())
3515 {
3516 if (int r = dg(fd))
3517 return r;
3518 }
3519 else
3520 {
3521 .error(d.loc, "%s `%s` is aliased to a function", d.kind, d.toPrettyChars);
3522 break;
3523 }
3524 next = fa.overnext;
3525 }
3526 else if (auto ad = d.isAliasDeclaration())
3527 {
3528 if (sc)
3529 {
3530 if (checkSymbolAccess(sc, ad))
3531 next = ad.toAlias();
3532 }
3533 else
3534 next = ad.toAlias();
3535 if (next == ad)
3536 break;
3537 if (next == fstart)
3538 break;
3539 }
3540 else if (auto td = d.isTemplateDeclaration())
3541 {
3542 if (int r = dg(td))
3543 return r;
3544 next = td.overnext;
3545 }
3546 else if (auto fd = d.isFuncDeclaration())
3547 {
3548 if (int r = dg(fd))
3549 return r;
3550 next = fd.overnext;
3551 }
3552 else if (auto os = d.isOverloadSet())
3553 {
3554 foreach (ds; os.a)
3555 if (int r = dg(ds))
3556 return r;
3557 }
3558 else
3559 {
3560 .error(d.loc, "%s `%s` is aliased to a function", d.kind, d.toPrettyChars);
3561 break;
3562 // BUG: should print error message?
3563 }
3564 }
3565 return 0;
3566 }
3567 return overloadApplyRecurse(fstart, dg, sc);
3568 }