Debian Codegraph @

gcc/d/dmd/pragmasem.d

raw
1 /**
2 * Does semantic analysis for pragmas.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/pragma.html, Pragmas)
5 *
6 * Copyright: Copyright (C) 1999-2023 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/pragmasem.d, _pragmasem.d)
10 * Documentation: https://dlang.org/phobos/dmd_pragmasem.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/pragmasem.d
12 */
13
14 module dmd.pragmasem;
15
16 import core.stdc.stdio;
17
18 import dmd.astenums;
19 import dmd.arraytypes;
20 import dmd.attrib;
21 import dmd.dinterpret;
22 import dmd.dscope;
23 import dmd.dsymbol;
24 import dmd.dsymbolsem : include;
25 import dmd.errors;
26 import dmd.expression;
27 import dmd.expressionsem;
28 import dmd.globals;
29 import dmd.location;
30 import dmd.id;
31 import dmd.statement;
32
33 /**
34 * Run semantic on `pragma` declaration.
35 *
36 * Params:
37 * pd = pragma declaration or statement to evaluate
38 * sc = enclosing scope
39 */
40 void pragmaDeclSemantic(PragmaDeclaration pd, Scope* sc)
41 {
42 import dmd.aggregate;
43 import dmd.common.outbuffer;
44 import dmd.dmodule;
45 import dmd.dsymbolsem;
46 import dmd.identifier;
47 import dmd.mangle : isValidMangling;
48 import dmd.root.rmem;
49 import dmd.root.utf;
50 import dmd.target;
51 import dmd.utils;
52
53 StringExp verifyMangleString(ref Expression e)
54 {
55 auto se = semanticString(sc, e, "mangled name");
56 if (!se)
57 return null;
58 e = se;
59 if (!se.len)
60 {
61 .error(pd.loc, "%s `%s` - zero-length string not allowed for mangled name", pd.kind, pd.toPrettyChars);
62 return null;
63 }
64 if (se.sz != 1)
65 {
66 .error(pd.loc, "%s `%s` - mangled name characters can only be of type `char`", pd.kind, pd.toPrettyChars);
67 return null;
68 }
69 version (all)
70 {
71 import dmd.common.charactertables;
72
73 /* Note: D language specification should not have any assumption about backend
74 * implementation. Ideally pragma(mangle) can accept a string of any content.
75 *
76 * Therefore, this validation is compiler implementation specific.
77 */
78 auto slice = se.peekString();
79 for (size_t i = 0; i < se.len;)
80 {
81 dchar c = slice[i];
82 if (c < 0x80)
83 {
84 if (c.isValidMangling)
85 {
86 ++i;
87 continue;
88 }
89 else
90 {
91 .error(pd.loc, "%s `%s` char 0x%02x not allowed in mangled name", pd.kind, pd.toPrettyChars, c);
92 break;
93 }
94 }
95 if (const msg = utf_decodeChar(slice, i, c))
96 {
97 .error(pd.loc, "%s `%s` %.*s", pd.kind, pd.toPrettyChars, cast(int)msg.length, msg.ptr);
98 break;
99 }
100 if (!isAnyIdentifierCharacter(c))
101 {
102 .error(pd.loc, "%s `%s` char `0x%04x` not allowed in mangled name", pd.kind, pd.toPrettyChars, c);
103 break;
104 }
105 }
106 }
107 return se;
108 }
109 void declarations()
110 {
111 if (!pd.decl)
112 return;
113
114 Scope* sc2 = pd.newScope(sc);
115 scope(exit)
116 if (sc2 != sc)
117 sc2.pop();
118
119 foreach (s; (*pd.decl)[])
120 {
121 if (pd.ident == Id.printf || pd.ident == Id.scanf)
122 {
123 s.setPragmaPrintf(pd.ident == Id.printf);
124 s.dsymbolSemantic(sc2);
125 continue;
126 }
127
128 s.dsymbolSemantic(sc2);
129 if (pd.ident != Id.mangle)
130 continue;
131 assert(pd.args);
132 if (auto ad = s.isAggregateDeclaration())
133 {
134 Expression e = (*pd.args)[0];
135 sc2 = sc2.startCTFE();
136 e = e.expressionSemantic(sc);
137 e = resolveProperties(sc2, e);
138 sc2 = sc2.endCTFE();
139 AggregateDeclaration agg;
140 if (auto tc = e.type.isTypeClass())
141 agg = tc.sym;
142 else if (auto ts = e.type.isTypeStruct())
143 agg = ts.sym;
144 ad.pMangleOverride = new MangleOverride;
145 void setString(ref Expression e)
146 {
147 if (auto se = verifyMangleString(e))
148 {
149 const name = (cast(const(char)[])se.peekData()).xarraydup;
150 ad.pMangleOverride.id = Identifier.idPool(name);
151 e = se;
152 }
153 else
154 error(e.loc, "must be a string");
155 }
156 if (agg)
157 {
158 ad.pMangleOverride.agg = agg;
159 if (pd.args.length == 2)
160 {
161 setString((*pd.args)[1]);
162 }
163 else
164 ad.pMangleOverride.id = agg.ident;
165 }
166 else
167 setString((*pd.args)[0]);
168 }
169 else if (auto td = s.isTemplateDeclaration())
170 {
171 .error(pd.loc, "%s `%s` cannot apply to a template declaration", pd.kind, pd.toPrettyChars);
172 errorSupplemental(pd.loc, "use `template Class(Args...){ pragma(mangle, \"other_name\") class Class {} }`");
173 }
174 else if (auto se = verifyMangleString((*pd.args)[0]))
175 {
176 const name = (cast(const(char)[])se.peekData()).xarraydup;
177 uint cnt = setMangleOverride(s, name);
178 if (cnt > 1)
179 .error(pd.loc, "%s `%s` can only apply to a single declaration", pd.kind, pd.toPrettyChars);
180 }
181 }
182 }
183
184 void noDeclarations()
185 {
186 if (pd.decl)
187 {
188 .error(pd.loc, "%s `%s` is missing a terminating `;`", pd.kind, pd.toPrettyChars);
189 declarations();
190 // do them anyway, to avoid segfaults.
191 }
192 }
193
194 // Should be merged with PragmaStatement
195 //printf("\tpragmaDeclSemantic '%s'\n", pd.toChars());
196 if (target.supportsLinkerDirective())
197 {
198 if (pd.ident == Id.linkerDirective)
199 {
200 if (!pd.args || pd.args.length != 1)
201 .error(pd.loc, "%s `%s` one string argument expected for pragma(linkerDirective)", pd.kind, pd.toPrettyChars);
202 else
203 {
204 auto se = semanticString(sc, (*pd.args)[0], "linker directive");
205 if (!se)
206 return noDeclarations();
207 (*pd.args)[0] = se;
208 if (global.params.v.verbose)
209 message("linkopt %.*s", cast(int)se.len, se.peekString().ptr);
210 }
211 return noDeclarations();
212 }
213 }
214 if (pd.ident == Id.msg)
215 {
216 if (!pd.args)
217 return noDeclarations();
218
219 if (!pragmaMsgSemantic(pd.loc, sc, pd.args))
220 return;
221
222 return noDeclarations();
223 }
224 else if (pd.ident == Id.lib)
225 {
226 if (!pd.args || pd.args.length != 1)
227 .error(pd.loc, "%s `%s` string expected for library name", pd.kind, pd.toPrettyChars);
228 else
229 {
230 auto se = semanticString(sc, (*pd.args)[0], "library name");
231 if (!se)
232 return noDeclarations();
233 (*pd.args)[0] = se;
234
235 auto name = se.peekString().xarraydup;
236 if (global.params.v.verbose)
237 message("library %s", name.ptr);
238 if (global.params.moduleDeps.buffer && !global.params.moduleDeps.name)
239 {
240 OutBuffer* ob = global.params.moduleDeps.buffer;
241 Module imod = sc._module;
242 ob.writestring("depsLib ");
243 ob.writestring(imod.toPrettyChars());
244 ob.writestring(" (");
245 escapePath(ob, imod.srcfile.toChars());
246 ob.writestring(") : ");
247 ob.writestring(name);
248 ob.writenl();
249 }
250 mem.xfree(name.ptr);
251 }
252 return noDeclarations();
253 }
254 else if (pd.ident == Id.startaddress)
255 {
256 pragmaStartAddressSemantic(pd.loc, sc, pd.args);
257 return noDeclarations();
258 }
259 else if (pd.ident == Id.Pinline)
260 {
261 // this pragma now gets evaluated on demand in function semantic
262
263 return declarations();
264 }
265 else if (pd.ident == Id.mangle)
266 {
267 if (!pd.args)
268 pd.args = new Expressions();
269 if (pd.args.length == 0 || pd.args.length > 2)
270 {
271 .error(pd.loc, pd.args.length == 0 ? "%s `%s` - string expected for mangled name"
272 : "%s `%s` expected 1 or 2 arguments", pd.kind, pd.toPrettyChars);
273 pd.args.setDim(1);
274 (*pd.args)[0] = ErrorExp.get(); // error recovery
275 }
276 return declarations();
277 }
278 else if (pd.ident == Id.crt_constructor || pd.ident == Id.crt_destructor)
279 {
280 if (pd.args && pd.args.length != 0)
281 .error(pd.loc, "%s `%s` takes no argument", pd.kind, pd.toPrettyChars);
282 else
283 {
284 immutable isCtor = pd.ident == Id.crt_constructor;
285
286 static uint recurse(Dsymbol s, bool isCtor)
287 {
288 if (auto ad = s.isAttribDeclaration())
289 {
290 uint nestedCount;
291 auto decls = ad.include(null);
292 if (decls)
293 {
294 for (size_t i = 0; i < decls.length; ++i)
295 nestedCount += recurse((*decls)[i], isCtor);
296 }
297 return nestedCount;
298 }
299 else if (auto f = s.isFuncDeclaration())
300 {
301 if (isCtor)
302 f.isCrtCtor = true;
303 else
304 f.isCrtDtor = true;
305
306 return 1;
307 }
308 else
309 return 0;
310 assert(0);
311 }
312
313 if (recurse(pd, isCtor) > 1)
314 .error(pd.loc, "%s `%s` can only apply to a single declaration", pd.kind, pd.toPrettyChars);
315 }
316 return declarations();
317 }
318 else if (pd.ident == Id.printf || pd.ident == Id.scanf)
319 {
320 if (pd.args && pd.args.length != 0)
321 .error(pd.loc, "%s `%s` takes no argument", pd.kind, pd.toPrettyChars);
322 return declarations();
323 }
324 else if (!global.params.ignoreUnsupportedPragmas)
325 {
326 error(pd.loc, "unrecognized `pragma(%s)`", pd.ident.toChars());
327 return declarations();
328 }
329
330 if (!global.params.v.verbose)
331 return declarations();
332
333 /* Print unrecognized pragmas
334 */
335 OutBuffer buf;
336 buf.writestring(pd.ident.toString());
337 if (pd.args)
338 {
339 const errors_save = global.startGagging();
340 for (size_t i = 0; i < pd.args.length; i++)
341 {
342 Expression e = (*pd.args)[i];
343 sc = sc.startCTFE();
344 e = e.expressionSemantic(sc);
345 e = resolveProperties(sc, e);
346 sc = sc.endCTFE();
347 e = e.ctfeInterpret();
348 if (i == 0)
349 buf.writestring(" (");
350 else
351 buf.writeByte(',');
352 buf.writestring(e.toChars());
353 }
354 if (pd.args.length)
355 buf.writeByte(')');
356 global.endGagging(errors_save);
357 }
358 message("pragma %s", buf.peekChars());
359 return declarations();
360 }
361
362 /**
363 * Run semantic on `pragma` statement.
364 *
365 * Params:
366 * ps = pragma statement to evaluate
367 * sc = enclosing scope
368 *
369 * Returns : true if `pragma` is valid, or false if an error was found
370 */
371 bool pragmaStmtSemantic(PragmaStatement ps, Scope* sc)
372 {
373 import dmd.statementsem;
374
375 /* https://dlang.org/spec/statement.html#pragma-statement
376 */
377 // Should be merged with PragmaDeclaration
378
379 //printf("pragmaStmtSemantic() %s\n", ps.toChars());
380 //printf("body = %p\n", ps._body);
381 if (ps.ident == Id.msg)
382 {
383 if (!pragmaMsgSemantic(ps.loc, sc, ps.args))
384 return false;
385 }
386 else if (ps.ident == Id.lib)
387 {
388 version (all)
389 {
390 /* Should this be allowed?
391 */
392 error(ps.loc, "`pragma(lib)` not allowed as statement");
393 return false;
394 }
395 else
396 {
397 if (!ps.args || ps.args.length != 1)
398 {
399 error(ps.loc, "`string` expected for library name");
400 return false;
401 }
402 else
403 {
404 auto se = semanticString(sc, (*ps.args)[0], "library name");
405 if (!se)
406 return false;
407
408 if (global.params.v.verbose)
409 {
410 message("library %.*s", cast(int)se.len, se.string);
411 }
412 }
413 }
414 }
415 else if (ps.ident == Id.linkerDirective)
416 {
417 /* Should this be allowed?
418 */
419 error(ps.loc, "`pragma(linkerDirective)` not allowed as statement");
420 return false;
421 }
422 else if (ps.ident == Id.startaddress)
423 {
424 if (!pragmaStartAddressSemantic(ps.loc, sc, ps.args))
425 return false;
426 }
427 else if (ps.ident == Id.Pinline)
428 {
429 if (auto fd = sc.func)
430 {
431 fd.inlining = evalPragmaInline(ps.loc, sc, ps.args);
432 }
433 else
434 {
435 error(ps.loc, "`pragma(inline)` is not inside a function");
436 return false;
437 }
438 }
439 else if (ps.ident == Id.mangle)
440 {
441 auto es = ps._body ? ps._body.isExpStatement() : null;
442 auto de = es ? es.exp.isDeclarationExp() : null;
443 if (!de)
444 {
445 error(ps.loc, "`pragma(mangle)` must be attached to a declaration");
446 return false;
447 }
448 const se = ps.args && (*ps.args).length == 1 ? semanticString(sc, (*ps.args)[0], "pragma mangle argument") : null;
449 if (!se)
450 {
451 error(ps.loc, "`pragma(mangle)` takes a single argument that must be a string literal");
452 return false;
453 }
454 const cnt = setMangleOverride(de.declaration, cast(const(char)[])se.peekData());
455 if (cnt != 1)
456 assert(0);
457 }
458 else if (!global.params.ignoreUnsupportedPragmas)
459 {
460 error(ps.loc, "unrecognized `pragma(%s)`", ps.ident.toChars());
461 return false;
462 }
463
464 if (ps._body)
465 {
466 if (ps.ident == Id.msg || ps.ident == Id.startaddress)
467 {
468 error(ps.loc, "`pragma(%s)` is missing a terminating `;`", ps.ident.toChars());
469 return false;
470 }
471 ps._body = ps._body.statementSemantic(sc);
472 }
473 return true;
474 }
475
476 /***************************************
477 * Interpret a `pragma(inline, x)`
478 *
479 * Params:
480 * loc = location for error messages
481 * sc = scope for evaluation of argument
482 * args = pragma arguments
483 * Returns: corresponding `PINLINE` state
484 */
485 package PINLINE evalPragmaInline(Loc loc, Scope* sc, Expressions* args)
486 {
487 if (!args || args.length == 0)
488 return PINLINE.default_;
489
490 if (args && args.length > 1)
491 {
492 .error(loc, "one boolean expression expected for `pragma(inline)`, not %llu", cast(ulong) args.length);
493 args.setDim(1);
494 (*args)[0] = ErrorExp.get();
495 }
496
497 Expression e = (*args)[0];
498 if (!e.type)
499 {
500 sc = sc.startCTFE();
501 e = e.expressionSemantic(sc);
502 e = resolveProperties(sc, e);
503 sc = sc.endCTFE();
504 e = e.ctfeInterpret();
505 e = e.toBoolean(sc);
506 if (e.isErrorExp())
507 .error(loc, "pragma(`inline`, `true` or `false`) expected, not `%s`", (*args)[0].toChars());
508 (*args)[0] = e;
509 }
510
511 const opt = e.toBool();
512 if (opt.isEmpty())
513 return PINLINE.default_;
514 if (opt.get())
515 return PINLINE.always;
516 return PINLINE.never;
517 }
518
519 /**
520 * Apply pragma mangle to FuncDeclarations and VarDeclarations
521 * under `s`, poking through attribute declarations such as
522 * `extern(C)` but not through aggregates or function bodies.
523 *
524 * Params:
525 * s = symbol to apply
526 * sym = overriding symbol name
527 */
528 private uint setMangleOverride(Dsymbol s, const(char)[] sym)
529 {
530 if (s.isFuncDeclaration() || s.isVarDeclaration())
531 {
532 s.isDeclaration().mangleOverride = sym;
533 return 1;
534 }
535
536 if (auto ad = s.isAttribDeclaration())
537 {
538 uint nestedCount = 0;
539
540 ad.include(null).foreachDsymbol( (s) { nestedCount += setMangleOverride(s, sym); } );
541
542 return nestedCount;
543 }
544 return 0;
545 }
546
547 /***********************************************************
548 * Evaluate and print a `pragma(msg, args)`
549 *
550 * Params:
551 * loc = location for error messages
552 * sc = scope for argument interpretation
553 * args = expressions to print
554 * Returns:
555 * `true` on success
556 */
557 private bool pragmaMsgSemantic(Loc loc, Scope* sc, Expressions* args)
558 {
559 import dmd.tokens;
560 import dmd.common.outbuffer;
561
562 if (!args)
563 return true;
564
565 OutBuffer buf;
566 if (expressionsToString(buf, sc, args, loc, "while evaluating `pragma(msg, %s)`", false))
567 return false;
568
569 buf.writestring("\n");
570 fprintf(stderr, "%s", buf.extractChars);
571 return true;
572 }
573
574 /**
575 * Apply pragma printf/scanf to FuncDeclarations under `s`,
576 * poking through attribute declarations such as `extern(C)`
577 * but not through aggregates or function bodies.
578 *
579 * Params:
580 * s = symbol to apply
581 * printf = `true` for printf, `false` for scanf
582 */
583 private void setPragmaPrintf(Dsymbol s, bool printf)
584 {
585 if (auto fd = s.isFuncDeclaration())
586 {
587 fd.printf = printf;
588 fd.scanf = !printf;
589 }
590
591 if (auto ad = s.isAttribDeclaration())
592 {
593 ad.include(null).foreachDsymbol( (s) { setPragmaPrintf(s, printf); } );
594 }
595 }
596
597 /***********************************************************
598 * Evaluate `pragma(startAddress, func)` and store the resolved symbol in `args`
599 *
600 * Params:
601 * loc = location for error messages
602 * sc = scope for argument interpretation
603 * args = pragma arguments
604 * Returns:
605 * `true` on success
606 */
607 private bool pragmaStartAddressSemantic(Loc loc, Scope* sc, Expressions* args)
608 {
609 import dmd.dtemplate;
610
611 if (!args || args.length != 1)
612 {
613 .error(loc, "function name expected for start address");
614 return false;
615 }
616 else
617 {
618 /* https://issues.dlang.org/show_bug.cgi?id=11980
619 * resolveProperties and ctfeInterpret call are not necessary.
620 */
621 Expression e = (*args)[0];
622 sc = sc.startCTFE();
623 e = e.expressionSemantic(sc);
624 // e = resolveProperties(sc, e);
625 sc = sc.endCTFE();
626
627 // e = e.ctfeInterpret();
628 (*args)[0] = e;
629 Dsymbol sa = getDsymbol(e);
630 if (!sa || !sa.isFuncDeclaration())
631 {
632 .error(loc, "function name expected for start address, not `%s`", e.toChars());
633 return false;
634 }
635 }
636 return true;
637 }