Debian Codegraph @

gcc/d/dmd/importc.d

raw
1 /**
2 * Contains semantic routines specific to ImportC
3 *
4 * Specification: C11
5 *
6 * Copyright: Copyright (C) 2021-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/importc.d, _importc.d)
10 * Documentation: https://dlang.org/phobos/dmd_importc.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/importc.d
12 */
13
14 module dmd.importc;
15
16 import core.stdc.stdio;
17
18 import dmd.astenums;
19 import dmd.dcast;
20 import dmd.declaration;
21 import dmd.dscope;
22 import dmd.dsymbol;
23 import dmd.dsymbolsem;
24 import dmd.errors;
25 import dmd.expression;
26 import dmd.expressionsem;
27 import dmd.identifier;
28 import dmd.init;
29 import dmd.mtype;
30 import dmd.tokens;
31 import dmd.typesem;
32
33 /**************************************
34 * C11 does not allow array or function parameters.
35 * Hence, adjust those types per C11 6.7.6.3 rules.
36 * Params:
37 * t = parameter type to adjust
38 * sc = context
39 * Returns:
40 * adjusted type
41 */
42 Type cAdjustParamType(Type t, Scope* sc)
43 {
44 if (!sc.inCfile)
45 return t;
46
47 Type tb = t.toBasetype();
48
49 /* C11 6.7.6.3-7 array of T is converted to pointer to T
50 */
51 if (auto ta = tb.isTypeDArray())
52 {
53 t = ta.next.pointerTo();
54 }
55 else if (auto ts = tb.isTypeSArray())
56 {
57 t = ts.next.pointerTo();
58 }
59 /* C11 6.7.6.3-8 function is converted to pointer to function
60 */
61 else if (tb.isTypeFunction())
62 {
63 t = tb.pointerTo();
64 }
65 return t;
66 }
67
68 /***********************************************
69 * C11 6.3.2.1-3 Convert expression that is an array of type to a pointer to type.
70 * C11 6.3.2.1-4 Convert expression that is a function to a pointer to a function.
71 * Params:
72 * e = ImportC expression to possibly convert
73 * sc = context
74 * Returns:
75 * converted expression
76 */
77 Expression arrayFuncConv(Expression e, Scope* sc)
78 {
79 //printf("arrayFuncConv() %s\n", e.toChars());
80 if (!sc.inCfile)
81 return e;
82
83 auto t = e.type.toBasetype();
84 if (auto ta = t.isTypeDArray())
85 {
86 if (!checkAddressable(e, sc))
87 return ErrorExp.get();
88 e = e.castTo(sc, ta.next.pointerTo());
89 }
90 else if (auto ts = t.isTypeSArray())
91 {
92 if (!checkAddressable(e, sc))
93 return ErrorExp.get();
94 e = e.castTo(sc, ts.next.pointerTo());
95 }
96 else if (t.isTypeFunction())
97 {
98 e = new AddrExp(e.loc, e);
99 }
100 else
101 return e;
102 return e.expressionSemantic(sc);
103 }
104
105 /****************************************
106 * Run semantic on `e`.
107 * Expression `e` evaluates to an instance of a struct.
108 * Look up `ident` as a field of that struct.
109 * Params:
110 * e = evaluates to an instance of a struct
111 * sc = context
112 * id = identifier of a field in that struct
113 * arrow = -> was used
114 * Returns:
115 * if successful `e.ident`
116 * if not then `ErrorExp` and message is printed
117 */
118 Expression fieldLookup(Expression e, Scope* sc, Identifier id, bool arrow)
119 {
120 e = e.expressionSemantic(sc);
121 if (e.isErrorExp())
122 return e;
123
124 auto t = e.type;
125 if (t.isTypePointer())
126 {
127 t = t.isTypePointer().next;
128 auto pe = e.toChars();
129 if (!arrow)
130 error(e.loc, "since `%s` is a pointer, use `%s->%s` instead of `%s.%s`", pe, pe, id.toChars(), pe, id.toChars());
131 e = new PtrExp(e.loc, e);
132 }
133 Dsymbol s;
134 if (auto ts = t.isTypeStruct())
135 s = ts.sym.search(e.loc, id, 0);
136 if (!s)
137 {
138 error(e.loc, "`%s` is not a member of `%s`", id.toChars(), t.toChars());
139 return ErrorExp.get();
140 }
141 Expression ef = new DotVarExp(e.loc, e, s.isDeclaration());
142 return ef.expressionSemantic(sc);
143 }
144
145 /****************************************
146 * C11 6.5.2.1-2
147 * Apply C semantics to `E[I]` expression.
148 * E1[E2] is lowered to *(E1 + E2)
149 * Params:
150 * ae = ArrayExp to run semantics on
151 * sc = context
152 * Returns:
153 * Expression if this was a C expression with completed semantic, null if not
154 */
155 Expression carraySemantic(ArrayExp ae, Scope* sc)
156 {
157 if (!sc.inCfile)
158 return null;
159
160 auto e1 = ae.e1.expressionSemantic(sc);
161
162 assert(ae.arguments.length == 1);
163 Expression e2 = (*ae.arguments)[0];
164
165 /* CTFE cannot do pointer arithmetic, but it can index arrays.
166 * So, rewrite as an IndexExp if we can.
167 */
168 auto t1 = e1.type.toBasetype();
169 if (t1.isStaticOrDynamicArray())
170 {
171 e2 = e2.expressionSemantic(sc).arrayFuncConv(sc);
172 // C doesn't do array bounds checking, so `true` turns it off
173 return new IndexExp(ae.loc, e1, e2, true).expressionSemantic(sc);
174 }
175
176 e1 = e1.arrayFuncConv(sc); // e1 might still be a function call
177 e2 = e2.expressionSemantic(sc);
178 auto t2 = e2.type.toBasetype();
179 if (t2.isStaticOrDynamicArray())
180 {
181 return new IndexExp(ae.loc, e2, e1, true).expressionSemantic(sc); // swap operands
182 }
183
184 e2 = e2.arrayFuncConv(sc);
185 auto ep = new PtrExp(ae.loc, new AddExp(ae.loc, e1, e2));
186 return ep.expressionSemantic(sc);
187 }
188
189 /******************************************
190 * Determine default initializer for const global symbol.
191 */
192 void addDefaultCInitializer(VarDeclaration dsym)
193 {
194 //printf("addDefaultCInitializer() %s\n", dsym.toChars());
195 if (!(dsym.storage_class & (STC.static_ | STC.gshared)))
196 return;
197 if (dsym.storage_class & (STC.extern_ | STC.field | STC.in_ | STC.foreach_ | STC.parameter | STC.result))
198 return;
199
200 Type t = dsym.type;
201 if (t.isTypeSArray() && t.isTypeSArray().isIncomplete())
202 {
203 dsym._init = new VoidInitializer(dsym.loc);
204 return; // incomplete arrays will be diagnosed later
205 }
206
207 if (t.isMutable())
208 return;
209
210 auto e = dsym.type.defaultInit(dsym.loc, true);
211 dsym._init = new ExpInitializer(dsym.loc, e);
212 }
213
214 /********************************************
215 * Resolve cast/call grammar ambiguity.
216 * Params:
217 * e = expression that might be a cast, might be a call
218 * sc = context
219 * Returns:
220 * null means leave as is, !=null means rewritten AST
221 */
222 Expression castCallAmbiguity(Expression e, Scope* sc)
223 {
224 Expression* pe = &e;
225
226 while (1)
227 {
228 // Walk down the postfix expressions till we find a CallExp or something else
229 switch ((*pe).op)
230 {
231 case EXP.dotIdentifier:
232 pe = &(*pe).isDotIdExp().e1;
233 continue;
234
235 case EXP.plusPlus:
236 case EXP.minusMinus:
237 pe = &(*pe).isPostExp().e1;
238 continue;
239
240 case EXP.array:
241 pe = &(*pe).isArrayExp().e1;
242 continue;
243
244 case EXP.call:
245 auto ce = (*pe).isCallExp();
246 if (ce.e1.parens)
247 {
248 ce.e1 = expressionSemantic(ce.e1, sc);
249 if (ce.e1.op == EXP.type)
250 {
251 const numArgs = ce.arguments ? ce.arguments.length : 0;
252 if (numArgs >= 1)
253 {
254 ce.e1.parens = false;
255 Expression arg;
256 foreach (a; (*ce.arguments)[])
257 {
258 arg = arg ? new CommaExp(a.loc, arg, a) : a;
259 }
260 auto t = ce.e1.isTypeExp().type;
261 *pe = arg;
262 return new CastExp(ce.loc, e, t);
263 }
264 }
265 }
266 return null;
267
268 default:
269 return null;
270 }
271 }
272 }
273
274 /********************************************
275 * Implement the C11 notion of function equivalence,
276 * which allows prototyped functions to match K+R functions,
277 * even though they are different.
278 * Params:
279 * tf1 = type of first function
280 * tf2 = type of second function
281 * Returns:
282 * true if C11 considers them equivalent
283 */
284
285 bool cFuncEquivalence(TypeFunction tf1, TypeFunction tf2)
286 {
287 //printf("cFuncEquivalence()\n %s\n %s\n", tf1.toChars(), tf2.toChars());
288 if (tf1.equals(tf2))
289 return true;
290
291 if (tf1.linkage != tf2.linkage)
292 return false;
293
294 // Allow func(void) to match func()
295 if (tf1.parameterList.length == 0 && tf2.parameterList.length == 0)
296 return true;
297
298 if (!cTypeEquivalence(tf1.next, tf2.next))
299 return false; // function return types don't match
300
301 if (tf1.parameterList.length != tf2.parameterList.length)
302 return false;
303
304 if (!tf1.parameterList.hasIdentifierList && !tf2.parameterList.hasIdentifierList) // if both are prototyped
305 {
306 if (tf1.parameterList.varargs != tf2.parameterList.varargs)
307 return false;
308 }
309
310 foreach (i, fparam ; tf1.parameterList)
311 {
312 Type t1 = fparam.type;
313 Type t2 = tf2.parameterList[i].type;
314
315 /* Strip off head const.
316 * Not sure if this is C11, but other compilers treat
317 * `void fn(int)` and `fn(const int x)`
318 * as equivalent.
319 */
320 t1 = t1.mutableOf();
321 t2 = t2.mutableOf();
322
323 if (!t1.equals(t2))
324 return false;
325 }
326
327 //printf("t1: %s\n", tf1.toChars());
328 //printf("t2: %s\n", tf2.toChars());
329 return true;
330 }
331
332 /*******************************
333 * Types haven't been merged yet, because we haven't done
334 * semantic() yet.
335 * But we still need to see if t1 and t2 are the same type.
336 * Params:
337 * t1 = first type
338 * t2 = second type
339 * Returns:
340 * true if they are equivalent types
341 */
342 bool cTypeEquivalence(Type t1, Type t2)
343 {
344 if (t1.equals(t2))
345 return true; // that was easy
346
347 if (t1.ty != t2.ty || t1.mod != t2.mod)
348 return false;
349
350 if (auto tp = t1.isTypePointer())
351 return cTypeEquivalence(tp.next, t2.nextOf());
352
353 if (auto ta = t1.isTypeSArray())
354 // Bug: should check array dimension
355 return cTypeEquivalence(ta.next, t2.nextOf());
356
357 if (auto ts = t1.isTypeStruct())
358 return ts.sym is t2.isTypeStruct().sym;
359
360 if (auto te = t1.isTypeEnum())
361 return te.sym is t2.isTypeEnum().sym;
362
363 if (auto tf = t1.isTypeFunction())
364 return cFuncEquivalence(tf, tf.isTypeFunction());
365
366 return false;
367 }
368
369 /**********************************************
370 * ImportC tag symbols sit in a parallel symbol table,
371 * so that this C code works:
372 * ---
373 * struct S { a; };
374 * int S;
375 * struct S s;
376 * ---
377 * But there are relatively few such tag symbols, so that would be
378 * a waste of memory and complexity. An additional problem is we'd like the D side
379 * to find the tag symbols with ordinary lookup, not lookup in both
380 * tables, if the tag symbol is not conflicting with an ordinary symbol.
381 * The solution is to put the tag symbols that conflict into an associative
382 * array, indexed by the address of the ordinary symbol that conflicts with it.
383 * C has no modules, so this associative array is tagSymTab[] in ModuleDeclaration.
384 * A side effect of our approach is that D code cannot access a tag symbol that is
385 * hidden by an ordinary symbol. This is more of a theoretical problem, as nobody
386 * has mentioned it when importing C headers. If someone wants to do it,
387 * too bad so sad. Change the C code.
388 * This function fixes up the symbol table when faced with adding a new symbol
389 * `s` when there is an existing symbol `s2` with the same name.
390 * C also allows forward and prototype declarations of tag symbols,
391 * this function merges those.
392 * Params:
393 * sc = context
394 * s = symbol to add to symbol table
395 * s2 = existing declaration
396 * sds = symbol table
397 * Returns:
398 * if s and s2 are successfully put in symbol table then return the merged symbol,
399 * null if they conflict
400 */
401 Dsymbol handleTagSymbols(ref Scope sc, Dsymbol s, Dsymbol s2, ScopeDsymbol sds)
402 {
403 enum log = false;
404 if (log) printf("handleTagSymbols('%s') add %p existing %p\n", s.toChars(), s, s2);
405 if (log) printf(" add %s %s, existing %s %s\n", s.kind(), s.toChars(), s2.kind(), s2.toChars());
406 auto sd = s.isScopeDsymbol(); // new declaration
407 auto sd2 = s2.isScopeDsymbol(); // existing declaration
408
409 static if (log) void print(EnumDeclaration sd)
410 {
411 printf("members: %p\n", sd.members);
412 printf("symtab: %p\n", sd.symtab);
413 printf("endlinnum: %d\n", sd.endlinnum);
414 printf("type: %s\n", sd.type.toChars());
415 printf("memtype: %s\n", sd.memtype.toChars());
416 }
417
418 if (!sd2)
419 {
420 /* Look in tag table
421 */
422 if (log) printf(" look in tag table\n");
423 if (auto p = cast(void*)s2 in sc._module.tagSymTab)
424 {
425 Dsymbol s2tag = *p;
426 sd2 = s2tag.isScopeDsymbol();
427 assert(sd2); // only tags allowed in tag symbol table
428 }
429 }
430
431 if (sd && sd2) // `s` is a tag, `sd2` is the same tag
432 {
433 if (log) printf(" tag is already defined\n");
434
435 if (sd.kind() != sd2.kind()) // being enum/struct/union must match
436 return null; // conflict
437
438 /* Not a redeclaration if one is a forward declaration.
439 * Move members to the first declared type, which is sd2.
440 */
441 if (sd2.members)
442 {
443 if (!sd.members)
444 return sd2; // ignore the sd redeclaration
445 }
446 else if (sd.members)
447 {
448 sd2.members = sd.members; // transfer definition to sd2
449 sd.members = null;
450 if (auto ed2 = sd2.isEnumDeclaration())
451 {
452 auto ed = sd.isEnumDeclaration();
453 if (ed.memtype != ed2.memtype)
454 return null; // conflict
455
456 // transfer ed's members to sd2
457 ed2.members.foreachDsymbol( (s)
458 {
459 if (auto em = s.isEnumMember())
460 em.ed = ed2;
461 });
462
463 ed2.type = ed.type;
464 ed2.memtype = ed.memtype;
465 ed2.added = false;
466 }
467 return sd2;
468 }
469 else
470 return sd2; // ignore redeclaration
471 }
472 else if (sd) // `s` is a tag, `s2` is not
473 {
474 if (log) printf(" s is tag, s2 is not\n");
475 /* add `s` as tag indexed by s2
476 */
477 sc._module.tagSymTab[cast(void*)s2] = s;
478 return s;
479 }
480 else if (s2 is sd2) // `s2` is a tag, `s` is not
481 {
482 if (log) printf(" s2 is tag, s is not\n");
483 /* replace `s2` in symbol table with `s`,
484 * then add `s2` as tag indexed by `s`
485 */
486 sds.symtab.update(s);
487 sc._module.tagSymTab[cast(void*)s] = s2;
488 return s;
489 }
490 // neither s2 nor s is a tag
491 if (log) printf(" collision\n");
492 return null;
493 }
494
495
496 /**********************************************
497 * ImportC allows redeclarations of C variables, functions and typedefs.
498 * extern int x;
499 * int x = 3;
500 * and:
501 * extern void f();
502 * void f() { }
503 * Attempt to merge them.
504 * Params:
505 * sc = context
506 * s = symbol to add to symbol table
507 * s2 = existing declaration
508 * sds = symbol table
509 * Returns:
510 * if s and s2 are successfully put in symbol table then return the merged symbol,
511 * null if they conflict
512 */
513 Dsymbol handleSymbolRedeclarations(ref Scope sc, Dsymbol s, Dsymbol s2, ScopeDsymbol sds)
514 {
515 enum log = false;
516 if (log) printf("handleSymbolRedeclarations('%s')\n", s.toChars());
517 if (log) printf(" add %s %s, existing %s %s\n", s.kind(), s.toChars(), s2.kind(), s2.toChars());
518
519 static Dsymbol collision()
520 {
521 if (log) printf(" collision\n");
522 return null;
523 }
524 /*
525 Handle merging declarations with asm("foo") and their definitions
526 */
527 static void mangleWrangle(Declaration oldDecl, Declaration newDecl)
528 {
529 if (oldDecl && newDecl)
530 {
531 newDecl.mangleOverride = oldDecl.mangleOverride ? oldDecl.mangleOverride : null;
532 }
533 }
534
535 auto vd = s.isVarDeclaration(); // new declaration
536 auto vd2 = s2.isVarDeclaration(); // existing declaration
537
538 if (vd && vd.isCmacro())
539 return vd2;
540
541 assert(!(vd2 && vd2.isCmacro()));
542
543 if (vd && vd2)
544 {
545 /* if one is `static` and the other isn't, the result is undefined
546 * behavior, C11 6.2.2.7
547 */
548 if ((vd.storage_class ^ vd2.storage_class) & STC.static_)
549 return collision();
550
551 const i1 = vd._init && ! vd._init.isVoidInitializer();
552 const i2 = vd2._init && !vd2._init.isVoidInitializer();
553
554 if (i1 && i2)
555 return collision(); // can't both have initializers
556
557 mangleWrangle(vd2, vd);
558
559 if (i1) // vd is the definition
560 {
561 vd2.storage_class |= STC.extern_; // so toObjFile() won't emit it
562 sds.symtab.update(vd); // replace vd2 with the definition
563 return vd;
564 }
565
566 /* BUG: the types should match, which needs semantic() to be run on it
567 * extern int x;
568 * int x; // match
569 * typedef int INT;
570 * INT x; // match
571 * long x; // collision
572 * We incorrectly ignore these collisions
573 */
574 return vd2;
575 }
576
577 auto fd = s.isFuncDeclaration(); // new declaration
578 auto fd2 = s2.isFuncDeclaration(); // existing declaration
579 if (fd && fd2)
580 {
581 /* if one is `static` and the other isn't, the result is undefined
582 * behavior, C11 6.2.2.7
583 * However, match what gcc allows:
584 * static int sun1(); int sun1() { return 0; }
585 * and:
586 * static int sun2() { return 0; } int sun2();
587 * Both produce a static function.
588 *
589 * Both of these should fail:
590 * int sun3(); static int sun3() { return 0; }
591 * and:
592 * int sun4() { return 0; } static int sun4();
593 */
594 // if adding `static`
595 if ( fd.storage_class & STC.static_ &&
596 !(fd2.storage_class & STC.static_))
597 {
598 return collision();
599 }
600
601 if (fd.fbody && fd2.fbody)
602 return collision(); // can't both have bodies
603
604 mangleWrangle(fd2, fd);
605
606 if (fd.fbody) // fd is the definition
607 {
608 if (log) printf(" replace existing with new\n");
609 sds.symtab.update(fd); // replace fd2 in symbol table with fd
610 fd.overnext = fd2;
611
612 /* If fd2 is covering a tag symbol, then fd has to cover the same one
613 */
614 auto ps = cast(void*)fd2 in sc._module.tagSymTab;
615 if (ps)
616 sc._module.tagSymTab[cast(void*)fd] = *ps;
617
618 return fd;
619 }
620
621 /* Just like with VarDeclaration, the types should match, which needs semantic() to be run on it.
622 * FuncDeclaration::semantic() detects this, but it relies on .overnext being set.
623 */
624 fd2.overloadInsert(fd);
625
626 return fd2;
627 }
628
629 auto td = s.isAliasDeclaration(); // new declaration
630 auto td2 = s2.isAliasDeclaration(); // existing declaration
631 if (td && td2)
632 {
633 /* BUG: just like with variables and functions, the types should match, which needs semantic() to be run on it.
634 * FuncDeclaration::semantic2() can detect this, but it relies overnext being set.
635 */
636 return td2;
637 }
638
639 return collision();
640 }