Debian Codegraph @

gcc/d/dmd/semantic3.d

raw
1 /**
2 * Performs the semantic3 stage, which deals with function bodies.
3 *
4 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
5 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
6 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/semantic3.d, _semantic3.d)
8 * Documentation: https://dlang.org/phobos/dmd_semantic3.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/semantic3.d
10 */
11
12 module dmd.semantic3;
13
14 import core.stdc.stdio;
15 import core.stdc.string;
16
17 import dmd.aggregate;
18 import dmd.aliasthis;
19 import dmd.arraytypes;
20 import dmd.astcodegen;
21 import dmd.astenums;
22 import dmd.attrib;
23 import dmd.blockexit;
24 import dmd.clone;
25 import dmd.ctorflow;
26 import dmd.dcast;
27 import dmd.dclass;
28 import dmd.declaration;
29 import dmd.denum;
30 import dmd.dimport;
31 import dmd.dinterpret;
32 import dmd.dmodule;
33 import dmd.dscope;
34 import dmd.dstruct;
35 import dmd.dsymbol;
36 import dmd.dsymbolsem;
37 import dmd.dtemplate;
38 import dmd.dversion;
39 import dmd.errors;
40 import dmd.escape;
41 import dmd.expression;
42 import dmd.expressionsem;
43 import dmd.func;
44 import dmd.funcsem;
45 import dmd.globals;
46 import dmd.id;
47 import dmd.identifier;
48 import dmd.init;
49 import dmd.initsem;
50 import dmd.hdrgen;
51 import dmd.location;
52 import dmd.mtype;
53 import dmd.nogc;
54 import dmd.nspace;
55 import dmd.ob;
56 import dmd.objc;
57 import dmd.opover;
58 import dmd.optimize;
59 import dmd.parse;
60 import dmd.root.filename;
61 import dmd.common.outbuffer;
62 import dmd.root.rmem;
63 import dmd.rootobject;
64 import dmd.root.utf;
65 import dmd.sideeffect;
66 import dmd.statementsem;
67 import dmd.staticassert;
68 import dmd.tokens;
69 import dmd.semantic2;
70 import dmd.statement;
71 import dmd.target;
72 import dmd.templateparamsem;
73 import dmd.typesem;
74 import dmd.visitor;
75
76 enum LOG = false;
77
78
79 /*************************************
80 * Does semantic analysis on function bodies.
81 */
82 void semantic3(Dsymbol dsym, Scope* sc)
83 {
84 scope v = new Semantic3Visitor(sc);
85 dsym.accept(v);
86 }
87
88 private extern(C++) final class Semantic3Visitor : Visitor
89 {
90 alias visit = Visitor.visit;
91
92 Scope* sc;
93 this(Scope* sc) scope @safe
94 {
95 this.sc = sc;
96 }
97
98 override void visit(Dsymbol) {}
99
100 override void visit(TemplateInstance tempinst)
101 {
102 static if (LOG)
103 {
104 printf("TemplateInstance.semantic3('%s'), semanticRun = %d\n", tempinst.toChars(), tempinst.semanticRun);
105 }
106 //if (toChars()[0] == 'D') *(char*)0=0;
107 if (tempinst.semanticRun >= PASS.semantic3)
108 return;
109 tempinst.semanticRun = PASS.semantic3;
110 if (tempinst.errors || !tempinst.members)
111 return;
112
113 TemplateDeclaration tempdecl = tempinst.tempdecl.isTemplateDeclaration();
114 assert(tempdecl);
115
116 sc = tempdecl._scope;
117 sc = sc.push(tempinst.argsym);
118 sc = sc.push(tempinst);
119 sc.tinst = tempinst;
120 sc.minst = tempinst.minst;
121
122 bool needGagging = tempinst.gagged && !global.gag;
123 const olderrors = global.errors;
124 const oldGaggedErrors = needGagging ? global.startGagging() : -1;
125 /* If this is a gagged instantiation, gag errors.
126 * Future optimisation: If the results are actually needed, errors
127 * would already be gagged, so we don't really need to run semantic
128 * on the members.
129 */
130
131 for (size_t i = 0; i < tempinst.members.length; i++)
132 {
133 Dsymbol s = (*tempinst.members)[i];
134 s.semantic3(sc);
135 if (tempinst.gagged && global.errors != olderrors)
136 break;
137 }
138
139 if (global.errors != olderrors)
140 {
141 if (!tempinst.errors)
142 {
143 if (!tempdecl.literal)
144 .error(tempinst.loc, "%s `%s` error instantiating", tempinst.kind, tempinst.toPrettyChars);
145 if (tempinst.tinst)
146 tempinst.tinst.printInstantiationTrace();
147 }
148 tempinst.errors = true;
149 }
150 if (needGagging)
151 global.endGagging(oldGaggedErrors);
152
153 sc = sc.pop();
154 sc.pop();
155 }
156
157 override void visit(TemplateMixin tmix)
158 {
159 if (tmix.semanticRun >= PASS.semantic3)
160 return;
161 tmix.semanticRun = PASS.semantic3;
162 static if (LOG)
163 {
164 printf("TemplateMixin.semantic3('%s')\n", tmix.toChars());
165 }
166 if (!tmix.members)
167 return;
168
169 sc = sc.push(tmix.argsym);
170 sc = sc.push(tmix);
171
172 const olderrors = global.errors;
173
174 for (size_t i = 0; i < tmix.members.length; i++)
175 {
176 Dsymbol s = (*tmix.members)[i];
177 s.semantic3(sc);
178 }
179
180 if (global.errors != olderrors)
181 errorSupplemental(tmix.loc, "parent scope from here: `mixin %s`", tmix.toChars());
182
183 sc = sc.pop();
184 sc.pop();
185 }
186
187 override void visit(Module mod)
188 {
189 //printf("Module::semantic3('%s'): parent = %p\n", toChars(), parent);
190 if (mod.semanticRun != PASS.semantic2done)
191 return;
192 mod.semanticRun = PASS.semantic3;
193 // Note that modules get their own scope, from scratch.
194 // This is so regardless of where in the syntax a module
195 // gets imported, it is unaffected by context.
196 Scope* sc = Scope.createGlobal(mod, global.errorSink); // create root scope
197 //printf("Module = %p\n", sc.scopesym);
198 if (mod.members)
199 {
200 // Pass 3 semantic routines: do initializers and function bodies
201 for (size_t i = 0; i < mod.members.length; i++)
202 {
203 Dsymbol s = (*mod.members)[i];
204 //printf("Module %s: %s.semantic3()\n", toChars(), s.toChars());
205 s.semantic3(sc);
206
207 mod.runDeferredSemantic2();
208 }
209 }
210 if (mod.userAttribDecl)
211 {
212 mod.userAttribDecl.semantic3(sc);
213 }
214 sc = sc.pop();
215 sc.pop();
216 mod.semanticRun = PASS.semantic3done;
217 }
218
219 override void visit(FuncDeclaration funcdecl)
220 {
221 //printf("FuncDeclaration::semantic3(%s '%s', sc = %p)\n", funcdecl.kind(), funcdecl.toChars(), sc);
222 import dmd.timetrace;
223 import dmd.root.string : toDString;
224 timeTraceBeginEvent(TimeTraceEventType.sema3);
225 scope (exit) timeTraceEndEvent(TimeTraceEventType.sema3, funcdecl);
226
227 /* Determine if function should add `return 0;`
228 */
229 bool addReturn0()
230 {
231 //printf("addReturn0()\n");
232 auto f = funcdecl.type.isTypeFunction();
233
234 // C11 5.1.2.2.3
235 if (sc.inCfile && funcdecl.isCMain() && f.next.ty == Tint32)
236 return true;
237
238 return f.next.ty == Tvoid && (funcdecl.isMain() || funcdecl.isCMain());
239 }
240
241 VarDeclaration _arguments = null;
242
243 if (!funcdecl.parent)
244 {
245 if (global.errors)
246 return;
247 //printf("FuncDeclaration::semantic3(%s '%s', sc = %p)\n", kind(), toChars(), sc);
248 assert(0);
249 }
250 if (funcdecl.errors || isError(funcdecl.parent))
251 {
252 funcdecl.errors = true;
253
254 // Mark that the return type could not be inferred
255 if (funcdecl.inferRetType)
256 {
257 assert(funcdecl.type);
258 auto tf = funcdecl.type.isTypeFunction();
259
260 // Only change the return type s.t. other analysis is
261 // still possible e.g. missmatched parameter types
262 if (tf && !tf.next)
263 tf.next = Type.terror;
264 }
265 return;
266 }
267 //printf("FuncDeclaration::semantic3('%s.%s', %p, sc = %p, loc = %s)\n", funcdecl.parent.toChars(), funcdecl.toChars(), funcdecl, sc, funcdecl.loc.toChars());
268 //fflush(stdout);
269 //printf("storage class = x%x %x\n", sc.stc, storage_class);
270 //{ static int x; if (++x == 2) *(char*)0=0; }
271 //printf("\tlinkage = %d\n", sc.linkage);
272
273 if (funcdecl.ident == Id.opAssign && !funcdecl.inuse)
274 {
275 if (funcdecl.storage_class & STC.inference)
276 {
277 /* https://issues.dlang.org/show_bug.cgi?id=15044
278 * For generated opAssign function, any errors
279 * from its body need to be gagged.
280 */
281 const oldErrors = global.startGagging();
282 ++funcdecl.inuse;
283 funcdecl.semantic3(sc);
284 --funcdecl.inuse;
285 if (global.endGagging(oldErrors)) // if errors happened
286 {
287 // Disable generated opAssign, because some members forbid identity assignment.
288 funcdecl.storage_class |= STC.disable;
289 funcdecl.fbody = null; // remove fbody which contains the error
290 funcdecl.hasSemantic3Errors = false;
291 }
292 return;
293 }
294 }
295
296 //printf(" sc.incontract = %d\n", sc.contract);
297 if (funcdecl.semanticRun >= PASS.semantic3)
298 return;
299 funcdecl.semanticRun = PASS.semantic3;
300 funcdecl.hasSemantic3Errors = false;
301 funcdecl.saferD = sc.previews.safer;
302
303 if (!funcdecl.type || funcdecl.type.ty != Tfunction)
304 return;
305 TypeFunction f = cast(TypeFunction)funcdecl.type;
306 if (!funcdecl.inferRetType && f.next.ty == Terror)
307 return;
308
309 if (!funcdecl.fbody && funcdecl.inferRetType && !f.next)
310 {
311 .error(funcdecl.loc, "%s `%s` has no function body with return type inference", funcdecl.kind, funcdecl.toPrettyChars);
312 return;
313 }
314
315 const oldErrors = global.errors;
316 auto fds = FuncDeclSem3(funcdecl,sc);
317
318 fds.checkInContractOverrides();
319
320 // Remember whether we need to generate an 'out' contract.
321 immutable bool needEnsure = funcdecl.needsFensure();
322
323 if (funcdecl.fbody || funcdecl.frequires || needEnsure)
324 {
325 /* Symbol table into which we place parameters and nested functions,
326 * solely to diagnose name collisions.
327 */
328 funcdecl.localsymtab = new DsymbolTable();
329
330 // Establish function scope
331 auto ss = new ScopeDsymbol(funcdecl.loc, null);
332 // find enclosing scope symbol, might skip symbol-less CTFE and/or FuncExp scopes
333 ss.parent = sc.inner().scopesym;
334 ss.endlinnum = funcdecl.endloc.linnum;
335 Scope* sc2 = sc.push(ss);
336 sc2.func = funcdecl;
337 sc2.parent = funcdecl;
338 sc2.ctorflow.callSuper = CSX.none;
339 sc2.sbreak = null;
340 sc2.scontinue = null;
341 sc2.switchStatement = null;
342 sc2.fes = funcdecl.fes;
343 sc2.linkage = funcdecl.isCsymbol() ? LINK.c : LINK.d;
344 sc2.stc &= STC.flowThruFunction;
345 sc2.visibility = Visibility(Visibility.Kind.public_);
346 sc2.explicitVisibility = 0;
347 sc2.aligndecl = null;
348 if (funcdecl.ident != Id.require && funcdecl.ident != Id.ensure)
349 {
350 sc2.copyFlagsFrom(sc);
351 sc2.contract = Contract.none;
352 }
353 sc2.tryFinally = null;
354 sc2.scopeGuard = null;
355 sc2.inLoop = false;
356 sc2.inDefaultArg = false;
357 sc2.userAttribDecl = null;
358 if (sc2.intypeof == 1)
359 sc2.intypeof = 2;
360 sc2.ctorflow.fieldinit = null;
361
362 /* Note: When a lambda is defined immediately under aggregate member
363 * scope, it should be contextless due to prevent interior pointers.
364 * e.g.
365 * // dg points 'this' - its interior pointer
366 * class C { int x; void delegate() dg = (){ this.x = 1; }; }
367 *
368 * However, lambdas could be used inside typeof, in order to check
369 * some expressions validity at compile time. For such case the lambda
370 * body can access aggregate instance members.
371 * e.g.
372 * class C { int x; static assert(is(typeof({ this.x = 1; }))); }
373 *
374 * To properly accept it, mark these lambdas as member functions.
375 */
376 if (auto fld = funcdecl.isFuncLiteralDeclaration())
377 {
378 if (auto ad = funcdecl.isMember2())
379 {
380 if (!sc.intypeof)
381 {
382 if (fld.tok == TOK.delegate_)
383 .error(funcdecl.loc, "%s `%s` cannot be %s members", funcdecl.kind, funcdecl.toErrMsg, ad.kind());
384 else
385 fld.tok = TOK.function_;
386 }
387 else
388 {
389 if (fld.tok != TOK.function_)
390 fld.tok = TOK.delegate_;
391 }
392 }
393 }
394
395 declareThis(funcdecl, sc2);
396
397 // Reverts: https://issues.dlang.org/show_bug.cgi?id=5710
398 // No compiler supports this, and there was never any spec for it.
399 // @@@DEPRECATED_2.116@@@
400 // Deprecated in 2.096, can be made an error in 2.116.
401 // The deprecation period is longer than usual as dual-context
402 // functions may be widely used by dmd-compiled projects.
403 // It also gives more time for the implementation of dual-context
404 // functions to be reworked as a frontend-only feature.
405 if (funcdecl.hasDualContext())
406 {
407 .deprecation(funcdecl.loc, "%s `%s` function requires a dual-context, which is deprecated", funcdecl.kind, funcdecl.toPrettyChars);
408 if (auto ti = sc2.parent ? sc2.parent.isInstantiated() : null)
409 ti.printInstantiationTrace(Classification.deprecation);
410 }
411
412 //printf("[%s] ad = %p vthis = %p\n", loc.toChars(), ad, vthis);
413 //if (vthis) printf("\tvthis.type = %s\n", vthis.type.toChars());
414
415 // Declare hidden variable _arguments[] and _argptr
416 if (f.parameterList.varargs == VarArg.variadic)
417 {
418 if (f.linkage == LINK.d)
419 {
420 // Variadic arguments depend on Typeinfo being defined.
421 if (!global.params.useTypeInfo || !Type.dtypeinfo || !Type.typeinfotypelist)
422 {
423 if (!global.params.useTypeInfo)
424 {
425 version (IN_GCC)
426 .error(funcdecl.loc, "%s `%s` D-style variadic functions cannot be used with `-fno-rtti`", funcdecl.kind, funcdecl.toPrettyChars);
427 else
428 .error(funcdecl.loc, "%s `%s` D-style variadic functions cannot be used with -betterC", funcdecl.kind, funcdecl.toPrettyChars);
429 }
430 else if (!Type.typeinfotypelist)
431 .error(funcdecl.loc, "%s `%s` `object.TypeInfo_Tuple` could not be found, but is implicitly used in D-style variadic functions", funcdecl.kind, funcdecl.toPrettyChars);
432 else
433 .error(funcdecl.loc, "%s `%s` `object.TypeInfo` could not be found, but is implicitly used in D-style variadic functions", funcdecl.kind, funcdecl.toPrettyChars);
434 funcdecl.errors = true;
435 }
436 }
437
438 if (!funcdecl.errors && f.linkage == LINK.d)
439 {
440 // Declare _arguments[]
441 funcdecl.v_arguments = new VarDeclaration(funcdecl.loc, Type.typeinfotypelist.type, Id._arguments_typeinfo, null);
442 funcdecl.v_arguments.storage_class |= STC.temp | STC.parameter;
443 funcdecl.v_arguments.dsymbolSemantic(sc2);
444 sc2.insert(funcdecl.v_arguments);
445 funcdecl.v_arguments.parent = funcdecl;
446
447 //Type t = Type.dtypeinfo.type.constOf().arrayOf();
448 Type t = Type.dtypeinfo.type.arrayOf();
449 _arguments = new VarDeclaration(funcdecl.loc, t, Id._arguments, null);
450 _arguments.storage_class |= STC.temp;
451 _arguments.dsymbolSemantic(sc2);
452 sc2.insert(_arguments);
453 _arguments.parent = funcdecl;
454 }
455 if (!funcdecl.errors && (f.linkage == LINK.d || f.parameterList.length))
456 {
457 // Declare _argptr
458 Type t = target.va_listType(funcdecl.loc, sc);
459 // Init is handled in FuncDeclaration_toObjFile
460 funcdecl.v_argptr = new VarDeclaration(funcdecl.loc, t, Id._argptr, new VoidInitializer(funcdecl.loc));
461 funcdecl.v_argptr.storage_class |= STC.temp;
462 funcdecl.v_argptr.dsymbolSemantic(sc2);
463 sc2.insert(funcdecl.v_argptr);
464 funcdecl.v_argptr.parent = funcdecl;
465 }
466 }
467
468 /* Declare all the function parameters as variables
469 * and install them in parameters[]
470 */
471 if (const nparams = f.parameterList.length)
472 {
473 /* parameters[] has all the tuples removed, as the back end
474 * doesn't know about tuples
475 */
476 funcdecl.parameters = new VarDeclarations();
477 funcdecl.parameters.reserve(nparams);
478 foreach (i, fparam; f.parameterList)
479 {
480 Identifier id = fparam.ident;
481 STC stc = STC.none;
482 if (!id)
483 {
484 /* Generate identifier for un-named parameter,
485 * because we need it later on.
486 */
487 fparam.ident = id = Identifier.generateId("__param_", i);
488 stc |= STC.temp;
489 }
490 Type vtype = fparam.type;
491 auto v = new VarDeclaration(fparam.loc, vtype, id, null);
492 //printf("declaring parameter %s of type %s\n", v.toChars(), v.type.toChars());
493 stc |= STC.parameter;
494 if (f.parameterList.varargs == VarArg.typesafe && i + 1 == nparams)
495 {
496 stc |= STC.variadic;
497 }
498
499 stc |= fparam.storageClass & (STC.IOR | STC.return_ | STC.scope_ | STC.lazy_ | STC.final_ | STC.TYPECTOR | STC.nodtor | STC.returnScope | STC.register);
500 v.storage_class = stc;
501 v.dsymbolSemantic(sc2);
502 if (!sc2.insert(v))
503 {
504 .error(funcdecl.loc, "%s `%s` parameter `%s.%s` is already defined", funcdecl.kind, funcdecl.toPrettyChars, funcdecl.toChars(), v.toChars());
505 funcdecl.errors = true;
506 }
507 else
508 funcdecl.parameters.push(v);
509 funcdecl.localsymtab.insert(v);
510 v.parent = funcdecl;
511 if (fparam.userAttribDecl)
512 v.userAttribDecl = fparam.userAttribDecl;
513 }
514 }
515
516 // Declare the tuple symbols and put them in the symbol table,
517 // but not in parameters[].
518 if (f.parameterList.parameters)
519 foreach (fparam; *f.parameterList.parameters)
520 {
521 if (!fparam.ident)
522 continue; // never used, so ignore
523 // expand any tuples
524 if (fparam.type.ty != Ttuple)
525 continue;
526
527 TypeTuple t = cast(TypeTuple)fparam.type;
528 size_t dim = Parameter.dim(t.arguments);
529 auto exps = new Objects(dim);
530 foreach (j; 0 .. dim)
531 {
532 Parameter narg = Parameter.getNth(t.arguments, j);
533 assert(narg.ident);
534 Dsymbol pscopesym;
535 VarDeclaration v = sc2.search(Loc.initial, narg.ident, pscopesym).isVarDeclaration();
536 assert(v);
537 (*exps)[j] = new VarExp(v.loc, v);
538 }
539 assert(fparam.ident);
540 auto v = new TupleDeclaration(funcdecl.loc, fparam.ident, exps);
541 //printf("declaring tuple %s\n", v.toChars());
542 v.isexp = true;
543 if (!sc2.insert(v))
544 .error(funcdecl.loc, "%s `%s` parameter `%s.%s` is already defined", funcdecl.kind, funcdecl.toPrettyChars, funcdecl.toChars(), v.toChars());
545 funcdecl.localsymtab.insert(v);
546 v.parent = funcdecl;
547 }
548
549 // Precondition invariant
550 Statement fpreinv = null;
551 if (funcdecl.addPreInvariant())
552 {
553 if (Expression e = addInvariant(funcdecl.isThis(), funcdecl.vthis))
554 fpreinv = new ExpStatement(Loc.initial, e);
555 }
556
557 // Postcondition invariant
558 Statement fpostinv = null;
559 if (funcdecl.addPostInvariant())
560 {
561 if (Expression e = addInvariant(funcdecl.isThis(), funcdecl.vthis))
562 fpostinv = new ExpStatement(Loc.initial, e);
563 }
564
565 // Pre/Postcondition contract
566 if (!funcdecl.fbody)
567 funcdecl.buildEnsureRequire();
568
569 Scope* scout = null;
570 if (needEnsure || funcdecl.addPostInvariant())
571 {
572 /* https://issues.dlang.org/show_bug.cgi?id=3657
573 * Set the correct end line number for fensure scope.
574 */
575 uint fensure_endlin = funcdecl.endloc.linnum;
576 if (funcdecl.fensure)
577 if (auto s = funcdecl.fensure.isScopeStatement())
578 fensure_endlin = s.endloc.linnum;
579
580 if ((needEnsure && global.params.useOut == CHECKENABLE.on) || fpostinv)
581 {
582 funcdecl.returnLabel = funcdecl.searchLabel(Id.returnLabel, Loc.initial);
583 }
584
585 // scope of out contract (need for vresult.semantic)
586 auto sym = new ScopeDsymbol(funcdecl.loc, null);
587 sym.parent = sc2.scopesym;
588 sym.endlinnum = fensure_endlin;
589 scout = sc2.push(sym);
590 }
591
592 if (funcdecl.fbody)
593 {
594 auto sym = new ScopeDsymbol(funcdecl.loc, null);
595 sym.parent = sc2.scopesym;
596 sym.endlinnum = funcdecl.endloc.linnum;
597 sc2 = sc2.push(sym);
598
599 auto ad2 = funcdecl.isMemberLocal();
600
601 /* If this is a class constructor
602 */
603 if (ad2 && funcdecl.isCtorDeclaration())
604 {
605 sc2.ctorflow.allocFieldinit(ad2.fields.length);
606 foreach (v; ad2.fields)
607 {
608 v.ctorinit = 0;
609 }
610 }
611
612 bool inferRef = (f.isRef && (funcdecl.storage_class & STC.auto_));
613
614 funcdecl.fbody = funcdecl.fbody.statementSemantic(sc2);
615 if (!funcdecl.fbody)
616 funcdecl.fbody = new CompoundStatement(Loc.initial, new Statements());
617
618 if (funcdecl.isNaked())
619 {
620 fpreinv = null; // can't accommodate with no stack frame
621 fpostinv = null;
622 }
623
624 assert(funcdecl.type == f || (funcdecl.type.ty == Tfunction && f.purity == PURE.impure && (cast(TypeFunction)funcdecl.type).purity >= PURE.fwdref));
625 f = cast(TypeFunction)funcdecl.type;
626
627 if (funcdecl.inferRetType)
628 {
629 // If no return type inferred yet, then infer a void
630 if (!f.next)
631 f.next = Type.tvoid;
632 if (f.checkRetType(funcdecl.loc))
633 funcdecl.fbody = new ErrorStatement();
634 else
635 funcdecl.checkMain(); // Check main() parameters and return type
636 }
637
638 if (f.next !is null)
639 f.next.checkComplexTransition(funcdecl.loc, sc);
640
641 if (funcdecl.returns && !funcdecl.fbody.isErrorStatement())
642 {
643 for (size_t i = 0; i < funcdecl.returns.length;)
644 {
645 Expression exp = (*funcdecl.returns)[i].exp;
646 if (exp.op == EXP.variable && (cast(VarExp)exp).var == funcdecl.vresult)
647 {
648 if (addReturn0())
649 exp.type = Type.tint32;
650 else
651 exp.type = f.next;
652 // Remove `return vresult;` from returns
653 funcdecl.returns.remove(i);
654 continue;
655 }
656 if (inferRef && f.isRef && !exp.type.constConv(f.next)) // https://issues.dlang.org/show_bug.cgi?id=13336
657 f.isRef = false;
658 i++;
659 }
660 }
661 if (f.isRef) // Function returns a reference
662 {
663 if (funcdecl.storage_class & STC.auto_)
664 funcdecl.storage_class &= ~STC.auto_;
665 }
666
667 // handle NRVO
668 if (!target.isReturnOnStack(f, funcdecl.needThis()) || !funcdecl.checkNRVO())
669 funcdecl.isNRVO = false;
670
671 if (funcdecl.fbody.isErrorStatement())
672 {
673 }
674 else if (funcdecl.isStaticCtorDeclaration())
675 {
676 /* It's a static constructor. Ensure that all
677 * ctor consts were initialized.
678 */
679 ScopeDsymbol pd = funcdecl.toParent().isScopeDsymbol();
680 for (size_t i = 0; i < pd.members.length; i++)
681 {
682 Dsymbol s = (*pd.members)[i];
683 s.checkCtorConstInit();
684 }
685 }
686 else if (ad2 && funcdecl.isCtorDeclaration())
687 {
688 ClassDeclaration cd = ad2.isClassDeclaration();
689
690 // Verify that all the ctorinit fields got initialized
691 if (!(sc2.ctorflow.callSuper & CSX.this_ctor))
692 {
693 foreach (i, v; ad2.fields)
694 {
695 if (v.isThisDeclaration())
696 continue;
697 if (v.ctorinit == 0)
698 {
699 /* Current bugs in the flow analysis:
700 * 1. union members should not produce error messages even if
701 * not assigned to
702 * 2. structs should recognize delegating opAssign calls as well
703 * as delegating calls to other constructors
704 */
705 if (v.isCtorinit() && !v.type.isMutable() && cd)
706 .error(funcdecl.loc, "%s `%s` missing initializer for %s field `%s`", funcdecl.kind, funcdecl.toPrettyChars, MODtoChars(v.type.mod), v.toChars());
707 else if (v.storage_class & STC.nodefaultctor)
708 error(funcdecl.loc, "field `%s` must be initialized in constructor", v.toChars());
709 else if (v.type.needsNested())
710 error(funcdecl.loc, "field `%s` must be initialized in constructor, because it is nested struct", v.toChars());
711 }
712 else
713 {
714 bool mustInit = (v.storage_class & STC.nodefaultctor || v.type.needsNested());
715 if (mustInit && !(sc2.ctorflow.fieldinit[i].csx & CSX.this_ctor))
716 {
717 .error(funcdecl.loc, "%s `%s` field `%s` must be initialized but skipped", funcdecl.kind, funcdecl.toPrettyChars, v.toChars());
718 }
719 }
720 }
721 }
722 sc2.ctorflow.freeFieldinit();
723
724 if (cd && !(sc2.ctorflow.callSuper & (CSX.any_ctor | CSX.halt)) && cd.baseClass && cd.baseClass.ctor)
725 {
726 sc2.ctorflow.callSuper = CSX.none;
727
728 // Insert implicit super() at start of fbody
729 Type tthis = ad2.type.addMod(funcdecl.vthis.type.mod);
730 FuncDeclaration fd = resolveFuncCall(Loc.initial, sc2, cd.baseClass.ctor, null, tthis, ArgumentList(), FuncResolveFlag.quiet);
731 if (!fd)
732 {
733 .error(funcdecl.loc, "%s `%s` no match for implicit `super()` call in constructor", funcdecl.kind, funcdecl.toPrettyChars);
734 }
735 else if (fd.storage_class & STC.disable)
736 {
737 .error(funcdecl.loc, "%s `%s` cannot call `super()` implicitly because it is annotated with `@disable`", funcdecl.kind, funcdecl.toPrettyChars);
738 }
739 else
740 {
741 Expression e1 = new SuperExp(Loc.initial);
742 Expression e = new CallExp(Loc.initial, e1);
743 e = e.expressionSemantic(sc2);
744 Statement s = new ExpStatement(Loc.initial, e);
745 funcdecl.fbody = new CompoundStatement(Loc.initial, s, funcdecl.fbody);
746 }
747 }
748 //printf("ctorflow.callSuper = x%x\n", sc2.ctorflow.callSuper);
749 }
750
751 /* https://issues.dlang.org/show_bug.cgi?id=17502
752 * Wait until after the return type has been inferred before
753 * generating the contracts for this function, and merging contracts
754 * from overrides.
755 *
756 * https://issues.dlang.org/show_bug.cgi?id=17893
757 * However should take care to generate this before inferered
758 * function attributes are applied, such as 'nothrow'.
759 *
760 * This was originally at the end of the first semantic pass, but
761 * required a fix-up to be done here for the '__result' variable
762 * type of __ensure() inside auto functions, but this didn't work
763 * if the out parameter was implicit.
764 */
765 funcdecl.buildEnsureRequire();
766
767 // Check for errors related to 'nothrow'.
768 const blockexit = funcdecl.fbody.blockExit(funcdecl, f.isNothrow ? global.errorSink : null);
769 if (f.isNothrow && blockexit & BE.throw_)
770 error(funcdecl.loc, "%s `%s` may throw but is marked as `nothrow`", funcdecl.kind(), funcdecl.toPrettyChars());
771
772 if (!(blockexit & (BE.throw_ | BE.halt) || funcdecl.hasCatches))
773 {
774 /* Don't generate unwind tables for this function
775 * https://issues.dlang.org/show_bug.cgi?id=17997
776 */
777 funcdecl.hasNoEH = true;
778 }
779
780 if (funcdecl.nothrowInprocess)
781 {
782 if (funcdecl.type == f)
783 f = cast(TypeFunction)f.copy();
784 f.isNothrow = !(blockexit & BE.throw_);
785 }
786
787 if (funcdecl.fbody.isErrorStatement())
788 {
789 }
790 else if (ad2 && funcdecl.isCtorDeclaration())
791 {
792 /* Append:
793 * return this;
794 * to function body
795 */
796 if (blockexit & BE.fallthru)
797 {
798 Statement s = new ReturnStatement(funcdecl.loc, null);
799 s = s.statementSemantic(sc2);
800 funcdecl.fbody = new CompoundStatement(funcdecl.loc, funcdecl.fbody, s);
801 funcdecl.hasMultipleReturnExp = funcdecl.hasReturnExp;
802 funcdecl.hasReturnExp = true;
803 }
804 }
805 else if (funcdecl.fes)
806 {
807 // For foreach(){} body, append a return 0;
808 if (blockexit & BE.fallthru)
809 {
810 Expression e = IntegerExp.literal!0;
811 Statement s = new ReturnStatement(Loc.initial, e);
812 funcdecl.fbody = new CompoundStatement(Loc.initial, funcdecl.fbody, s);
813 funcdecl.hasMultipleReturnExp = funcdecl.hasReturnExp;
814 funcdecl.hasReturnExp = true;
815 }
816 assert(!funcdecl.returnLabel);
817 }
818 else if (f.next.toBasetype().ty == Tnoreturn)
819 {
820 // Fallthrough despite being declared as noreturn? return is already rejected when evaluating the ReturnStatement
821 if (blockexit & BE.fallthru)
822 {
823 .error(funcdecl.loc, "%s `%s` is typed as `%s` but does return", funcdecl.kind, funcdecl.toPrettyChars, f.next.toChars());
824 funcdecl.loc.errorSupplemental("`noreturn` functions must either throw, abort or loop indefinitely");
825 }
826 }
827 else
828 {
829 if ((blockexit & BE.fallthru) && f.next.ty != Tvoid && !funcdecl.hasInlineAsm && !sc.inCfile)
830 {
831 if (!funcdecl.hasReturnExp)
832 .error(funcdecl.loc, "%s `%s` has no `return` statement, but is expected to return a value of type `%s`", funcdecl.kind, funcdecl.toPrettyChars, f.next.toChars());
833 else
834 .error(funcdecl.loc, "%s `%s` no `return exp;` or `assert(0);` at end of function", funcdecl.kind, funcdecl.toPrettyChars);
835 }
836 }
837
838 if (funcdecl.returns)
839 {
840 bool implicit0 = addReturn0();
841 Type tret = implicit0 ? Type.tint32 : f.next;
842 assert(tret.ty != Tvoid);
843 if (funcdecl.vresult || funcdecl.returnLabel)
844 funcdecl.buildResultVar(scout ? scout : sc2, tret);
845
846 /* Cannot move this loop into NrvoWalker, because
847 * returns[i] may be in the nested delegate for foreach-body.
848 */
849 for (size_t i = 0; i < funcdecl.returns.length; i++)
850 {
851 ReturnStatement rs = (*funcdecl.returns)[i];
852 Expression exp = rs.exp;
853 if (exp.op == EXP.error)
854 continue;
855 if (tret.ty == Terror)
856 {
857 // https://issues.dlang.org/show_bug.cgi?id=13702
858 exp = checkGC(sc2, exp);
859 continue;
860 }
861
862 /* If the expression in the return statement (exp) cannot be implicitly
863 * converted to the return type (tret) of the function and if the
864 * type of the expression is type isolated, then it may be possible
865 * that a promotion to `immutable` or `inout` (through a cast) will
866 * match the return type.
867 */
868 if (!exp.implicitConvTo(tret) && funcdecl.isTypeIsolated(exp.type))
869 {
870 /* https://issues.dlang.org/show_bug.cgi?id=20073
871 *
872 * The problem is that if the type of the returned expression (exp.type)
873 * is an aggregated declaration with an alias this, the alias this may be
874 * used for the conversion testing without it being an isolated type.
875 *
876 * To make sure this does not happen, we can test here the implicit conversion
877 * only for the aggregated declaration type by using `implicitConvToWithoutAliasThis`.
878 * The implicit conversion with alias this is taken care of later.
879 */
880 AggregateDeclaration aggDecl = isAggregate(exp.type);
881 TypeStruct tstruct;
882 TypeClass tclass;
883 bool hasAliasThis;
884 if (aggDecl && aggDecl.aliasthis)
885 {
886 hasAliasThis = true;
887 tclass = exp.type.isTypeClass();
888 if (!tclass)
889 tstruct = exp.type.isTypeStruct();
890 assert(tclass || tstruct);
891 }
892 if (hasAliasThis)
893 {
894 if (tclass)
895 {
896 if ((cast(TypeClass)(exp.type.immutableOf())).implicitConvToWithoutAliasThis(tret))
897 exp = exp.castTo(sc2, exp.type.immutableOf());
898 else if ((cast(TypeClass)(exp.type.wildOf())).implicitConvToWithoutAliasThis(tret))
899 exp = exp.castTo(sc2, exp.type.wildOf());
900 }
901 else
902 {
903 if ((cast(TypeStruct)exp.type.immutableOf()).implicitConvToWithoutAliasThis(tret))
904 exp = exp.castTo(sc2, exp.type.immutableOf());
905 else if ((cast(TypeStruct)exp.type.immutableOf()).implicitConvToWithoutAliasThis(tret))
906 exp = exp.castTo(sc2, exp.type.wildOf());
907 }
908 }
909 else
910 {
911 if (exp.type.immutableOf().implicitConvTo(tret))
912 exp = exp.castTo(sc2, exp.type.immutableOf());
913 else if (exp.type.wildOf().implicitConvTo(tret))
914 exp = exp.castTo(sc2, exp.type.wildOf());
915 }
916 }
917
918 // Function returns a reference
919 if (f.isRef)
920 {
921 if (!MODimplicitConv(exp.type.mod, tret.mod) && !tret.isTypeSArray())
922 error(exp.loc, "expression `%s` of type `%s` is not implicitly convertible to return type `ref %s`",
923 exp.toChars(), exp.type.toChars(), tret.toChars());
924 else
925 exp = exp.implicitCastTo(sc2, tret);
926
927 exp = exp.toLvalue(sc2, "`ref` return");
928 checkReturnEscapeRef(*sc2, exp, false);
929 exp = exp.optimize(WANTvalue, /*keepLvalue*/ true);
930 }
931 else
932 {
933 // if a copy constructor is present, the return type conversion will be handled by it
934 const hasCopyCtor = exp.type.ty == Tstruct && (cast(TypeStruct)exp.type).sym.hasCopyCtor;
935 if (!hasCopyCtor || !exp.isLvalue())
936 {
937 const errors = global.startGagging();
938 auto implicitlyCastedExp = exp.implicitCastTo(sc2, tret);
939 global.endGagging(errors);
940
941 // <https://github.com/dlang/dmd/issues/20888>
942 if (implicitlyCastedExp.isErrorExp())
943 {
944 auto types = toAutoQualChars(exp.type, tret);
945 error(
946 exp.loc,
947 "return value `%s` of type `%s` does not match return type `%s`"
948 ~ ", and cannot be implicitly converted",
949 exp.toErrMsg(),
950 types[0],
951 types[1],
952 );
953
954 if (const func = exp.type.isFunction_Delegate_PtrToFunction())
955 if (func.next.equals(tret))
956 errorSupplemental(
957 exp.loc,
958 "Did you intend to call the %s?",
959 (exp.type.isPtrToFunction())
960 ? "function pointer"
961 : exp.type.kind
962 );
963 }
964
965 exp = implicitlyCastedExp;
966 }
967
968 exp = exp.optimize(WANTvalue);
969
970 /* https://issues.dlang.org/show_bug.cgi?id=10789
971 * If NRVO is not possible, all returned lvalues should call their postblits.
972 */
973 if (!funcdecl.isNRVO())
974 exp = doCopyOrMove(sc2, exp, f.next, true, true);
975
976 if (tret.hasPointers())
977 checkReturnEscape(*sc2, exp, false);
978 }
979
980 exp = checkGC(sc2, exp);
981
982 if (funcdecl.vresult)
983 {
984 // Create: return vresult = exp;
985 exp = new BlitExp(rs.loc, funcdecl.vresult, exp);
986 exp.type = funcdecl.vresult.type;
987
988 if (rs.caseDim)
989 exp = Expression.combine(exp, new IntegerExp(rs.caseDim));
990 }
991 else if (funcdecl.tintro && !tret.equals(funcdecl.tintro.nextOf()))
992 {
993 exp = exp.implicitCastTo(sc2, funcdecl.tintro.nextOf());
994 }
995 rs.exp = exp;
996 }
997 }
998 if (funcdecl.nrvo_var || funcdecl.returnLabel)
999 {
1000 scope NrvoWalker nw = new NrvoWalker();
1001 nw.fd = funcdecl;
1002 nw.sc = sc2;
1003 nw.visitStmt(funcdecl.fbody);
1004 }
1005
1006 sc2 = sc2.pop();
1007 }
1008
1009 if (sc.previews.inclusiveInContracts)
1010 {
1011 funcdecl.frequire = funcdecl.mergeFrequireInclusivePreview(
1012 funcdecl.frequire, funcdecl.fdrequireParams);
1013 }
1014 else
1015 {
1016 funcdecl.frequire = funcdecl.mergeFrequire(funcdecl.frequire, funcdecl.fdrequireParams);
1017 }
1018 funcdecl.fensure = funcdecl.mergeFensure(funcdecl.fensure, Id.result, funcdecl.fdensureParams);
1019
1020 Statement freq = funcdecl.frequire;
1021 Statement fens = funcdecl.fensure;
1022
1023 /* Do the semantic analysis on the [in] preconditions and
1024 * [out] postconditions.
1025 */
1026 immutable bool isNothrow = f.isNothrow && !funcdecl.nothrowInprocess;
1027 if (freq)
1028 {
1029 /* frequire is composed of the [in] contracts
1030 */
1031 auto sym = new ScopeDsymbol(funcdecl.loc, null);
1032 sym.parent = sc2.scopesym;
1033 sym.endlinnum = funcdecl.endloc.linnum;
1034 sc2 = sc2.push(sym);
1035 sc2.contract = Contract.require;
1036
1037 // BUG: need to error if accessing out parameters
1038 // BUG: need to disallow returns
1039 // BUG: verify that all in and ref parameters are read
1040 freq = freq.statementSemantic(sc2);
1041
1042 const blockExit = freq.blockExit(funcdecl, null);
1043 if (blockExit & BE.throw_)
1044 {
1045 if (isNothrow)
1046 error(funcdecl.loc, "`%s`: `in` contract may throw but function is marked as `nothrow`",
1047 funcdecl.toPrettyChars());
1048 else if (funcdecl.nothrowInprocess)
1049 f.isNothrow = false;
1050 }
1051
1052 funcdecl.hasNoEH = false;
1053
1054 sc2 = sc2.pop();
1055
1056 if (global.params.useIn == CHECKENABLE.off)
1057 freq = null;
1058 }
1059
1060 if (fens)
1061 {
1062 /* fensure is composed of the [out] contracts
1063 */
1064 if (f.next.ty == Tvoid && funcdecl.fensures)
1065 {
1066 foreach (e; *funcdecl.fensures)
1067 {
1068 if (e.id)
1069 {
1070 .error(e.ensure.loc, "%s `%s` `void` functions have no result", funcdecl.kind, funcdecl.toPrettyChars);
1071 //fens = null;
1072 }
1073 }
1074 }
1075
1076 sc2 = scout; //push
1077 sc2.contract = Contract.ensure;
1078
1079 // BUG: need to disallow returns and throws
1080
1081 if (funcdecl.fensure && f.next.ty != Tvoid)
1082 funcdecl.buildResultVar(scout, f.next);
1083
1084 fens = fens.statementSemantic(sc2);
1085
1086 const blockExit = fens.blockExit(funcdecl, null);
1087 if (blockExit & BE.throw_)
1088 {
1089 if (isNothrow)
1090 error(funcdecl.loc, "`%s`: `out` contract may throw but function is marked as `nothrow`",
1091 funcdecl.toPrettyChars());
1092 else if (funcdecl.nothrowInprocess)
1093 f.isNothrow = false;
1094 }
1095
1096 funcdecl.hasNoEH = false;
1097
1098 sc2 = sc2.pop();
1099
1100 if (global.params.useOut == CHECKENABLE.off)
1101 fens = null;
1102 }
1103 if (funcdecl.fbody && funcdecl.fbody.isErrorStatement())
1104 {
1105 }
1106 else
1107 {
1108 auto a = new Statements();
1109 // Merge in initialization of 'out' parameters
1110 if (funcdecl.parameters)
1111 {
1112 for (size_t i = 0; i < funcdecl.parameters.length; i++)
1113 {
1114 VarDeclaration v = (*funcdecl.parameters)[i];
1115 if (v.storage_class & STC.out_)
1116 {
1117 if (!v._init)
1118 {
1119 .error(v.loc, "%s `%s` zero-length `out` parameters are not allowed.", v.kind, v.toPrettyChars);
1120 return;
1121 }
1122 ExpInitializer ie = v._init.isExpInitializer();
1123 assert(ie);
1124 if (auto iec = ie.exp.isConstructExp())
1125 {
1126 // construction occurred in parameter processing
1127 auto ec = new AssignExp(iec.loc, iec.e1, iec.e2);
1128 ec.type = iec.type;
1129 ie.exp = ec;
1130 }
1131 a.push(new ExpStatement(Loc.initial, ie.exp));
1132 }
1133 }
1134 }
1135
1136 if (_arguments)
1137 {
1138 /* Advance to elements[] member of TypeInfo_Tuple with:
1139 * _arguments = v_arguments.elements;
1140 */
1141 Expression e = new VarExp(Loc.initial, funcdecl.v_arguments);
1142 e = new DotIdExp(Loc.initial, e, Id.elements);
1143 e = new ConstructExp(Loc.initial, _arguments, e);
1144 e = e.expressionSemantic(sc2);
1145
1146 _arguments._init = new ExpInitializer(Loc.initial, e);
1147 auto de = new DeclarationExp(Loc.initial, _arguments);
1148 a.push(new ExpStatement(Loc.initial, de));
1149 }
1150
1151 // Merge contracts together with body into one compound statement
1152
1153 if (freq || fpreinv)
1154 {
1155 if (!freq)
1156 freq = fpreinv;
1157 else if (fpreinv)
1158 freq = new CompoundStatement(Loc.initial, freq, fpreinv);
1159
1160 a.push(freq);
1161 }
1162
1163 if (funcdecl.fbody)
1164 a.push(funcdecl.fbody);
1165
1166 if (fens || fpostinv)
1167 {
1168 if (!fens)
1169 fens = fpostinv;
1170 else if (fpostinv)
1171 fens = new CompoundStatement(Loc.initial, fpostinv, fens);
1172
1173 auto ls = new LabelStatement(Loc.initial, Id.returnLabel, fens);
1174 funcdecl.returnLabel.statement = ls;
1175 a.push(funcdecl.returnLabel.statement);
1176
1177 if (f.next.ty != Tvoid && funcdecl.vresult)
1178 {
1179 // Create: return vresult;
1180 Expression e = new VarExp(Loc.initial, funcdecl.vresult);
1181 if (funcdecl.tintro)
1182 {
1183 e = e.implicitCastTo(sc, funcdecl.tintro.nextOf());
1184 e = e.expressionSemantic(sc);
1185 }
1186 auto s = new ReturnStatement(Loc.initial, e);
1187 a.push(s);
1188 }
1189 }
1190 if (addReturn0())
1191 {
1192 // Add a return 0; statement
1193 Statement s = new ReturnStatement(Loc.initial, IntegerExp.literal!0);
1194 a.push(s);
1195 }
1196
1197 Statement sbody = new CompoundStatement(Loc.initial, a);
1198
1199 /* Append destructor calls for parameters as finally blocks.
1200 */
1201 if (funcdecl.parameters)
1202 {
1203 // check if callee destroys arguments
1204 const bool paramsNeedDtor = target.isCalleeDestroyingArgs(f);
1205
1206 foreach (v; *funcdecl.parameters)
1207 {
1208 if (v.isReference() || (v.storage_class & STC.lazy_))
1209 continue;
1210 if (!v.needsScopeDtor())
1211 continue;
1212 v.storage_class |= STC.nodtor;
1213 if (!paramsNeedDtor)
1214 continue;
1215
1216 // same with ExpStatement.scopeCode()
1217 Statement s = new DtorExpStatement(Loc.initial, v.edtor, v);
1218
1219 s = s.statementSemantic(sc2);
1220
1221 const blockexit = s.blockExit(funcdecl, isNothrow ? global.errorSink : null);
1222 if (blockexit & BE.throw_)
1223 {
1224 funcdecl.hasNoEH = false;
1225 if (isNothrow)
1226 error(funcdecl.loc, "%s `%s` may throw but is marked as `nothrow`", funcdecl.kind(), funcdecl.toPrettyChars());
1227 else if (funcdecl.nothrowInprocess)
1228 f.isNothrow = false;
1229 }
1230
1231 if (sbody.blockExit(funcdecl, f.isNothrow ? global.errorSink : null) == BE.fallthru)
1232 sbody = new CompoundStatement(Loc.initial, sbody, s);
1233 else
1234 sbody = new TryFinallyStatement(Loc.initial, sbody, s);
1235 }
1236 }
1237 // from this point on all possible 'throwers' are checked
1238 funcdecl.nothrowInprocess = false;
1239
1240 if (funcdecl.isSynchronized())
1241 {
1242 /* Wrap the entire function body in a synchronized statement
1243 */
1244 if (ClassDeclaration cd = funcdecl.toParentDecl().isClassDeclaration())
1245 {
1246 if (target.libraryObjectMonitors(funcdecl, sbody))
1247 {
1248 Expression vsync;
1249 if (funcdecl.isStatic())
1250 {
1251 // The monitor is in the ClassInfo
1252 vsync = new DotIdExp(funcdecl.loc, symbolToExp(cd, funcdecl.loc, sc2, false), Id.classinfo);
1253 }
1254 else
1255 {
1256 // 'this' is the monitor
1257 vsync = new VarExp(funcdecl.loc, funcdecl.vthis);
1258 if (funcdecl.hasDualContext())
1259 {
1260 vsync = new PtrExp(funcdecl.loc, vsync);
1261 vsync = new IndexExp(funcdecl.loc, vsync, IntegerExp.literal!0);
1262 }
1263 }
1264 sbody = new PeelStatement(sbody); // don't redo semantic()
1265 sbody = new SynchronizedStatement(funcdecl.loc, vsync, sbody);
1266 sbody = sbody.statementSemantic(sc2);
1267 }
1268 }
1269 else
1270 {
1271 .error(funcdecl.loc, "%s `%s` synchronized function `%s` must be a member of a class", funcdecl.kind, funcdecl.toPrettyChars, funcdecl.toChars());
1272 }
1273 }
1274
1275 // If declaration has no body, don't set sbody to prevent incorrect codegen.
1276 if (funcdecl.fbody || funcdecl.allowsContractWithoutBody())
1277 funcdecl.fbody = sbody;
1278 }
1279
1280 // Check for undefined labels
1281 if (funcdecl.labtab)
1282 foreach (keyValue; funcdecl.labtab.tab.asRange)
1283 {
1284 //printf(" KV: %s = %s\n", keyValue.key.toChars(), keyValue.value.toChars());
1285 LabelDsymbol label = cast(LabelDsymbol)keyValue.value;
1286 if (!label.statement && (!label.deleted || label.iasm))
1287 {
1288 .error(label.loc, "%s `%s` label `%s` is undefined", funcdecl.kind, funcdecl.toPrettyChars, label.toChars());
1289 }
1290 }
1291
1292 // Fix up forward-referenced gotos
1293 if (funcdecl.gotos && !funcdecl.isCsymbol())
1294 {
1295 for (size_t i = 0; i < funcdecl.gotos.length; ++i)
1296 {
1297 (*funcdecl.gotos)[i].checkLabel();
1298 }
1299 }
1300
1301 if (funcdecl.isNaked() && (funcdecl.fensures || funcdecl.frequires))
1302 .error(funcdecl.loc, "%s `%s` naked assembly functions with contracts are not supported", funcdecl.kind, funcdecl.toPrettyChars);
1303
1304 sc2.ctorflow.callSuper = CSX.none;
1305 sc2.pop();
1306 }
1307
1308 if (funcdecl.checkClosure())
1309 {
1310 // We should be setting errors here instead of relying on the global error count.
1311 //errors = true;
1312 }
1313
1314 /* If function survived being marked as impure, then it is pure
1315 */
1316 if (funcdecl.purityInprocess)
1317 {
1318 funcdecl.purityInprocess = false;
1319 if (funcdecl.type == f)
1320 f = cast(TypeFunction)f.copy();
1321 f.purity = PURE.fwdref;
1322 }
1323
1324 if (funcdecl.safetyInprocess)
1325 {
1326 funcdecl.safetyInprocess = false;
1327 if (funcdecl.type == f)
1328 f = cast(TypeFunction)f.copy();
1329 f.trust = TRUST.safe;
1330 }
1331
1332 if (funcdecl.nogcInprocess)
1333 {
1334 funcdecl.nogcInprocess = false;
1335 if (funcdecl.type == f)
1336 f = cast(TypeFunction)f.copy();
1337 f.isNogc = true;
1338 }
1339
1340 finishScopeParamInference(funcdecl, f);
1341
1342 // reset deco to apply inference result to mangled name
1343 if (f != funcdecl.type)
1344 f.deco = null;
1345
1346 // Do semantic type AFTER pure/nothrow inference.
1347 if (!f.deco && funcdecl.ident != Id.xopEquals && funcdecl.ident != Id.xopCmp)
1348 {
1349 sc = sc.push();
1350 if (funcdecl.isCtorDeclaration()) // https://issues.dlang.org/show_bug.cgi?id=#15665
1351 f.isCtor = true;
1352 sc.stc = STC.none;
1353 sc.linkage = funcdecl._linkage; // https://issues.dlang.org/show_bug.cgi?id=8496
1354 funcdecl.type = f.typeSemantic(funcdecl.loc, sc);
1355 sc = sc.pop();
1356 }
1357
1358 // Check `extern(C++)` functions for invalid the return/parameter types
1359 if (funcdecl._linkage == LINK.cpp)
1360 {
1361 static bool isCppNonMappableType(Type type, Parameter param = null, Type origType = null)
1362 {
1363 // Don't allow D `immutable` and `shared` types to be interfaced with C++
1364 if (type.isImmutable() || type.isShared())
1365 return true;
1366 if (Type cpptype = target.cpp.parameterType(type))
1367 type = cpptype;
1368
1369 if (origType is null)
1370 origType = type;
1371
1372 // Permit types that are handled by toCppMangle. This list should be kept in sync with
1373 // each visit method in dmd.cppmangle and dmd.cppmanglewin.
1374 switch (type.ty)
1375 {
1376 case Tnull:
1377 case Tnoreturn:
1378 case Tvector:
1379 case Tpointer:
1380 case Treference:
1381 case Tfunction:
1382 case Tstruct:
1383 case Tenum:
1384 case Tclass:
1385 case Tident:
1386 case Tinstance:
1387 break;
1388
1389 case Tsarray:
1390 if (!origType.isTypePointer())
1391 return true;
1392 break;
1393
1394 default:
1395 if (!type.isTypeBasic())
1396 return true;
1397 break;
1398 }
1399
1400 // Descend to the enclosing type
1401 if (auto tnext = type.nextOf())
1402 return isCppNonMappableType(tnext, param, origType);
1403
1404 return false;
1405 }
1406 if (isCppNonMappableType(f.next.toBasetype()))
1407 {
1408 .error(funcdecl.loc, "%s `%s` cannot return type `%s` because its linkage is `extern(C++)`", funcdecl.kind, funcdecl.toErrMsg(), f.next.toChars());
1409 if (f.next.isTypeDArray())
1410 errorSupplemental(funcdecl.loc, "slices are specific to D and do not have a counterpart representation in C++", f.next.toChars());
1411 funcdecl.errors = true;
1412 }
1413 foreach (i, param; f.parameterList)
1414 {
1415 if (isCppNonMappableType(param.type.toBasetype(), param))
1416 {
1417 .error(funcdecl.loc, "%s `%s` cannot have parameter of type `%s` because its linkage is `extern(C++)`", funcdecl.kind, funcdecl.toErrMsg(), param.type.toChars());
1418 if (param.type.toBasetype().isTypeSArray())
1419 errorSupplemental(funcdecl.loc, "perhaps use a `%s*` type instead",
1420 param.type.nextOf().mutableOf().unSharedOf().toChars());
1421 funcdecl.errors = true;
1422 }
1423 }
1424 }
1425
1426 // Do live analysis
1427 if (sc.previews.dip1021 && funcdecl.fbody && funcdecl.type.ty != Terror &&
1428 funcdecl.type.isTypeFunction().isLive)
1429 {
1430 oblive(funcdecl);
1431 }
1432
1433 /* If this function had instantiated with gagging, error reproduction will be
1434 * done by TemplateInstance::semantic.
1435 * Otherwise, error gagging should be temporarily ungagged by functionSemantic3.
1436 */
1437 funcdecl.semanticRun = PASS.semantic3done;
1438 if ((global.errors != oldErrors) || (funcdecl.fbody && funcdecl.fbody.isErrorStatement()))
1439 funcdecl.hasSemantic3Errors = true;
1440 else
1441 funcdecl.hasSemantic3Errors = false;
1442 if (funcdecl.type.ty == Terror)
1443 funcdecl.errors = true;
1444 //printf("-FuncDeclaration::semantic3('%s.%s', sc = %p, loc = %s)\n", funcdecl.parent.toChars(), funcdecl.toChars(), sc, funcdecl.loc.toChars());
1445 //fflush(stdout);
1446 }
1447
1448 override void visit(CtorDeclaration ctor)
1449 {
1450 //printf("CtorDeclaration()\n%s\n", ctor.fbody.toChars());
1451 if (ctor.semanticRun >= PASS.semantic3)
1452 return;
1453
1454 /* If any of the fields of the aggregate have a destructor, add
1455 * scope (failure) { this.fieldDtor(); }
1456 * as the first statement of the constructor (unless the constructor
1457 * doesn't define a body - @disable, extern)
1458 *.It is not necessary to add it after
1459 * each initialization of a field, because destruction of .init constructed
1460 * structs should be benign.
1461 * https://issues.dlang.org/show_bug.cgi?id=14246
1462 */
1463 AggregateDeclaration ad = ctor.isMemberDecl();
1464 if (!ctor.fbody || !ad || !ad.fieldDtor ||
1465 global.params.dtorFields == FeatureState.disabled || !global.params.useExceptions || ctor.type.toTypeFunction.isNothrow)
1466 return visit(cast(FuncDeclaration)ctor);
1467
1468 /* Generate:
1469 * this.fieldDtor()
1470 */
1471 Expression e = new ThisExp(ctor.loc);
1472 e.type = ad.type.mutableOf();
1473 e = new DotVarExp(ctor.loc, e, ad.fieldDtor, false);
1474 auto ce = new CallExp(ctor.loc, e);
1475 auto sexp = new ExpStatement(ctor.loc, ce);
1476 auto ss = new ScopeStatement(ctor.loc, sexp, ctor.loc);
1477
1478 if (global.params.dtorFields == FeatureState.default_)
1479 {
1480 auto ctf = cast(TypeFunction) ctor.type;
1481 auto dtf = cast(TypeFunction) ad.fieldDtor.type;
1482
1483 const ngErr = ctf.isNogc && !dtf.isNogc;
1484 const puErr = ctf.purity && !dtf.purity;
1485 const saErr = ctf.trust == TRUST.safe && dtf.trust <= TRUST.system;
1486
1487 if (ngErr || puErr || saErr)
1488 {
1489 // storage_class is apparently not set for dtor & ctor
1490 OutBuffer ob;
1491 stcToBuffer(ob,
1492 (ngErr ? STC.nogc : STC.none) |
1493 (puErr ? STC.pure_ : STC.none) |
1494 (saErr ? STC.system : STC.none)
1495 );
1496 ctor.loc.error("`%s` has stricter attributes than its destructor (`%s`)", ctor.toPrettyChars(), ob.peekChars());
1497 ctor.loc.errorSupplemental("The destructor will be called if an exception is thrown");
1498 ctor.loc.errorSupplemental("Either make the constructor `nothrow` or adjust the field destructors");
1499
1500 ce.ignoreAttributes = true;
1501 }
1502 }
1503
1504 version (all)
1505 {
1506 /* Generate:
1507 * try { ctor.fbody; }
1508 * catch (Exception __o)
1509 * { this.fieldDtor(); throw __o; }
1510 * This differs from the alternate scope(failure) version in that an Exception
1511 * is caught rather than a Throwable. This enables the optimization whereby
1512 * the try-catch can be removed if ctor.fbody is nothrow. (nothrow only
1513 * applies to Exception.)
1514 */
1515 Identifier id = Identifier.generateId("__o");
1516 auto ts = new ThrowStatement(ctor.loc, new IdentifierExp(ctor.loc, id));
1517 auto handler = new CompoundStatement(ctor.loc, ss, ts);
1518
1519 auto catches = new Catches();
1520 auto ctch = new Catch(ctor.loc, getException(), id, handler);
1521 catches.push(ctch);
1522
1523 ctor.fbody = new TryCatchStatement(ctor.loc, ctor.fbody, catches);
1524 }
1525 else
1526 {
1527 /* Generate:
1528 * scope (failure) { this.fieldDtor(); }
1529 * Hopefully we can use this version someday when scope(failure) catches
1530 * Exception instead of Throwable.
1531 */
1532 auto s = new ScopeGuardStatement(ctor.loc, TOK.onScopeFailure, ss);
1533 ctor.fbody = new CompoundStatement(ctor.loc, s, ctor.fbody);
1534 }
1535 visit(cast(FuncDeclaration)ctor);
1536 }
1537
1538
1539 override void visit(Nspace ns)
1540 {
1541 if (ns.semanticRun >= PASS.semantic3)
1542 return;
1543 ns.semanticRun = PASS.semantic3;
1544 static if (LOG)
1545 {
1546 printf("Nspace::semantic3('%s')\n", ns.toChars());
1547 }
1548 if (!ns.members)
1549 return;
1550
1551 sc = sc.push(ns);
1552 sc.linkage = LINK.cpp;
1553 foreach (s; *ns.members)
1554 {
1555 s.semantic3(sc);
1556 }
1557 sc.pop();
1558 }
1559
1560 override void visit(AttribDeclaration ad)
1561 {
1562 Dsymbols* d = ad.include(sc);
1563 if (!d)
1564 return;
1565
1566 Scope* sc2 = ad.newScope(sc);
1567 for (size_t i = 0; i < d.length; i++)
1568 {
1569 Dsymbol s = (*d)[i];
1570 s.semantic3(sc2);
1571 }
1572 if (sc2 != sc)
1573 sc2.pop();
1574 }
1575
1576 override void visit(AggregateDeclaration ad)
1577 {
1578 //printf("AggregateDeclaration::semantic3(sc=%p, %s) type = %s, errors = %d\n", sc, toChars(), type.toChars(), errors);
1579 if (!ad.members)
1580 return;
1581
1582 StructDeclaration sd = ad.isStructDeclaration();
1583 if (!sc) // from runDeferredSemantic3 for TypeInfo generation
1584 {
1585 assert(sd);
1586 sd.semanticTypeInfoMembers();
1587 return;
1588 }
1589
1590 auto sc2 = ad.newScope(sc);
1591
1592 for (size_t i = 0; i < ad.members.length; i++)
1593 {
1594 Dsymbol s = (*ad.members)[i];
1595 s.semantic3(sc2);
1596 }
1597
1598 sc2.pop();
1599
1600 // Instantiate RTInfo!S to provide a pointer bitmap for the GC
1601 // Don't do it in -betterC or on unused deprecated / error types
1602 if (!ad.getRTInfo && global.params.useTypeInfo && Type.rtinfo &&
1603 (!ad.isDeprecated() || global.params.useDeprecated != DiagnosticReporting.error) &&
1604 (ad.type && ad.type.ty != Terror))
1605 {
1606 // Evaluate: RTinfo!type
1607 auto tiargs = new Objects();
1608 tiargs.push(ad.type);
1609 auto ti = new TemplateInstance(ad.loc, Type.rtinfo, tiargs);
1610
1611 Scope* sc3 = ti.tempdecl._scope.startCTFE();
1612 sc3.tinst = sc.tinst;
1613 sc3.minst = sc.minst;
1614 if (ad.isDeprecated())
1615 sc3.stc |= STC.deprecated_;
1616
1617 ti.dsymbolSemantic(sc3);
1618 ti.semantic2(sc3);
1619 ti.semantic3(sc3);
1620 auto e = symbolToExp(ti.toAlias(), Loc.initial, sc3, false);
1621
1622 sc3.endCTFE();
1623
1624 e = e.ctfeInterpret();
1625 ad.getRTInfo = e;
1626 }
1627 if (sd)
1628 sd.semanticTypeInfoMembers();
1629 ad.semanticRun = PASS.semantic3done;
1630 }
1631 }
1632
1633 private struct FuncDeclSem3
1634 {
1635 // The FuncDeclaration subject to Semantic analysis
1636 FuncDeclaration funcdecl;
1637
1638 // Scope of analysis
1639 Scope* sc;
1640 this(FuncDeclaration fd,Scope* s) scope @safe
1641 {
1642 funcdecl = fd;
1643 sc = s;
1644 }
1645
1646 /* Checks that the overridden functions (if any) have in contracts if
1647 * funcdecl has an in contract.
1648 */
1649 void checkInContractOverrides()
1650 {
1651 if (funcdecl.frequires)
1652 {
1653 for (size_t i = 0; i < funcdecl.foverrides.length; i++)
1654 {
1655 FuncDeclaration fdv = funcdecl.foverrides[i];
1656 if (fdv.fbody && !fdv.frequires)
1657 {
1658 .error(funcdecl.loc, "%s `%s` cannot have an in contract when overridden function `%s` does not have an in contract", funcdecl.kind, funcdecl.toPrettyChars, fdv.toPrettyChars());
1659 break;
1660 }
1661 }
1662 }
1663 }
1664 }
1665
1666 void semanticTypeInfoMembers(StructDeclaration sd)
1667 {
1668 if (sd.xeq &&
1669 sd.xeq._scope &&
1670 sd.xeq.semanticRun < PASS.semantic3done)
1671 {
1672 const errors = global.startGagging();
1673 sd.xeq.semantic3(sd.xeq._scope);
1674 if (global.endGagging(errors))
1675 sd.xeq = sd.xerreq;
1676 }
1677
1678 if (sd.xcmp &&
1679 sd.xcmp._scope &&
1680 sd.xcmp.semanticRun < PASS.semantic3done)
1681 {
1682 const errors = global.startGagging();
1683 sd.xcmp.semantic3(sd.xcmp._scope);
1684 if (global.endGagging(errors))
1685 sd.xcmp = sd.xerrcmp;
1686 }
1687
1688 FuncDeclaration ftostr = search_toString(sd);
1689 if (ftostr &&
1690 ftostr._scope &&
1691 ftostr.semanticRun < PASS.semantic3done)
1692 {
1693 ftostr.semantic3(ftostr._scope);
1694 }
1695
1696 if (sd.xhash &&
1697 sd.xhash._scope &&
1698 sd.xhash.semanticRun < PASS.semantic3done)
1699 {
1700 sd.xhash.semantic3(sd.xhash._scope);
1701 }
1702
1703 if (sd.postblit &&
1704 sd.postblit._scope &&
1705 sd.postblit.semanticRun < PASS.semantic3done)
1706 {
1707 sd.postblit.semantic3(sd.postblit._scope);
1708 }
1709
1710 if (sd.dtor &&
1711 sd.dtor._scope &&
1712 sd.dtor.semanticRun < PASS.semantic3done)
1713 {
1714 sd.dtor.semantic3(sd.dtor._scope);
1715 }
1716 }
1717
1718 /***********************************************
1719 * Check that the function contains any closure.
1720 * If it's @nogc, report suitable errors.
1721 * This is mostly consistent with FuncDeclaration::needsClosure().
1722 *
1723 * Returns:
1724 * true if any errors occur.
1725 */
1726 extern (D) bool checkClosure(FuncDeclaration fd)
1727 {
1728 //printf("checkClosure() %s\n", toPrettyChars());
1729 if (!fd.needsClosure())
1730 return false;
1731
1732 if (fd.setGC(fd.loc, "allocating a closure for `%s()`", fd))
1733 {
1734 .error(fd.loc, "%s `%s` is `@nogc` yet allocates closure for `%s()` with the GC", fd.kind, fd.toPrettyChars(), fd.toChars());
1735 if (global.gag) // need not report supplemental errors
1736 return true;
1737 }
1738 else if (!global.params.useGC)
1739 {
1740 .error(fd.loc, "%s `%s` is `-betterC` yet allocates closure for `%s()` with the GC", fd.kind, fd.toPrettyChars(), fd.toChars());
1741 if (global.gag) // need not report supplemental errors
1742 return true;
1743 }
1744 else
1745 {
1746 fd.printGCUsage(fd.loc, "using closure causes GC allocation");
1747 return false;
1748 }
1749
1750 FuncDeclarations a;
1751 foreach (v; fd.closureVars)
1752 {
1753 foreach (f; v.nestedrefs)
1754 {
1755 assert(f !is fd);
1756
1757 LcheckAncestorsOfANestedRef:
1758 for (Dsymbol s = f; s && s !is fd; s = s.toParentP(fd))
1759 {
1760 auto fx = s.isFuncDeclaration();
1761 if (!fx)
1762 continue;
1763 if (fx.isThis() ||
1764 fx.tookAddressOf ||
1765 checkEscapingSiblings(fx, fd))
1766 {
1767 foreach (f2; a)
1768 {
1769 if (f2 == f)
1770 break LcheckAncestorsOfANestedRef;
1771 }
1772 a.push(f);
1773 .errorSupplemental(f.loc, "%s `%s` closes over variable `%s`",
1774 f.kind, f.toErrMsg(), v.toChars());
1775 if (v.ident != Id.This)
1776 .errorSupplemental(v.loc, "`%s` declared here", v.toChars());
1777
1778 break LcheckAncestorsOfANestedRef;
1779 }
1780 }
1781 }
1782 }
1783
1784 return true;
1785 }