Debian Codegraph @

gcc/d/dmd/hdrgen.d

raw
1 /**
2 * Generate $(LINK2 https://dlang.org/dmd-windows.html#interface-files, D interface files).
3 *
4 * Also used to convert AST nodes to D code in general, e.g. for error messages or `printf` debugging.
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/hdrgen.d, _hdrgen.d)
10 * Documentation: https://dlang.org/phobos/dmd_hdrgen.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/hdrgen.d
12 */
13
14 module dmd.hdrgen;
15
16 import core.stdc.ctype;
17 import core.stdc.stdio;
18 import core.stdc.string;
19 import dmd.aggregate;
20 import dmd.aliasthis;
21 import dmd.arraytypes;
22 import dmd.astenums;
23 import dmd.attrib;
24 import dmd.cond;
25 import dmd.ctfeexpr;
26 import dmd.dclass;
27 import dmd.declaration;
28 import dmd.denum;
29 import dmd.dimport;
30 import dmd.dmodule;
31 import dmd.doc;
32 import dmd.dstruct;
33 import dmd.dsymbol;
34 import dmd.dtemplate;
35 import dmd.dversion;
36 import dmd.expression;
37 import dmd.func;
38 import dmd.id;
39 import dmd.identifier;
40 import dmd.init;
41 import dmd.mtype;
42 import dmd.nspace;
43 import dmd.optimize;
44 import dmd.parse;
45 import dmd.root.complex;
46 import dmd.root.ctfloat;
47 import dmd.common.outbuffer;
48 import dmd.rootobject;
49 import dmd.root.string;
50 import dmd.statement;
51 import dmd.staticassert;
52 import dmd.tokens;
53 import dmd.typesem;
54 import dmd.visitor;
55
56 struct HdrGenState
57 {
58 bool hdrgen; /// true if generating header file
59 bool ddoc; /// true if generating Ddoc file
60 bool fullDump; /// true if generating a full AST dump file
61 bool importcHdr; /// true if generating a .di file from an ImportC file
62 bool inCAlias; /// Set to prevent ImportC translating typedefs as `alias X = X`
63 bool doFuncBodies; /// include function bodies in output
64 bool vcg_ast; /// write out codegen-ast
65 bool skipConstraints; // skip constraints when doing templates
66 bool showOneMember = true;
67 bool errorMsg; /// true if formatting for inside an error message
68
69 bool fullQual; /// fully qualify types when printing
70 int tpltMember;
71 int autoMember;
72 int forStmtInit;
73 int insideFuncBody;
74 int insideAggregate;
75
76 bool declstring; // set while declaring alias for string,wstring or dstring
77 EnumDeclaration inEnumDecl;
78 }
79
80 enum TEST_EMIT_ALL = 0;
81
82 /****************************************
83 * Generate a header (.di) file for Module m.
84 * Params:
85 * m = Module to generate header for
86 * doFuncBodies = generate function definitions rather than just declarations
87 * buf = buffer to write the data to
88 */
89 void genhdrfile(Module m, bool doFuncBodies, ref OutBuffer buf)
90 {
91 buf.doindent = 1;
92 buf.printf("// D import file generated from '%s'", m.srcfile.toChars());
93 buf.writenl();
94 HdrGenState hgs;
95 hgs.hdrgen = true;
96 hgs.importcHdr = (m.filetype == FileType.c);
97 hgs.doFuncBodies = doFuncBodies;
98 toCBuffer(m, buf, hgs);
99 }
100
101 /**
102 * Convert `o` to a string for error messages.
103 * Params:
104 * e = object to convert
105 * Returns: string representation of `e`
106 */
107 const(char)* toErrMsg(const RootObject o)
108 {
109 if (auto e = o.isExpression())
110 return toErrMsg(e);
111 if (auto d = o.isDsymbol())
112 return toErrMsg(d);
113 if (auto t = o.isType())
114 return t.toChars();
115 if (auto id = o.isIdentifier())
116 return id.toChars();
117 assert(0);
118 }
119
120 /// ditto
121 const(char)* toErrMsg(const Expression e)
122 {
123 HdrGenState hgs;
124 hgs.errorMsg = true;
125 OutBuffer buf;
126 toCBuffer(e, buf, hgs);
127 truncateForError(buf, 60);
128
129 return buf.extractChars();
130 }
131
132 /// ditto
133 const(char)* toErrMsg(const Dsymbol d)
134 {
135 if (d.isFuncDeclaration() || d.isTemplateInstance())
136 {
137 if (d.ident && d.ident.toString.startsWith("__") && !d.isCtorDeclaration())
138 {
139 HdrGenState hgs;
140 hgs.errorMsg = true;
141 OutBuffer buf;
142 toCBuffer(cast() d, buf, hgs);
143 truncateForError(buf, 80);
144 return buf.extractChars();
145 }
146 }
147
148 return d.toChars();
149 }
150
151 /**
152 * Make the content of `buf` fit inline for an error message.
153 * Params:
154 * buf = buffer with text to modify
155 * maxLength = truncate text when it exceeds this length
156 */
157 private void truncateForError(ref OutBuffer buf, size_t maxLength)
158 {
159 // Remove newlines, escape backticks ` by doubling them
160 for (size_t i = 0; i < buf.length; i++)
161 {
162 if (buf[i] == '\r')
163 buf.remove(i, 1);
164 if (buf[i] == '\n')
165 buf.peekSlice[i] = ' ';
166 if (buf[i] == '`')
167 i = buf.insert(i, "`");
168 }
169
170 // Strip trailing whitespace
171 while (buf.length && buf[$-1] == ' ')
172 buf.setsize(buf.length - 1);
173
174 // Truncate
175 if (buf.length > maxLength)
176 {
177 buf.setsize(maxLength - 3);
178 buf.writestring("...");
179 }
180 }
181
182 /***************************************
183 * Turn a Statement into a string suitable for printf.
184 * Leaks memory.
185 * Params:
186 * s = Statement to convert
187 * Returns:
188 * 0-terminated string
189 */
190 public const(char)* toChars(const Statement s)
191 {
192 HdrGenState hgs;
193 OutBuffer buf;
194 toCBuffer(s, buf, hgs);
195 buf.writeByte(0);
196 return buf.extractSlice().ptr;
197 }
198
199 public const(char)* toChars(const Expression e)
200 {
201 HdrGenState hgs;
202 OutBuffer buf;
203 toCBuffer(e, buf, hgs);
204 return buf.extractChars();
205 }
206
207 public const(char)* toChars(const Initializer i)
208 {
209 OutBuffer buf;
210 HdrGenState hgs;
211 toCBuffer(i, buf, hgs);
212 return buf.extractChars();
213 }
214
215 public const(char)* toChars(const Type t)
216 {
217 OutBuffer buf;
218 buf.reserve(16);
219 HdrGenState hgs;
220 hgs.fullQual = (t.ty == Tclass && !t.mod);
221
222 toCBuffer(t, buf, null, hgs);
223 return buf.extractChars();
224 }
225
226 public const(char)* toChars(const Dsymbol d)
227 {
228 if (auto td = d.isTemplateDeclaration())
229 {
230 HdrGenState hgs;
231 OutBuffer buf;
232 toCharsMaybeConstraints(td, buf, hgs);
233 return buf.extractChars();
234 }
235
236 if (auto ti = d.isTemplateInstance())
237 {
238 OutBuffer buf;
239 toCBufferInstance(ti, buf);
240 return buf.extractChars();
241 }
242
243 if (auto tm = d.isTemplateMixin())
244 {
245 OutBuffer buf;
246 toCBufferInstance(tm, buf);
247 return buf.extractChars();
248 }
249
250 if (auto tid = d.isTypeInfoDeclaration())
251 {
252 OutBuffer buf;
253 buf.writestring("typeid(");
254 buf.writestring(tid.tinfo.toChars());
255 buf.writeByte(')');
256 return buf.extractChars();
257 }
258
259 return d.ident ? d.ident.toHChars2() : "__anonymous";
260 }
261
262 public const(char)[] toString(const Initializer i)
263 {
264 OutBuffer buf;
265 HdrGenState hgs;
266 toCBuffer(i, buf, hgs);
267 return buf.extractSlice();
268 }
269
270 /**
271 * Dumps the full contents of module `m` to `buf`.
272 * Params:
273 * buf = buffer to write to.
274 * vcg_ast = write out codegen ast
275 * m = module to visit all members of.
276 */
277 void moduleToBuffer(ref OutBuffer buf, bool vcg_ast, Module m)
278 {
279 HdrGenState hgs;
280 hgs.fullDump = true;
281 hgs.vcg_ast = vcg_ast;
282 toCBuffer(m, buf, hgs);
283 }
284
285 void moduleToBuffer2(Module m, ref OutBuffer buf, ref HdrGenState hgs)
286 {
287 if (m.md)
288 {
289 if (m.userAttribDecl)
290 {
291 buf.writestring("@(");
292 argsToBuffer(m.userAttribDecl.atts, buf, hgs);
293 buf.writeByte(')');
294 buf.writenl();
295 }
296 if (m.md.isdeprecated)
297 {
298 if (m.md.msg)
299 {
300 buf.writestring("deprecated(");
301 m.md.msg.expressionToBuffer(buf, hgs);
302 buf.writestring(") ");
303 }
304 else
305 buf.writestring("deprecated ");
306 }
307 buf.writestring("module ");
308 buf.writestring(m.md.toChars());
309 buf.writeByte(';');
310 buf.writenl();
311 }
312
313 foreach (s; *m.members)
314 {
315 s.dsymbolToBuffer(buf, hgs);
316 }
317 }
318
319 private void statementToBuffer(Statement s, ref OutBuffer buf, ref HdrGenState hgs)
320 {
321 void visitDefaultCase(Statement s)
322 {
323 printf("Statement::toCBuffer() %d\n", s.stmt);
324 assert(0, "unrecognized statement in statementToBuffer()");
325 }
326
327 void visitError(ErrorStatement s)
328 {
329 buf.writestring("__error__");
330 buf.writenl();
331 }
332
333 void visitExp(ExpStatement s)
334 {
335 if (s.exp && s.exp.op == EXP.declaration &&
336 (cast(DeclarationExp)s.exp).declaration)
337 {
338 // bypass visit(DeclarationExp)
339 (cast(DeclarationExp)s.exp).declaration.dsymbolToBuffer(buf, hgs);
340 return;
341 }
342 if (s.exp)
343 s.exp.expressionToBuffer(buf, hgs);
344 buf.writeByte(';');
345 if (!hgs.forStmtInit)
346 buf.writenl();
347 }
348
349 void visitDtorExp(DtorExpStatement s)
350 {
351 visitExp(s);
352 }
353
354 void visitMixin(MixinStatement s)
355 {
356 buf.writestring("mixin(");
357 argsToBuffer(s.exps, buf, hgs, null);
358 buf.writestring(");");
359 if (!hgs.forStmtInit)
360 buf.writenl();
361 }
362
363 void visitCompound(CompoundStatement s)
364 {
365 foreach (sx; *s.statements)
366 {
367 if (sx)
368 sx.statementToBuffer(buf, hgs);
369 }
370 }
371
372 void visitCompoundAsm(CompoundAsmStatement s)
373 {
374 visitCompound(s);
375 }
376
377 void visitCompoundDeclaration(CompoundDeclarationStatement s)
378 {
379 bool anywritten = false;
380 foreach (sx; *s.statements)
381 {
382 auto ds = sx ? sx.isExpStatement() : null;
383 if (ds && ds.exp.isDeclarationExp())
384 {
385 auto d = ds.exp.isDeclarationExp().declaration;
386 if (auto v = d.isVarDeclaration())
387 {
388 visitVarDecl(v, anywritten, buf, hgs);
389 }
390 else
391 d.dsymbolToBuffer(buf, hgs);
392 anywritten = true;
393 }
394 }
395 buf.writeByte(';');
396 if (!hgs.forStmtInit)
397 buf.writenl();
398 }
399
400 void visitUnrolledLoop(UnrolledLoopStatement s)
401 {
402 buf.writestring("/*unrolled*/ {");
403 buf.writenl();
404 buf.level++;
405 foreach (sx; *s.statements)
406 {
407 if (sx)
408 sx.statementToBuffer(buf, hgs);
409 }
410 buf.level--;
411 buf.writeByte('}');
412 buf.writenl();
413 }
414
415 void visitScope(ScopeStatement s)
416 {
417 buf.writeByte('{');
418 buf.writenl();
419 buf.level++;
420 if (s.statement)
421 s.statement.statementToBuffer(buf, hgs);
422 buf.level--;
423 buf.writeByte('}');
424 buf.writenl();
425 }
426
427 void printConditionAssignment(Parameter p, Expression condition)
428 {
429 if (p)
430 {
431 // Print condition assignment
432 STC stc = p.storageClass;
433 if (!p.type && !stc)
434 stc = STC.auto_;
435 if (stcToBuffer(buf, stc))
436 buf.writeByte(' ');
437 if (p.type)
438 typeToBuffer(p.type, p.ident, buf, hgs);
439 else
440 buf.writestring(p.ident.toString());
441 buf.writestring(" = ");
442 }
443 condition.expressionToBuffer(buf, hgs);
444 }
445
446 void visitWhile(WhileStatement s)
447 {
448 buf.writestring("while (");
449 printConditionAssignment(s.param, s.condition);
450 buf.writeByte(')');
451 buf.writenl();
452 if (s._body)
453 s._body.statementToBuffer(buf, hgs);
454 }
455
456 void visitDo(DoStatement s)
457 {
458 buf.writestring("do");
459 buf.writenl();
460 if (s._body)
461 s._body.statementToBuffer(buf, hgs);
462 buf.writestring("while (");
463 s.condition.expressionToBuffer(buf, hgs);
464 buf.writestring(");");
465 buf.writenl();
466 }
467
468 void visitFor(ForStatement s)
469 {
470 buf.writestring("for (");
471 if (s._init)
472 {
473 hgs.forStmtInit++;
474 s._init.statementToBuffer(buf, hgs);
475 hgs.forStmtInit--;
476 }
477 else
478 buf.writeByte(';');
479 if (s.condition)
480 {
481 buf.writeByte(' ');
482 s.condition.expressionToBuffer(buf, hgs);
483 }
484 buf.writeByte(';');
485 if (s.increment)
486 {
487 buf.writeByte(' ');
488 s.increment.expressionToBuffer(buf, hgs);
489 }
490 buf.writeByte(')');
491 buf.writenl();
492 buf.writeByte('{');
493 buf.writenl();
494 buf.level++;
495 if (s._body)
496 s._body.statementToBuffer(buf, hgs);
497 buf.level--;
498 buf.writeByte('}');
499 buf.writenl();
500 }
501
502 void foreachWithoutBody(ForeachStatement s)
503 {
504 buf.writestring(Token.toString(s.op));
505 buf.writestring(" (");
506 foreach (i, p; *s.parameters)
507 {
508 if (i)
509 buf.writestring(", ");
510 if (stcToBuffer(buf, p.storageClass))
511 buf.writeByte(' ');
512 if (p.type)
513 typeToBuffer(p.type, p.ident, buf, hgs);
514 else
515 buf.writestring(p.ident.toString());
516 }
517 buf.writestring("; ");
518 s.aggr.expressionToBuffer(buf, hgs);
519 buf.writeByte(')');
520 buf.writenl();
521 }
522
523 void visitForeach(ForeachStatement s)
524 {
525 foreachWithoutBody(s);
526 buf.writeByte('{');
527 buf.writenl();
528 buf.level++;
529 if (s._body)
530 s._body.statementToBuffer(buf, hgs);
531 buf.level--;
532 buf.writeByte('}');
533 buf.writenl();
534 }
535
536 void foreachRangeWithoutBody(ForeachRangeStatement s)
537 {
538 buf.writestring(Token.toString(s.op));
539 buf.writestring(" (");
540 if (s.param.type)
541 typeToBuffer(s.param.type, s.param.ident, buf, hgs);
542 else
543 buf.writestring(s.param.ident.toString());
544 buf.writestring("; ");
545 s.lwr.expressionToBuffer(buf, hgs);
546 buf.writestring(" .. ");
547 s.upr.expressionToBuffer(buf, hgs);
548 buf.writeByte(')');
549 buf.writenl();
550 }
551
552 void visitForeachRange(ForeachRangeStatement s)
553 {
554 foreachRangeWithoutBody(s);
555 buf.writeByte('{');
556 buf.writenl();
557 buf.level++;
558 if (s._body)
559 s._body.statementToBuffer(buf, hgs);
560 buf.level--;
561 buf.writeByte('}');
562 buf.writenl();
563 }
564
565 void visitStaticForeach(StaticForeachStatement s)
566 {
567 buf.writestring("static ");
568 if (s.sfe.aggrfe)
569 {
570 visitForeach(s.sfe.aggrfe);
571 }
572 else
573 {
574 assert(s.sfe.rangefe);
575 visitForeachRange(s.sfe.rangefe);
576 }
577 }
578
579 void visitForwarding(ForwardingStatement s)
580 {
581 s.statement.statementToBuffer(buf, hgs);
582 }
583
584 void visitIf(IfStatement s)
585 {
586 buf.writestring("if (");
587 printConditionAssignment(s.param, s.condition);
588 buf.writeByte(')');
589 buf.writenl();
590 if (s.ifbody.isScopeStatement())
591 {
592 s.ifbody.statementToBuffer(buf, hgs);
593 }
594 else
595 {
596 buf.level++;
597 s.ifbody.statementToBuffer(buf, hgs);
598 buf.level--;
599 }
600 if (s.elsebody)
601 {
602 buf.writestring("else");
603 if (!s.elsebody.isIfStatement())
604 {
605 buf.writenl();
606 }
607 else
608 {
609 buf.writeByte(' ');
610 }
611 if (s.elsebody.isScopeStatement() || s.elsebody.isIfStatement())
612 {
613 s.elsebody.statementToBuffer(buf, hgs);
614 }
615 else
616 {
617 buf.level++;
618 s.elsebody.statementToBuffer(buf, hgs);
619 buf.level--;
620 }
621 }
622 }
623
624 void visitConditional(ConditionalStatement s)
625 {
626 s.condition.conditionToBuffer(buf, hgs);
627 buf.writenl();
628 buf.writeByte('{');
629 buf.writenl();
630 buf.level++;
631 if (s.ifbody)
632 s.ifbody.statementToBuffer(buf, hgs);
633 buf.level--;
634 buf.writeByte('}');
635 buf.writenl();
636 if (s.elsebody)
637 {
638 buf.writestring("else");
639 buf.writenl();
640 buf.writeByte('{');
641 buf.level++;
642 buf.writenl();
643 s.elsebody.statementToBuffer(buf, hgs);
644 buf.level--;
645 buf.writeByte('}');
646 }
647 buf.writenl();
648 }
649
650 void visitPragma(PragmaStatement s)
651 {
652 buf.writestring("pragma (");
653 buf.writestring(s.ident.toString());
654 if (s.args && s.args.length)
655 {
656 buf.writestring(", ");
657 argsToBuffer(s.args, buf, hgs);
658 }
659 buf.writeByte(')');
660 if (s._body)
661 {
662 buf.writenl();
663 buf.writeByte('{');
664 buf.writenl();
665 buf.level++;
666 s._body.statementToBuffer(buf, hgs);
667 buf.level--;
668 buf.writeByte('}');
669 buf.writenl();
670 }
671 else
672 {
673 buf.writeByte(';');
674 buf.writenl();
675 }
676 }
677
678 void visitStaticAssert(StaticAssertStatement s)
679 {
680 s.sa.dsymbolToBuffer(buf, hgs);
681 }
682
683 void visitSwitch(SwitchStatement s)
684 {
685 buf.writestring(s.isFinal ? "final switch (" : "switch (");
686 printConditionAssignment(s.param, s.condition);
687 buf.writeByte(')');
688 buf.writenl();
689 if (s._body)
690 {
691 if (!s._body.isScopeStatement())
692 {
693 buf.writeByte('{');
694 buf.writenl();
695 buf.level++;
696 s._body.statementToBuffer(buf, hgs);
697 buf.level--;
698 buf.writeByte('}');
699 buf.writenl();
700 }
701 else
702 {
703 s._body.statementToBuffer(buf, hgs);
704 }
705 }
706 }
707
708 void visitCase(CaseStatement s)
709 {
710 buf.writestring("case ");
711 s.exp.expressionToBuffer(buf, hgs);
712 buf.writeByte(':');
713 buf.writenl();
714 s.statement.statementToBuffer(buf, hgs);
715 }
716
717 void visitCaseRange(CaseRangeStatement s)
718 {
719 buf.writestring("case ");
720 s.first.expressionToBuffer(buf, hgs);
721 buf.writestring(": .. case ");
722 s.last.expressionToBuffer(buf, hgs);
723 buf.writeByte(':');
724 buf.writenl();
725 s.statement.statementToBuffer(buf, hgs);
726 }
727
728 void visitDefault(DefaultStatement s)
729 {
730 buf.writestring("default:");
731 buf.writenl();
732 s.statement.statementToBuffer(buf, hgs);
733 }
734
735 void visitGotoDefault(GotoDefaultStatement s)
736 {
737 buf.writestring("goto default;");
738 buf.writenl();
739 }
740
741 void visitGotoCase(GotoCaseStatement s)
742 {
743 buf.writestring("goto case");
744 if (s.exp)
745 {
746 buf.writeByte(' ');
747 s.exp.expressionToBuffer(buf, hgs);
748 }
749 buf.writeByte(';');
750 buf.writenl();
751 }
752
753 void visitSwitchError(SwitchErrorStatement s)
754 {
755 buf.writestring("SwitchErrorStatement::toCBuffer()");
756 buf.writenl();
757 }
758
759 void visitReturn(ReturnStatement s)
760 {
761 buf.writestring("return ");
762 if (s.exp)
763 s.exp.expressionToBuffer(buf, hgs);
764 buf.writeByte(';');
765 buf.writenl();
766 }
767
768 void visitBreak(BreakStatement s)
769 {
770 buf.writestring("break");
771 if (s.ident)
772 {
773 buf.writeByte(' ');
774 buf.writestring(s.ident.toString());
775 }
776 buf.writeByte(';');
777 buf.writenl();
778 }
779
780 void visitContinue(ContinueStatement s)
781 {
782 buf.writestring("continue");
783 if (s.ident)
784 {
785 buf.writeByte(' ');
786 buf.writestring(s.ident.toString());
787 }
788 buf.writeByte(';');
789 buf.writenl();
790 }
791
792 void visitSynchronized(SynchronizedStatement s)
793 {
794 buf.writestring("synchronized");
795 if (s.exp)
796 {
797 buf.writeByte('(');
798 s.exp.expressionToBuffer(buf, hgs);
799 buf.writeByte(')');
800 }
801 if (s._body)
802 {
803 buf.writeByte(' ');
804 s._body.statementToBuffer(buf, hgs);
805 }
806 }
807
808 void visitWith(WithStatement s)
809 {
810 buf.writestring("with (");
811 s.exp.expressionToBuffer(buf, hgs);
812 buf.writestring(")");
813 buf.writenl();
814 if (s._body)
815 s._body.statementToBuffer(buf, hgs);
816 }
817
818 void visitTryCatch(TryCatchStatement s)
819 {
820 buf.writestring("try");
821 buf.writenl();
822 if (s._body)
823 {
824 if (s._body.isScopeStatement())
825 {
826 s._body.statementToBuffer(buf, hgs);
827 }
828 else
829 {
830 buf.level++;
831 s._body.statementToBuffer(buf, hgs);
832 buf.level--;
833 }
834 }
835 foreach (c; *s.catches)
836 {
837 buf.writestring("catch");
838 if (c.type)
839 {
840 buf.writeByte('(');
841 typeToBuffer(c.type, c.ident, buf, hgs);
842 buf.writeByte(')');
843 }
844 buf.writenl();
845 buf.writeByte('{');
846 buf.writenl();
847 buf.level++;
848 if (c.handler)
849 c.handler.statementToBuffer(buf, hgs);
850 buf.level--;
851 buf.writeByte('}');
852 buf.writenl();
853 }
854 }
855
856 void visitTryFinally(TryFinallyStatement s)
857 {
858 buf.writestring("try");
859 buf.writenl();
860 buf.writeByte('{');
861 buf.writenl();
862 buf.level++;
863 s._body.statementToBuffer(buf, hgs);
864 buf.level--;
865 buf.writeByte('}');
866 buf.writenl();
867 buf.writestring("finally");
868 buf.writenl();
869 if (s.finalbody.isScopeStatement())
870 {
871 s.finalbody.statementToBuffer(buf, hgs);
872 }
873 else
874 {
875 buf.level++;
876 s.finalbody.statementToBuffer(buf, hgs);
877 buf.level--;
878 }
879 }
880
881 void visitScopeGuard(ScopeGuardStatement s)
882 {
883 buf.writestring(Token.toString(s.tok));
884 buf.writeByte(' ');
885 if (s.statement)
886 s.statement.statementToBuffer(buf, hgs);
887 }
888
889 void visitThrow(ThrowStatement s)
890 {
891 buf.writestring("throw ");
892 s.exp.expressionToBuffer(buf, hgs);
893 buf.writeByte(';');
894 buf.writenl();
895 }
896
897 void visitDebug(DebugStatement s)
898 {
899 if (s.statement)
900 {
901 s.statement.statementToBuffer(buf, hgs);
902 }
903 }
904
905 void visitGoto(GotoStatement s)
906 {
907 buf.writestring("goto ");
908 buf.writestring(s.ident.toString());
909 buf.writeByte(';');
910 buf.writenl();
911 }
912
913 void visitLabel(LabelStatement s)
914 {
915 buf.writestring(s.ident.toString());
916 buf.writeByte(':');
917 buf.writenl();
918 if (s.statement)
919 s.statement.statementToBuffer(buf, hgs);
920 }
921
922 void visitAsm(AsmStatement s)
923 {
924 buf.writestring("asm { ");
925 Token* t = s.tokens;
926 buf.level++;
927 while (t)
928 {
929 buf.writestring(t.toString());
930 if (t.next &&
931 t.value != TOK.min &&
932 t.value != TOK.comma && t.next.value != TOK.comma &&
933 t.value != TOK.leftBracket && t.next.value != TOK.leftBracket &&
934 t.next.value != TOK.rightBracket &&
935 t.value != TOK.leftParenthesis && t.next.value != TOK.leftParenthesis &&
936 t.next.value != TOK.rightParenthesis &&
937 t.value != TOK.dot && t.next.value != TOK.dot)
938 {
939 buf.writeByte(' ');
940 }
941 t = t.next;
942 }
943 buf.level--;
944 buf.writestring("; }");
945 buf.writenl();
946 }
947
948 void visitInlineAsm(InlineAsmStatement s)
949 {
950 visitAsm(s);
951 }
952
953 void visitGccAsm(GccAsmStatement s)
954 {
955 visitAsm(s);
956 }
957
958 void visitImport(ImportStatement s)
959 {
960 foreach (imp; *s.imports)
961 {
962 imp.dsymbolToBuffer(buf, hgs);
963 }
964 }
965
966 mixin VisitStatement!void visit;
967 visit.VisitStatement(s);
968 }
969
970 private void dsymbolToBuffer(Dsymbol s, ref OutBuffer buf, ref HdrGenState hgs)
971 {
972 toCBuffer(s, buf, hgs);
973 }
974
975 void toCBuffer(Dsymbol s, ref OutBuffer buf, ref HdrGenState hgs)
976 {
977 void visitDsymbol(Dsymbol s)
978 {
979 buf.writestring(s.toChars());
980 }
981
982 void visitStaticAssert(StaticAssert s)
983 {
984 buf.writestring(s.kind());
985 buf.writeByte('(');
986 s.exp.expressionToBuffer(buf, hgs);
987 if (s.msgs)
988 {
989 foreach (m; (*s.msgs)[])
990 {
991 buf.writestring(", ");
992 m.expressionToBuffer(buf, hgs);
993 }
994 }
995 buf.writestring(");");
996 buf.writenl();
997 }
998
999 void visitDebugSymbol(DebugSymbol s)
1000 {
1001 buf.writestring("debug = ");
1002 buf.writestring(s.ident.toString());
1003 buf.writeByte(';');
1004 buf.writenl();
1005 }
1006
1007 void visitVersionSymbol(VersionSymbol s)
1008 {
1009 buf.writestring("version = ");
1010 buf.writestring(s.ident.toString());
1011 buf.writeByte(';');
1012 buf.writenl();
1013 }
1014
1015 void visitEnumMember(EnumMember em)
1016 {
1017 if (em.type)
1018 typeToBuffer(em.type, em.ident, buf, hgs);
1019 else
1020 buf.writestring(em.ident.toString());
1021 if (em.value)
1022 {
1023 buf.writestring(" = ");
1024 em.value.expressionToBuffer(buf, hgs);
1025 }
1026 }
1027
1028 void visitImport(Import imp)
1029 {
1030 if (hgs.hdrgen && imp.id == Id.object)
1031 return; // object is imported by default
1032 if (imp.isstatic)
1033 buf.writestring("static ");
1034 buf.writestring("import ");
1035 if (imp.aliasId)
1036 {
1037 buf.printf("%s = ", imp.aliasId.toChars());
1038 }
1039 foreach (const pid; imp.packages)
1040 {
1041 buf.write(pid.toString());
1042 buf.writeByte('.');
1043 }
1044 buf.writestring(imp.id.toString());
1045 if (imp.names.length)
1046 {
1047 buf.writestring(" : ");
1048 foreach (const i, const name; imp.names)
1049 {
1050 if (i)
1051 buf.writestring(", ");
1052 const _alias = imp.aliases[i];
1053 if (_alias)
1054 buf.printf("%s = %s", _alias.toChars(), name.toChars());
1055 else
1056 buf.writestring(name.toChars());
1057 }
1058 }
1059 buf.writeByte(';');
1060 buf.writenl();
1061 }
1062
1063 void visitAliasThis(AliasThis d)
1064 {
1065 buf.writestring("alias ");
1066 buf.writestring(d.ident.toString());
1067 buf.writestring(" this;\n");
1068 }
1069
1070 void visitAttribDeclaration(AttribDeclaration d)
1071 {
1072 bool hasSTC;
1073 if (auto stcd = d.isStorageClassDeclaration)
1074 {
1075 hasSTC = stcToBuffer(buf, stcd.stc);
1076 }
1077
1078 if (!d.decl)
1079 {
1080 buf.writeByte(';');
1081 buf.writenl();
1082 return;
1083 }
1084 if (d.decl.length == 0 || (hgs.hdrgen && d.decl.length == 1 && (*d.decl)[0].isUnitTestDeclaration()))
1085 {
1086 // hack for https://issues.dlang.org/show_bug.cgi?id=8081
1087 if (hasSTC) buf.writeByte(' ');
1088 buf.writestring("{}");
1089 }
1090 else if (d.decl.length == 1)
1091 {
1092 if (hasSTC) buf.writeByte(' ');
1093 toCBuffer((*d.decl)[0], buf, hgs);
1094 return;
1095 }
1096 else
1097 {
1098 buf.writenl();
1099 buf.writeByte('{');
1100 buf.writenl();
1101 buf.level++;
1102 foreach (de; *d.decl)
1103 toCBuffer(de, buf, hgs);
1104 buf.level--;
1105 buf.writeByte('}');
1106 }
1107 buf.writenl();
1108 }
1109
1110 void visitStorageClassDeclaration(StorageClassDeclaration d)
1111 {
1112 visitAttribDeclaration(d);
1113 }
1114
1115 void visitDeprecatedDeclaration(DeprecatedDeclaration d)
1116 {
1117 buf.writestring("deprecated(");
1118 d.msg.expressionToBuffer(buf, hgs);
1119 buf.writestring(") ");
1120 visitAttribDeclaration(d);
1121 }
1122
1123 void visitLinkDeclaration(LinkDeclaration d)
1124 {
1125 buf.writestring("extern (");
1126 buf.writestring(linkageToString(d.linkage));
1127 buf.writestring(") ");
1128 visitAttribDeclaration(d);
1129 }
1130
1131 void visitCPPMangleDeclaration(CPPMangleDeclaration d)
1132 {
1133 string s;
1134 final switch (d.cppmangle)
1135 {
1136 case CPPMANGLE.asClass:
1137 s = "class";
1138 break;
1139 case CPPMANGLE.asStruct:
1140 s = "struct";
1141 break;
1142 case CPPMANGLE.def:
1143 break;
1144 }
1145 buf.writestring("extern (C++, ");
1146 buf.writestring(s);
1147 buf.writestring(") ");
1148 visitAttribDeclaration(d);
1149 }
1150
1151 void visitVisibilityDeclaration(VisibilityDeclaration d)
1152 {
1153 visibilityToBuffer(buf, d.visibility);
1154 AttribDeclaration ad = cast(AttribDeclaration)d;
1155 if (ad.decl.length <= 1)
1156 buf.writeByte(' ');
1157 if (ad.decl.length == 1 && (*ad.decl)[0].isVisibilityDeclaration)
1158 visitAttribDeclaration((*ad.decl)[0].isVisibilityDeclaration);
1159 else
1160 visitAttribDeclaration(d);
1161 }
1162
1163 void visitAlignDeclaration(AlignDeclaration d)
1164 {
1165 if (d.exps)
1166 {
1167 foreach (i, exp; (*d.exps)[])
1168 {
1169 if (i)
1170 buf.writeByte(' ');
1171 buf.writestring("align (");
1172 toCBuffer(exp, buf, hgs);
1173 buf.writeByte(')');
1174 }
1175 if (d.decl && d.decl.length < 2)
1176 buf.writeByte(' ');
1177 }
1178 else
1179 buf.writestring("align ");
1180
1181 visitAttribDeclaration(d.isAttribDeclaration());
1182 }
1183
1184 void visitAnonDeclaration(AnonDeclaration d)
1185 {
1186 buf.writestring(d.isunion ? "union" : "struct");
1187 buf.writenl();
1188 buf.writestring("{");
1189 buf.writenl();
1190 buf.level++;
1191 if (d.decl)
1192 {
1193 foreach (de; *d.decl)
1194 toCBuffer(de, buf, hgs);
1195 }
1196 buf.level--;
1197 buf.writestring("}");
1198 buf.writenl();
1199 }
1200
1201 void visitPragmaDeclaration(PragmaDeclaration d)
1202 {
1203 buf.writestring("pragma (");
1204 buf.writestring(d.ident.toString());
1205 if (d.args && d.args.length)
1206 {
1207 buf.writestring(", ");
1208 argsToBuffer(d.args, buf, hgs);
1209 }
1210
1211 buf.writeByte(')');
1212
1213 // https://issues.dlang.org/show_bug.cgi?id=14690
1214 // Unconditionally perform a full output dump
1215 // for `pragma(inline)` declarations.
1216 const saved = hgs.doFuncBodies;
1217 if (d.ident == Id.Pinline)
1218 hgs.doFuncBodies = true;
1219
1220 visitAttribDeclaration(d);
1221 hgs.doFuncBodies = saved;
1222 }
1223
1224 void visitConditionalDeclaration(ConditionalDeclaration d)
1225 {
1226 d.condition.conditionToBuffer(buf, hgs);
1227 if (d.decl || d.elsedecl)
1228 {
1229 buf.writenl();
1230 buf.writeByte('{');
1231 buf.writenl();
1232 buf.level++;
1233 if (d.decl)
1234 {
1235 foreach (de; *d.decl)
1236 toCBuffer(de, buf, hgs);
1237 }
1238 buf.level--;
1239 buf.writeByte('}');
1240 if (d.elsedecl)
1241 {
1242 buf.writenl();
1243 buf.writestring("else");
1244 buf.writenl();
1245 buf.writeByte('{');
1246 buf.writenl();
1247 buf.level++;
1248 foreach (de; *d.elsedecl)
1249 toCBuffer(de, buf, hgs);
1250 buf.level--;
1251 buf.writeByte('}');
1252 }
1253 }
1254 else
1255 buf.writeByte(':');
1256 buf.writenl();
1257 }
1258
1259 void visitStaticForeachDeclaration(StaticForeachDeclaration s)
1260 {
1261 void foreachWithoutBody(ForeachStatement s)
1262 {
1263 buf.writestring(Token.toString(s.op));
1264 buf.writestring(" (");
1265 foreach (i, p; *s.parameters)
1266 {
1267 if (i)
1268 buf.writestring(", ");
1269 if (stcToBuffer(buf, p.storageClass))
1270 buf.writeByte(' ');
1271 if (p.type)
1272 typeToBuffer(p.type, p.ident, buf, hgs);
1273 else
1274 buf.writestring(p.ident.toString());
1275 }
1276 buf.writestring("; ");
1277 s.aggr.expressionToBuffer(buf, hgs);
1278 buf.writeByte(')');
1279 buf.writenl();
1280 }
1281
1282 void foreachRangeWithoutBody(ForeachRangeStatement s)
1283 {
1284 /* s.op ( param ; lwr .. upr )
1285 */
1286 buf.writestring(Token.toString(s.op));
1287 buf.writestring(" (");
1288 if (s.param.type)
1289 typeToBuffer(s.param.type, s.param.ident, buf, hgs);
1290 else
1291 buf.writestring(s.param.ident.toString());
1292 buf.writestring("; ");
1293 s.lwr.expressionToBuffer(buf, hgs);
1294 buf.writestring(" .. ");
1295 s.upr.expressionToBuffer(buf, hgs);
1296 buf.writeByte(')');
1297 buf.writenl();
1298 }
1299
1300 buf.writestring("static ");
1301 if (s.sfe.aggrfe)
1302 {
1303 foreachWithoutBody(s.sfe.aggrfe);
1304 }
1305 else
1306 {
1307 assert(s.sfe.rangefe);
1308 foreachRangeWithoutBody(s.sfe.rangefe);
1309 }
1310 buf.writeByte('{');
1311 buf.writenl();
1312 buf.level++;
1313 visitAttribDeclaration(s);
1314 buf.level--;
1315 buf.writeByte('}');
1316 buf.writenl();
1317
1318 }
1319
1320 void visitMixinDeclaration(MixinDeclaration d)
1321 {
1322 buf.writestring("mixin(");
1323 argsToBuffer(d.exps, buf, hgs, null);
1324 buf.writestring(");");
1325 buf.writenl();
1326 }
1327
1328 void visitUserAttributeDeclaration(UserAttributeDeclaration d)
1329 {
1330 buf.writestring("@(");
1331 argsToBuffer(d.atts, buf, hgs);
1332 buf.writeByte(')');
1333 visitAttribDeclaration(d);
1334 }
1335
1336 void visitTemplateConstraint(Expression constraint)
1337 {
1338 if (!constraint)
1339 return;
1340 buf.writestring(" if (");
1341 constraint.expressionToBuffer(buf, hgs);
1342 buf.writeByte(')');
1343 }
1344
1345 /// Returns: whether `do` is needed to write the function body
1346 bool contractsToBuffer(FuncDeclaration f)
1347 {
1348 bool requireDo = false;
1349 // in{}
1350 if (f.frequires)
1351 {
1352 foreach (frequire; *f.frequires)
1353 {
1354 buf.writestring("in");
1355 if (auto es = frequire.isExpStatement())
1356 {
1357 assert(es.exp && es.exp.op == EXP.assert_);
1358 buf.writestring(" (");
1359 (cast(AssertExp)es.exp).e1.expressionToBuffer(buf, hgs);
1360 buf.writeByte(')');
1361 buf.writenl();
1362 requireDo = false;
1363 }
1364 else
1365 {
1366 buf.writenl();
1367 frequire.statementToBuffer(buf, hgs);
1368 requireDo = true;
1369 }
1370 }
1371 }
1372 // out{}
1373 if (f.fensures)
1374 {
1375 foreach (fensure; *f.fensures)
1376 {
1377 buf.writestring("out");
1378 if (auto es = fensure.ensure.isExpStatement())
1379 {
1380 assert(es.exp && es.exp.op == EXP.assert_);
1381 buf.writestring(" (");
1382 if (fensure.id)
1383 {
1384 buf.writestring(fensure.id.toString());
1385 }
1386 buf.writestring("; ");
1387 (cast(AssertExp)es.exp).e1.expressionToBuffer(buf, hgs);
1388 buf.writeByte(')');
1389 buf.writenl();
1390 requireDo = false;
1391 }
1392 else
1393 {
1394 if (fensure.id)
1395 {
1396 buf.writeByte('(');
1397 buf.writestring(fensure.id.toString());
1398 buf.writeByte(')');
1399 }
1400 buf.writenl();
1401 fensure.ensure.statementToBuffer(buf, hgs);
1402 requireDo = true;
1403 }
1404 }
1405 }
1406 return requireDo;
1407 }
1408
1409 void bodyToBuffer(FuncDeclaration f)
1410 {
1411 if (!f.fbody || (hgs.hdrgen && hgs.doFuncBodies == false && !hgs.autoMember && !hgs.tpltMember && !hgs.insideFuncBody))
1412 {
1413 if (!f.fbody && (f.fensures || f.frequires))
1414 {
1415 buf.writenl();
1416 contractsToBuffer(f);
1417 }
1418 buf.writeByte(';');
1419 buf.writenl();
1420 return;
1421 }
1422
1423 // there is no way to know if a function is nested
1424 // or not after parsing. We need scope information
1425 // for that, which is avaible during semantic
1426 // analysis. To overcome that, a simple mechanism
1427 // is implemented: everytime we print a function
1428 // body (templated or not) we increment a counter.
1429 // We decredement the counter when we stop
1430 // printing the function body.
1431 ++hgs.insideFuncBody;
1432 scope(exit) { --hgs.insideFuncBody; }
1433
1434 const savetlpt = hgs.tpltMember;
1435 const saveauto = hgs.autoMember;
1436 hgs.tpltMember = 0;
1437 hgs.autoMember = 0;
1438 buf.writenl();
1439 bool requireDo = contractsToBuffer(f);
1440
1441 if (requireDo)
1442 {
1443 buf.writestring("do");
1444 buf.writenl();
1445 }
1446 buf.writeByte('{');
1447 buf.writenl();
1448 buf.level++;
1449 f.fbody.statementToBuffer(buf, hgs);
1450 buf.level--;
1451 buf.writeByte('}');
1452 buf.writenl();
1453 hgs.tpltMember = savetlpt;
1454 hgs.autoMember = saveauto;
1455 }
1456
1457 void visitBaseClasses(ClassDeclaration d)
1458 {
1459 if (!d || !d.baseclasses.length)
1460 return;
1461 if (!d.isAnonymous())
1462 buf.writestring(" : ");
1463 foreach (i, b; *d.baseclasses)
1464 {
1465 if (i)
1466 buf.writestring(", ");
1467 typeToBuffer(b.type, null, buf, hgs);
1468 }
1469 }
1470
1471 bool visitEponymousMember(TemplateDeclaration d)
1472 {
1473 if (!d.members || d.members.length != 1)
1474 return false;
1475 Dsymbol onemember = (*d.members)[0];
1476 if (onemember.ident != d.ident)
1477 return false;
1478 if (FuncDeclaration fd = onemember.isFuncDeclaration())
1479 {
1480 assert(fd.type);
1481 if (stcToBuffer(buf, fd.storage_class))
1482 buf.writeByte(' ');
1483 functionToBufferFull(cast(TypeFunction)fd.type, buf, d.ident, hgs, d);
1484 visitTemplateConstraint(d.constraint);
1485 hgs.tpltMember++;
1486 bodyToBuffer(fd);
1487 hgs.tpltMember--;
1488 return true;
1489 }
1490 if (AggregateDeclaration ad = onemember.isAggregateDeclaration())
1491 {
1492 buf.writestring(ad.kind());
1493 buf.writeByte(' ');
1494 buf.writestring(ad.ident.toString());
1495 buf.writeByte('(');
1496 visitTemplateParameters(hgs.ddoc ? d.origParameters : d.parameters, buf, hgs);
1497 buf.writeByte(')');
1498 visitTemplateConstraint(d.constraint);
1499 visitBaseClasses(ad.isClassDeclaration());
1500 hgs.tpltMember++;
1501 if (ad.members)
1502 {
1503 buf.writenl();
1504 buf.writeByte('{');
1505 buf.writenl();
1506 buf.level++;
1507 foreach (s; *ad.members)
1508 toCBuffer(s, buf, hgs);
1509 buf.level--;
1510 buf.writeByte('}');
1511 }
1512 else
1513 buf.writeByte(';');
1514 buf.writenl();
1515 hgs.tpltMember--;
1516 return true;
1517 }
1518 if (VarDeclaration vd = onemember.isVarDeclaration())
1519 {
1520 if (d.constraint)
1521 return false;
1522 if (stcToBuffer(buf, vd.storage_class))
1523 buf.writeByte(' ');
1524 if (vd.type)
1525 typeToBuffer(vd.type, vd.ident, buf, hgs);
1526 else
1527 buf.writestring(vd.ident.toString());
1528 buf.writeByte('(');
1529 visitTemplateParameters(hgs.ddoc ? d.origParameters : d.parameters, buf, hgs);
1530 buf.writeByte(')');
1531 if (vd._init)
1532 {
1533 buf.writestring(" = ");
1534 ExpInitializer ie = vd._init.isExpInitializer();
1535 if (ie && (ie.exp.op == EXP.construct || ie.exp.op == EXP.blit))
1536 (cast(AssignExp)ie.exp).e2.expressionToBuffer(buf, hgs);
1537 else
1538 vd._init.initializerToBuffer(buf, hgs);
1539 }
1540 buf.writeByte(';');
1541 buf.writenl();
1542 return true;
1543 }
1544 return false;
1545 }
1546
1547 void visitTemplateDeclaration(TemplateDeclaration d)
1548 {
1549 version (none)
1550 {
1551 // Should handle template functions for doc generation
1552 if (onemember && onemember.isFuncDeclaration())
1553 buf.writestring("foo ");
1554 }
1555 if ((hgs.hdrgen || hgs.fullDump) && visitEponymousMember(d))
1556 return;
1557 if (hgs.ddoc)
1558 buf.writestring(d.kind());
1559 else
1560 buf.writestring("template");
1561 buf.writeByte(' ');
1562 buf.writestring(d.ident.toString());
1563 buf.writeByte('(');
1564 visitTemplateParameters(hgs.ddoc ? d.origParameters : d.parameters, buf, hgs);
1565 buf.writeByte(')');
1566 visitTemplateConstraint(d.constraint);
1567 if (hgs.hdrgen || hgs.fullDump)
1568 {
1569 hgs.tpltMember++;
1570 buf.writenl();
1571 buf.writeByte('{');
1572 buf.writenl();
1573 buf.level++;
1574 foreach (s; *d.members)
1575 toCBuffer(s, buf, hgs);
1576 buf.level--;
1577 buf.writeByte('}');
1578 buf.writenl();
1579 hgs.tpltMember--;
1580 }
1581 }
1582
1583 void visitTemplateInstance(TemplateInstance ti)
1584 {
1585 buf.writestring(ti.name.toChars());
1586 tiargsToBuffer(ti, buf, hgs);
1587
1588 if (hgs.fullDump)
1589 {
1590 buf.writenl();
1591 dumpTemplateInstance(ti, buf, hgs);
1592 }
1593 }
1594
1595 void visitTemplateMixin(TemplateMixin tm)
1596 {
1597 buf.writestring("mixin ");
1598 typeToBuffer(tm.tqual, null, buf, hgs);
1599 tiargsToBuffer(tm, buf, hgs);
1600 if (tm.ident && memcmp(tm.ident.toString().ptr, cast(const(char)*) "__mixin", 7) != 0)
1601 {
1602 buf.writeByte(' ');
1603 buf.writestring(tm.ident.toString());
1604 }
1605 buf.writeByte(';');
1606 buf.writenl();
1607 if (hgs.fullDump)
1608 dumpTemplateInstance(tm, buf, hgs);
1609 }
1610
1611 void visitEnumDeclaration(EnumDeclaration d)
1612 {
1613 auto oldInEnumDecl = hgs.inEnumDecl;
1614 scope(exit) hgs.inEnumDecl = oldInEnumDecl;
1615 hgs.inEnumDecl = d;
1616 buf.writestring("enum ");
1617 if (d.ident)
1618 {
1619 buf.writestring(d.ident.toString());
1620 }
1621 if (d.memtype)
1622 {
1623 buf.writestring(" : ");
1624 typeToBuffer(d.memtype, null, buf, hgs);
1625 }
1626 if (!d.members)
1627 {
1628 buf.writeByte(';');
1629 buf.writenl();
1630 return;
1631 }
1632 buf.writenl();
1633 buf.writeByte('{');
1634 buf.writenl();
1635 buf.level++;
1636 foreach (em; *d.members)
1637 {
1638 if (!em)
1639 continue;
1640 toCBuffer(em, buf, hgs);
1641 buf.writeByte(',');
1642 buf.writenl();
1643 }
1644 buf.level--;
1645 buf.writeByte('}');
1646 buf.writenl();
1647
1648 if (!hgs.importcHdr || !d.ident)
1649 return;
1650
1651 /* C enums get their members inserted into the symbol table of the enum declaration.
1652 * This is accomplished in addEnumMembersToSymtab().
1653 * But when generating D code from ImportC code, D rulez are followed.
1654 * Accomplish this by generating an alias declaration for each member
1655 */
1656 foreach (em; *d.members)
1657 {
1658 if (!em)
1659 continue;
1660 buf.writestring("alias ");
1661 buf.writestring(em.ident.toString);
1662 buf.writestring(" = ");
1663 buf.writestring(d.ident.toString);
1664 buf.writeByte('.');
1665 buf.writestring(em.ident.toString);
1666 buf.writeByte(';');
1667 buf.writenl();
1668 }
1669 }
1670
1671 void visitNspace(Nspace d)
1672 {
1673 buf.writestring("extern (C++, ");
1674 buf.writestring(d.ident.toString());
1675 buf.writeByte(')');
1676 buf.writenl();
1677 buf.writeByte('{');
1678 buf.writenl();
1679 buf.level++;
1680 foreach (s; *d.members)
1681 toCBuffer(s, buf, hgs);
1682 buf.level--;
1683 buf.writeByte('}');
1684 buf.writenl();
1685 }
1686
1687 void visitStructDeclaration(StructDeclaration d)
1688 {
1689 //printf("visitStructDeclaration() %s\n", d.ident.toChars());
1690 buf.writestring(d.kind());
1691 buf.writeByte(' ');
1692 if (!d.isAnonymous())
1693 buf.writestring(d.toChars());
1694 if (!d.members)
1695 {
1696 buf.writeByte(';');
1697 buf.writenl();
1698 return;
1699 }
1700 buf.writenl();
1701 buf.writeByte('{');
1702 buf.writenl();
1703 buf.level++;
1704 hgs.insideAggregate++;
1705 foreach (s; *d.members)
1706 toCBuffer(s, buf, hgs);
1707 hgs.insideAggregate--;
1708 buf.level--;
1709 buf.writeByte('}');
1710 buf.writenl();
1711 }
1712
1713 void visitClassDeclaration(ClassDeclaration d)
1714 {
1715 if (!d.isAnonymous())
1716 {
1717 buf.writestring(d.kind());
1718 buf.writeByte(' ');
1719 buf.writestring(d.ident.toString());
1720 }
1721 visitBaseClasses(d);
1722 if (d.members)
1723 {
1724 buf.writenl();
1725 buf.writeByte('{');
1726 buf.writenl();
1727 buf.level++;
1728 hgs.insideAggregate++;
1729 foreach (s; *d.members)
1730 toCBuffer(s, buf, hgs);
1731 hgs.insideAggregate--;
1732 buf.level--;
1733 buf.writeByte('}');
1734 }
1735 else
1736 buf.writeByte(';');
1737 buf.writenl();
1738 }
1739
1740 void visitAliasDeclaration(AliasDeclaration d)
1741 {
1742 if (d.storage_class & STC.local)
1743 return;
1744 if (d.hidden)
1745 return;
1746 buf.writestring("alias ");
1747 if (d.aliassym)
1748 {
1749 buf.writestring(d.ident.toString());
1750 buf.writestring(" = ");
1751 if (stcToBuffer(buf, d.storage_class))
1752 buf.writeByte(' ');
1753 /*
1754 https://issues.dlang.org/show_bug.cgi?id=23223
1755 https://issues.dlang.org/show_bug.cgi?id=23222
1756 This special case (initially just for modules) avoids some segfaults
1757 and nicer -vcg-ast output.
1758 */
1759 if (d.aliassym.isModule())
1760 {
1761 buf.writestring(d.aliassym.ident.toString());
1762 }
1763 else
1764 {
1765 toCBuffer(d.aliassym, buf, hgs);
1766 }
1767 }
1768 else if (d.type.ty == Tfunction)
1769 {
1770 if (stcToBuffer(buf, d.storage_class))
1771 buf.writeByte(' ');
1772 typeToBuffer(d.type, d.ident, buf, hgs);
1773 }
1774 else if (d.ident)
1775 {
1776 hgs.declstring = (d.ident == Id.string || d.ident == Id.wstring || d.ident == Id.dstring);
1777 buf.writestring(d.ident.toString());
1778 buf.writestring(" = ");
1779 if (stcToBuffer(buf, d.storage_class))
1780 buf.writeByte(' ');
1781 hgs.inCAlias = hgs.importcHdr;
1782 typeToBuffer(d.type, null, buf, hgs);
1783 hgs.inCAlias = false;
1784 hgs.declstring = false;
1785 }
1786 buf.writeByte(';');
1787 buf.writenl();
1788 }
1789
1790 void visitAliasAssign(AliasAssign d)
1791 {
1792 buf.writestring(d.ident.toString());
1793 buf.writestring(" = ");
1794 if (d.aliassym)
1795 toCBuffer(d.aliassym, buf, hgs);
1796 else // d.type
1797 typeToBuffer(d.type, null, buf, hgs);
1798 buf.writeByte(';');
1799 buf.writenl();
1800 }
1801
1802 void visitVarDeclaration(VarDeclaration d)
1803 {
1804 if (d.storage_class & STC.local)
1805 return;
1806 visitVarDecl(d, false, buf, hgs);
1807 buf.writeByte(';');
1808 buf.writenl();
1809 }
1810
1811 void visitFuncDeclaration(FuncDeclaration f)
1812 {
1813 //printf("FuncDeclaration::toCBuffer() '%s'\n", f.toChars());
1814
1815 // https://issues.dlang.org/show_bug.cgi?id=24891
1816 // return/scope storage classes are printed as part of function type
1817 if (stcToBuffer(buf, f.storage_class & ~(STC.scope_ | STC.return_ | STC.returnScope)))
1818 buf.writeByte(' ');
1819 typeToBuffer(f.type, f.ident, buf, hgs);
1820 auto tf = f.type.isTypeFunction();
1821
1822 if (hgs.hdrgen && tf)
1823 {
1824 // if the return type is missing (e.g. ref functions or auto)
1825 // https://issues.dlang.org/show_bug.cgi?id=20090
1826 // constructors are an exception: they don't have an explicit return
1827 // type but we still don't output the body.
1828 if ((!f.isCtorDeclaration() && !tf.next) || f.storage_class & STC.auto_)
1829 {
1830 hgs.autoMember++;
1831 bodyToBuffer(f);
1832 hgs.autoMember--;
1833 }
1834 else if (hgs.tpltMember == 0 && hgs.doFuncBodies == false && !hgs.insideFuncBody)
1835 {
1836 if (!f.fbody)
1837 {
1838 // this can happen on interfaces / abstract functions, see `allowsContractWithoutBody`
1839 if (f.fensures || f.frequires)
1840 buf.writenl();
1841 contractsToBuffer(f);
1842 }
1843 buf.writeByte(';');
1844 buf.writenl();
1845 }
1846 else
1847 bodyToBuffer(f);
1848 }
1849 else
1850 bodyToBuffer(f);
1851 }
1852
1853 void visitFuncLiteralDeclaration(FuncLiteralDeclaration f)
1854 {
1855 if (f.type.ty == Terror)
1856 {
1857 buf.writestring("__error");
1858 return;
1859 }
1860 if (f.tok != TOK.reserved && !hgs.errorMsg)
1861 {
1862 buf.writestring(f.kind());
1863 buf.writeByte(' ');
1864 }
1865 TypeFunction tf = cast(TypeFunction)f.type;
1866
1867 if (!f.inferRetType && tf.next)
1868 typeToBuffer(tf.next, null, buf, hgs);
1869 parametersToBuffer(tf.parameterList, buf, hgs);
1870
1871 // https://issues.dlang.org/show_bug.cgi?id=20074
1872 void printAttribute(string str)
1873 {
1874 buf.writeByte(' ');
1875 buf.writestring(str);
1876 }
1877
1878 if (!hgs.errorMsg)
1879 tf.attributesApply(&printAttribute);
1880
1881 CompoundStatement cs = f.fbody.isCompoundStatement();
1882 Statement s1;
1883 if (f.semanticRun >= PASS.semantic3done && cs)
1884 {
1885 s1 = (*cs.statements)[cs.statements.length - 1];
1886 }
1887 else
1888 s1 = !cs ? f.fbody : null;
1889 ReturnStatement rs = s1 ? s1.endsWithReturnStatement() : null;
1890 if (rs && rs.exp)
1891 {
1892 buf.writestring(" => ");
1893 rs.exp.expressionToBuffer(buf, hgs);
1894 }
1895 else
1896 {
1897 hgs.tpltMember++;
1898 bodyToBuffer(f);
1899 hgs.tpltMember--;
1900 }
1901 }
1902
1903 void visitPostBlitDeclaration(PostBlitDeclaration d)
1904 {
1905 if (stcToBuffer(buf, d.storage_class))
1906 buf.writeByte(' ');
1907 buf.writestring("this(this)");
1908 bodyToBuffer(d);
1909 }
1910
1911 void visitDtorDeclaration(DtorDeclaration d)
1912 {
1913 if (stcToBuffer(buf, d.storage_class))
1914 buf.writeByte(' ');
1915 buf.writestring("~this()");
1916 bodyToBuffer(d);
1917 }
1918
1919 void visitStaticCtorDeclaration(StaticCtorDeclaration d)
1920 {
1921 if (stcToBuffer(buf, d.storage_class & ~STC.static_))
1922 buf.writeByte(' ');
1923 if (d.isSharedStaticCtorDeclaration())
1924 buf.writestring("shared ");
1925 buf.writestring("static this()");
1926 if (hgs.hdrgen && !hgs.tpltMember)
1927 {
1928 buf.writeByte(';');
1929 buf.writenl();
1930 }
1931 else
1932 bodyToBuffer(d);
1933 }
1934
1935 void visitStaticDtorDeclaration(StaticDtorDeclaration d)
1936 {
1937 if (stcToBuffer(buf, d.storage_class & ~STC.static_))
1938 buf.writeByte(' ');
1939 if (d.isSharedStaticDtorDeclaration())
1940 buf.writestring("shared ");
1941 buf.writestring("static ~this()");
1942 if (hgs.hdrgen && !hgs.tpltMember)
1943 {
1944 buf.writeByte(';');
1945 buf.writenl();
1946 }
1947 else
1948 bodyToBuffer(d);
1949 }
1950
1951 void visitInvariantDeclaration(InvariantDeclaration d)
1952 {
1953 if (hgs.hdrgen)
1954 return;
1955 if (stcToBuffer(buf, d.storage_class))
1956 buf.writeByte(' ');
1957 buf.writestring("invariant");
1958 auto es = d.fbody.isExpStatement();
1959 if (es && es.exp && es.exp.op == EXP.assert_)
1960 {
1961 buf.writestring(" (");
1962 (cast(AssertExp)es.exp).e1.expressionToBuffer(buf, hgs);
1963 buf.writestring(");");
1964 buf.writenl();
1965 }
1966 else
1967 {
1968 bodyToBuffer(d);
1969 }
1970 }
1971
1972 void visitUnitTestDeclaration(UnitTestDeclaration d)
1973 {
1974 if (hgs.hdrgen)
1975 return;
1976 if (stcToBuffer(buf, d.storage_class))
1977 buf.writeByte(' ');
1978 buf.writestring("unittest");
1979 bodyToBuffer(d);
1980 }
1981
1982 void visitBitFieldDeclaration(BitFieldDeclaration d)
1983 {
1984 if (stcToBuffer(buf, d.storage_class))
1985 buf.writeByte(' ');
1986 Identifier id = d.isAnonymous() ? null : d.ident;
1987 typeToBuffer(d.type, id, buf, hgs);
1988 buf.writestring(" : ");
1989 d.width.expressionToBuffer(buf, hgs);
1990 buf.writeByte(';');
1991 buf.writenl();
1992 }
1993
1994 void visitNewDeclaration(NewDeclaration d)
1995 {
1996 if (stcToBuffer(buf, d.storage_class & ~STC.static_))
1997 buf.writeByte(' ');
1998 buf.writestring("new();");
1999 }
2000
2001 void visitModule(Module m)
2002 {
2003 moduleToBuffer2(m, buf, hgs);
2004 }
2005
2006 extern (C++)
2007 final class DsymbolPrettyPrintVisitor : Visitor
2008 {
2009 alias visit = Visitor.visit;
2010
2011 public:
2012 override:
2013 void visit(Dsymbol s) { visitDsymbol(s); }
2014 void visit(StaticAssert s) { visitStaticAssert(s); }
2015 void visit(DebugSymbol s) { visitDebugSymbol(s); }
2016 void visit(VersionSymbol s) { visitVersionSymbol(s); }
2017 void visit(EnumMember em) { visitEnumMember(em); }
2018 void visit(Import imp) { visitImport(imp); }
2019 void visit(AliasThis d) { visitAliasThis(d); }
2020 void visit(AttribDeclaration d) { visitAttribDeclaration(d); }
2021 void visit(StorageClassDeclaration d) { visitStorageClassDeclaration(d); }
2022 void visit(DeprecatedDeclaration d) { visitDeprecatedDeclaration(d); }
2023 void visit(LinkDeclaration d) { visitLinkDeclaration(d); }
2024 void visit(CPPMangleDeclaration d) { visitCPPMangleDeclaration(d); }
2025 void visit(VisibilityDeclaration d) { visitVisibilityDeclaration(d); }
2026 void visit(AlignDeclaration d) { visitAlignDeclaration(d); }
2027 void visit(AnonDeclaration d) { visitAnonDeclaration(d); }
2028 void visit(PragmaDeclaration d) { visitPragmaDeclaration(d); }
2029 void visit(ConditionalDeclaration d) { visitConditionalDeclaration(d); }
2030 void visit(StaticForeachDeclaration s) { visitStaticForeachDeclaration(s); }
2031 void visit(MixinDeclaration d) { visitMixinDeclaration(d); }
2032 void visit(UserAttributeDeclaration d) { visitUserAttributeDeclaration(d); }
2033 void visit(TemplateDeclaration d) { visitTemplateDeclaration(d); }
2034 void visit(TemplateInstance ti) { visitTemplateInstance(ti); }
2035 void visit(TemplateMixin tm) { visitTemplateMixin(tm); }
2036 void visit(EnumDeclaration d) { visitEnumDeclaration(d); }
2037 void visit(Nspace d) { visitNspace(d); }
2038 void visit(StructDeclaration d) { visitStructDeclaration(d); }
2039 void visit(ClassDeclaration d) { visitClassDeclaration(d); }
2040 void visit(AliasDeclaration d) { visitAliasDeclaration(d); }
2041 void visit(AliasAssign d) { visitAliasAssign(d); }
2042 void visit(VarDeclaration d) { visitVarDeclaration(d); }
2043 void visit(FuncDeclaration f) { visitFuncDeclaration(f); }
2044 void visit(FuncLiteralDeclaration f) { visitFuncLiteralDeclaration(f); }
2045 void visit(PostBlitDeclaration d) { visitPostBlitDeclaration(d); }
2046 void visit(DtorDeclaration d) { visitDtorDeclaration(d); }
2047 void visit(StaticCtorDeclaration d) { visitStaticCtorDeclaration(d); }
2048 void visit(StaticDtorDeclaration d) { visitStaticDtorDeclaration(d); }
2049 void visit(InvariantDeclaration d) { visitInvariantDeclaration(d); }
2050 void visit(UnitTestDeclaration d) { visitUnitTestDeclaration(d); }
2051 void visit(BitFieldDeclaration d) { visitBitFieldDeclaration(d); }
2052 void visit(NewDeclaration d) { visitNewDeclaration(d); }
2053 void visit(Module m) { visitModule(m); }
2054 }
2055
2056 scope v = new DsymbolPrettyPrintVisitor();
2057 s.accept(v);
2058 }
2059
2060 // Note: this function is not actually `const`, because iterating the
2061 // function parameter list may run dsymbolsemantic on enum types
2062 public
2063 void toCharsMaybeConstraints(const TemplateDeclaration td, ref OutBuffer buf, ref HdrGenState hgs)
2064 {
2065 buf.writestring(td.ident == Id.ctor ? "this" : td.ident.toString());
2066 buf.writeByte('(');
2067 foreach (i, const tp; *td.parameters)
2068 {
2069 if (i)
2070 buf.writestring(", ");
2071 toCBuffer(tp, buf, hgs);
2072 }
2073 buf.writeByte(')');
2074
2075 if (hgs.showOneMember && td.onemember)
2076 {
2077 if (const fd = td.onemember.isFuncDeclaration())
2078 {
2079 if (TypeFunction tf = cast(TypeFunction)fd.type.isTypeFunction())
2080 {
2081 // !! Casted away const
2082 buf.writestring(parametersTypeToChars(tf.parameterList));
2083 if (tf.mod)
2084 {
2085 buf.writeByte(' ');
2086 buf.MODtoBuffer(tf.mod);
2087 }
2088 }
2089 }
2090 }
2091
2092 if (!hgs.skipConstraints &&
2093 td.constraint)
2094 {
2095 buf.writestring(" if (");
2096 toCBuffer(td.constraint, buf, hgs);
2097 buf.writeByte(')');
2098 }
2099 }
2100
2101
2102 /*****************************************
2103 * Pretty-print a template parameter list to a buffer.
2104 */
2105 private void visitTemplateParameters(TemplateParameters* parameters, ref OutBuffer buf, ref HdrGenState hgs)
2106 {
2107 if (!parameters)
2108 return;
2109 foreach (i, p; *parameters)
2110 {
2111 if (i)
2112 buf.writestring(", ");
2113 toCBuffer(p, buf, hgs);
2114 }
2115 }
2116
2117
2118 /*******************************************
2119 * Pretty-print a VarDeclaration to buf.
2120 */
2121 private void visitVarDecl(VarDeclaration v, bool anywritten, ref OutBuffer buf, ref HdrGenState hgs)
2122 {
2123 const bool isextern = hgs.hdrgen &&
2124 !hgs.insideFuncBody &&
2125 !hgs.tpltMember &&
2126 !hgs.insideAggregate &&
2127 !(v.storage_class & STC.manifest);
2128
2129 void vinit(VarDeclaration v)
2130 {
2131 auto ie = v._init.isExpInitializer();
2132 if (ie && (ie.exp.op == EXP.construct || ie.exp.op == EXP.blit))
2133 (cast(AssignExp)ie.exp).e2.expressionToBuffer(buf, hgs);
2134 else
2135 v._init.initializerToBuffer(buf, hgs);
2136 }
2137
2138 const commentIt = hgs.importcHdr && isSpecialCName(v.ident);
2139 if (commentIt)
2140 buf.writestring("/+");
2141
2142 if (anywritten)
2143 {
2144 buf.writestring(", ");
2145 buf.writestring(v.ident.toString());
2146 }
2147 else
2148 {
2149 const bool useTypeof = isextern && v._init && !v.type;
2150 auto stc = v.storage_class;
2151 if (isextern)
2152 stc |= STC.extern_;
2153 if (useTypeof)
2154 stc &= ~STC.auto_;
2155 if (stcToBuffer(buf, stc))
2156 buf.writeByte(' ');
2157 if (v.type)
2158 typeToBuffer(v.type, v.ident, buf, hgs);
2159 else if (useTypeof)
2160 {
2161 buf.writestring("typeof(");
2162 vinit(v);
2163 buf.writestring(") ");
2164 buf.writestring(v.ident.toString());
2165 }
2166 else
2167 buf.writestring(v.ident.toString());
2168 }
2169 if (v._init && !isextern)
2170 {
2171 buf.writestring(" = ");
2172 vinit(v);
2173 }
2174 if (commentIt)
2175 buf.writestring("+/");
2176 }
2177
2178 /*************************************
2179 * The names __DATE__, __TIME__,__EOF__, __VENDOR__, __TIMESTAMP__, __VERSION__
2180 * are special to the D lexer and cannot be used as D source variable names.
2181 * Params:
2182 * id = name to check
2183 * Returns:
2184 * true if special C name
2185 */
2186 private bool isSpecialCName(Identifier id)
2187 {
2188 auto s = id.toString();
2189 if (s.length >= 7 && s[0] == '_' && s[1] == '_' &&
2190 (id == Id.DATE ||
2191 id == Id.TIME ||
2192 id == Id.EOFX ||
2193 id == Id.VENDOR ||
2194 id == Id.TIMESTAMP ||
2195 id == Id.VERSIONX))
2196 return true;
2197 return false;
2198 }
2199
2200 /*********************************************
2201 * Print expression to buffer.
2202 */
2203 private void expressionPrettyPrint(Expression e, ref OutBuffer buf, ref HdrGenState hgs)
2204 {
2205 void visit(Expression e)
2206 {
2207 buf.writestring(EXPtoString(e.op));
2208 }
2209
2210 void visitInteger(IntegerExp e)
2211 {
2212 const ulong v = e.toInteger();
2213 if (e.type)
2214 {
2215 Type t = e.type;
2216 L1:
2217 switch (t.ty)
2218 {
2219 case Tenum:
2220 {
2221 TypeEnum te = cast(TypeEnum)t;
2222 auto sym = te.sym;
2223 if (sym && sym.members && (!hgs.inEnumDecl || hgs.inEnumDecl != sym))
2224 {
2225 foreach (em; *sym.members)
2226 {
2227 if ((cast(EnumMember)em).value.toInteger == v)
2228 {
2229 const id = em.ident.toString();
2230 buf.printf("%s.%.*s", sym.toChars(), cast(int)id.length, id.ptr);
2231 return ;
2232 }
2233 }
2234 }
2235
2236 buf.printf("cast(%s)", te.sym.toChars());
2237 t = te.sym.memtype;
2238 goto L1;
2239 }
2240 case Tchar:
2241 case Twchar:
2242 case Tdchar:
2243 {
2244 const o = buf.length;
2245 writeSingleCharLiteral(buf, cast(dchar) v);
2246 if (hgs.ddoc)
2247 escapeDdocString(buf, o);
2248 break;
2249 }
2250 case Tint8:
2251 buf.writestring("cast(byte)");
2252 goto L2;
2253 case Tint16:
2254 buf.writestring("cast(short)");
2255 goto L2;
2256 case Tint32:
2257 L2:
2258 buf.printf("%d", cast(int)v);
2259 break;
2260 case Tuns8:
2261 buf.writestring("cast(ubyte)");
2262 goto case Tuns32;
2263 case Tuns16:
2264 buf.writestring("cast(ushort)");
2265 goto case Tuns32;
2266 case Tuns32:
2267 buf.printf("%uu", cast(uint)v);
2268 break;
2269 case Tint64:
2270 if (v == long.min)
2271 {
2272 // https://issues.dlang.org/show_bug.cgi?id=23173
2273 // This is a special case because - is not part of the
2274 // integer literal and 9223372036854775808L overflows a long
2275 buf.writestring("cast(long)-9223372036854775808");
2276 }
2277 else
2278 {
2279 buf.printf("%lldL", v);
2280 }
2281 break;
2282 case Tuns64:
2283 buf.printf("%lluLU", v);
2284 break;
2285 case Tbool:
2286 buf.writestring(v ? "true" : "false");
2287 break;
2288 case Tpointer:
2289 buf.writestring("cast(");
2290
2291 HdrGenState hgs2; // should re-examine need for new hgs
2292 hgs2.fullQual = (t.ty == Tclass && !t.mod);
2293 toCBuffer(t, buf, null, hgs2);
2294
2295 buf.writestring(")cast(size_t)");
2296 goto case Tuns64;
2297
2298 case Tvoid:
2299 buf.writestring("cast(void)0");
2300 break;
2301
2302 default:
2303 /* This can happen if errors, such as
2304 * the type is painted on like in fromConstInitializer().
2305 * Just ignore
2306 */
2307 break;
2308 }
2309 }
2310 else if (v & 0x8000000000000000L)
2311 buf.printf("0x%llx", v);
2312 else
2313 buf.print(v);
2314 }
2315
2316 void visitError(ErrorExp e)
2317 {
2318 buf.writestring("__error");
2319 }
2320
2321 void visitVoidInit(VoidInitExp e)
2322 {
2323 buf.writestring("void");
2324 }
2325
2326 void floatToBuffer(Type type, real_t value)
2327 {
2328 .floatToBuffer(type, value, buf, hgs.hdrgen);
2329 }
2330
2331 void visitReal(RealExp e)
2332 {
2333 floatToBuffer(e.type, e.value);
2334 }
2335
2336 void visitComplex(ComplexExp e)
2337 {
2338 /* Print as:
2339 * (re+imi)
2340 */
2341 buf.writeByte('(');
2342 floatToBuffer(e.type, creall(e.value));
2343 buf.writeByte('+');
2344 floatToBuffer(e.type, cimagl(e.value));
2345 buf.writestring("i)");
2346 }
2347
2348 void visitIdentifier(IdentifierExp e)
2349 {
2350 if (hgs.hdrgen || hgs.ddoc)
2351 buf.writestring(e.ident.toHChars2());
2352 else
2353 buf.writestring(e.ident.toString());
2354 }
2355
2356 void visitDsymbol(Dsymbol s)
2357 {
2358 // For -vcg-ast, print internal names such as __invariant, __ctor etc.
2359 // This condition is a bit kludge, and can be cleaned up if the
2360 // mutual dependency `AST.toChars <> hdrgen.d` gets refactored
2361 if (hgs.vcg_ast && s.ident && !s.isTemplateInstance() && !s.isTemplateDeclaration())
2362 buf.writestring(s.ident.toChars());
2363 else
2364 buf.writestring(s.toChars());
2365 }
2366
2367 void visitDsymbolExp(DsymbolExp e)
2368 {
2369 visitDsymbol(e.s);
2370 }
2371
2372 void visitThis(ThisExp e)
2373 {
2374 buf.writestring("this");
2375 }
2376
2377 void visitSuper(SuperExp e)
2378 {
2379 buf.writestring("super");
2380 }
2381
2382 void visitNull(NullExp e)
2383 {
2384 buf.writestring("null");
2385 }
2386
2387 void visitString(StringExp e)
2388 {
2389 if (e.hexString || e.sz == 8)
2390 {
2391 buf.writeByte('x');
2392 buf.writeByte('"');
2393 foreach (i; 0 .. e.len)
2394 buf.printf("%0*llX", e.sz, e.getIndex(i));
2395 buf.writeByte('"');
2396 if (e.postfix)
2397 buf.writeByte(e.postfix);
2398 return;
2399 }
2400 buf.writeByte('"');
2401 const o = buf.length;
2402 foreach (i; 0 .. e.len)
2403 {
2404 writeCharLiteral(buf, e.getCodeUnit(i));
2405 }
2406 if (hgs.ddoc)
2407 escapeDdocString(buf, o);
2408 buf.writeByte('"');
2409 if (e.postfix)
2410 buf.writeByte(e.postfix);
2411 }
2412
2413 void visitInterpolation(InterpExp e)
2414 {
2415 buf.writeByte('i');
2416 buf.writeByte('"');
2417 const o = buf.length;
2418
2419 foreach (idx, str; e.interpolatedSet.parts)
2420 {
2421 if (idx % 2 == 0)
2422 {
2423 foreach(ch; str)
2424 writeCharLiteral(buf, ch);
2425 }
2426 else
2427 {
2428 buf.writeByte('$');
2429 buf.writeByte('(');
2430 foreach(ch; str)
2431 buf.writeByte(ch);
2432 buf.writeByte(')');
2433 }
2434 }
2435
2436 if (hgs.ddoc)
2437 escapeDdocString(buf, o);
2438 buf.writeByte('"');
2439 if (e.postfix)
2440 buf.writeByte(e.postfix);
2441
2442 }
2443
2444 void visitArrayLiteral(ArrayLiteralExp e)
2445 {
2446 buf.writeByte('[');
2447 argsToBuffer(e.elements, buf, hgs, e.basis);
2448 buf.writeByte(']');
2449 }
2450
2451 void visitAssocArrayLiteral(AssocArrayLiteralExp e)
2452 {
2453 buf.writeByte('[');
2454 foreach (i, key; *e.keys)
2455 {
2456 if (i)
2457 buf.writestring(", ");
2458 expToBuffer(key, PREC.assign, buf, hgs);
2459 buf.writeByte(':');
2460 auto value = (*e.values)[i];
2461 expToBuffer(value, PREC.assign, buf, hgs);
2462 }
2463 buf.writeByte(']');
2464 }
2465
2466 void visitStructLiteral(StructLiteralExp e)
2467 {
2468 buf.writestring(e.sd.toChars());
2469 buf.writeByte('(');
2470 // CTFE can generate struct literals that contain an AddrExp pointing
2471 // to themselves, need to avoid infinite recursion:
2472 // struct S { this(int){ this.s = &this; } S* s; }
2473 // const foo = new S(0);
2474 if (e.stageflags & StructLiteralExp.StageFlags.toCBuffer)
2475 buf.writestring("<recursion>");
2476 else
2477 {
2478 const old = e.stageflags;
2479 e.stageflags |= StructLiteralExp.StageFlags.toCBuffer;
2480 argsToBuffer(e.elements, buf, hgs);
2481 e.stageflags = old;
2482 }
2483 buf.writeByte(')');
2484 }
2485
2486 void visitCompoundLiteral(CompoundLiteralExp e)
2487 {
2488 buf.writeByte('(');
2489 typeToBuffer(e.type, null, buf, hgs);
2490 buf.writeByte(')');
2491 e.initializer.initializerToBuffer(buf, hgs);
2492 }
2493
2494 void visitType(TypeExp e)
2495 {
2496 typeToBuffer(e.type, null, buf, hgs);
2497 }
2498
2499 void visitScope(ScopeExp e)
2500 {
2501 if (e.sds.isTemplateInstance())
2502 {
2503 e.sds.dsymbolToBuffer(buf, hgs);
2504 }
2505 else if (hgs.ddoc)
2506 {
2507 // fixes bug 6491
2508 if (auto m = e.sds.isModule())
2509 buf.writestring(m.md.toChars());
2510 else
2511 buf.writestring(e.sds.toChars());
2512 }
2513 else
2514 {
2515 buf.writestring(e.sds.kind());
2516 buf.writeByte(' ');
2517 buf.writestring(e.sds.toChars());
2518 }
2519 }
2520
2521 void visitTemplate(TemplateExp e)
2522 {
2523 buf.writestring(e.td.toChars());
2524 }
2525
2526 void visitNew(NewExp e)
2527 {
2528 if (e.thisexp)
2529 {
2530 expToBuffer(e.thisexp, PREC.primary, buf, hgs);
2531 buf.writeByte('.');
2532 }
2533 buf.writestring("new ");
2534 if (e.placement)
2535 {
2536 buf.writeByte('(');
2537 expToBuffer(e.placement, PREC.assign, buf, hgs);
2538 buf.writeByte(')');
2539 buf.writeByte(' ');
2540 }
2541 typeToBuffer(e.newtype, null, buf, hgs);
2542 if (e.arguments && e.arguments.length)
2543 {
2544 buf.writeByte('(');
2545 argsToBuffer(e.arguments, buf, hgs, null, e.names);
2546 buf.writeByte(')');
2547 }
2548 }
2549
2550 void visitNewAnonClass(NewAnonClassExp e)
2551 {
2552 if (e.thisexp)
2553 {
2554 expToBuffer(e.thisexp, PREC.primary, buf, hgs);
2555 buf.writeByte('.');
2556 }
2557 buf.writestring("new");
2558 if (e.placement)
2559 {
2560 buf.writeByte(' ');
2561 buf.writeByte('(');
2562 expToBuffer(e.placement, PREC.assign, buf, hgs);
2563 buf.writeByte(')');
2564 }
2565 buf.writestring(" class ");
2566 if (e.arguments && e.arguments.length)
2567 {
2568 buf.writeByte('(');
2569 argsToBuffer(e.arguments, buf, hgs);
2570 buf.writeByte(')');
2571 }
2572 if (e.cd)
2573 e.cd.dsymbolToBuffer(buf, hgs);
2574 }
2575
2576 void visitSymOff(SymOffExp e)
2577 {
2578 if (e.offset)
2579 buf.printf("(& %s + %llu)", e.var.toChars(), e.offset);
2580 else if (e.var.isTypeInfoDeclaration())
2581 buf.writestring(e.var.toChars());
2582 else
2583 buf.printf("& %s", e.var.toChars());
2584 }
2585
2586 void visitVar(VarExp e)
2587 {
2588 visitDsymbol(e.var);
2589 }
2590
2591 void visitOver(OverExp e)
2592 {
2593 buf.writestring(e.vars.ident.toString());
2594 }
2595
2596 void visitTuple(TupleExp e)
2597 {
2598 if (e.e0)
2599 {
2600 buf.writeByte('(');
2601 e.e0.expressionPrettyPrint(buf, hgs);
2602 buf.writestring(", AliasSeq!(");
2603 argsToBuffer(e.exps, buf, hgs);
2604 buf.writestring("))");
2605 }
2606 else
2607 {
2608 buf.writestring("AliasSeq!(");
2609 argsToBuffer(e.exps, buf, hgs);
2610 buf.writeByte(')');
2611 }
2612 }
2613
2614 void visitFunc(FuncExp e)
2615 {
2616 e.fd.dsymbolToBuffer(buf, hgs);
2617 //buf.writestring(e.fd.toChars());
2618 }
2619
2620 void visitDeclaration(DeclarationExp e)
2621 {
2622 /* Normal dmd execution won't reach here - regular variable declarations
2623 * are handled in visit(ExpStatement), so here would be used only when
2624 * we'll directly call Expression.toChars() for debugging.
2625 */
2626 if (e.declaration)
2627 {
2628 if (auto var = e.declaration.isVarDeclaration())
2629 {
2630 // For debugging use:
2631 // - Avoid printing newline.
2632 // - Intentionally use the format (Type var;)
2633 // which isn't correct as regular D code.
2634 buf.writeByte('(');
2635
2636 visitVarDecl(var, false, buf, hgs);
2637
2638 buf.writeByte(';');
2639 buf.writeByte(')');
2640 }
2641 else e.declaration.dsymbolToBuffer(buf, hgs);
2642 }
2643 }
2644
2645 void visitTypeid(TypeidExp e)
2646 {
2647 buf.writestring("typeid(");
2648 objectToBuffer(e.obj, buf, hgs);
2649 buf.writeByte(')');
2650 }
2651
2652 void visitTraits(TraitsExp e)
2653 {
2654 buf.writestring("__traits(");
2655 if (e.ident)
2656 buf.writestring(e.ident.toString());
2657 if (e.args)
2658 {
2659 foreach (arg; *e.args)
2660 {
2661 buf.writestring(", ");
2662 objectToBuffer(arg, buf, hgs);
2663 }
2664 }
2665 buf.writeByte(')');
2666 }
2667
2668 void visitHalt(HaltExp e)
2669 {
2670 buf.writestring("halt");
2671 }
2672
2673 void visitIs(IsExp e)
2674 {
2675 buf.writestring("is(");
2676 typeToBuffer(e.targ, e.id, buf, hgs);
2677 if (e.tok2 != TOK.reserved)
2678 {
2679 buf.writeByte(' ');
2680 buf.writestring(Token.toString(e.tok));
2681 buf.writeByte(' ');
2682 buf.writestring(Token.toString(e.tok2));
2683 }
2684 else if (e.tspec)
2685 {
2686 if (e.tok == TOK.colon)
2687 buf.writestring(" : ");
2688 else
2689 buf.writestring(" == ");
2690 typeToBuffer(e.tspec, null, buf, hgs);
2691 }
2692 if (e.parameters && e.parameters.length)
2693 {
2694 buf.writestring(", ");
2695 visitTemplateParameters(e.parameters, buf, hgs);
2696 }
2697 buf.writeByte(')');
2698 }
2699
2700 void visitUna(UnaExp e)
2701 {
2702 buf.writestring(EXPtoString(e.op));
2703 expToBuffer(e.e1, precedence[e.op], buf, hgs);
2704 }
2705
2706 void visitLoweredAssignExp(LoweredAssignExp e)
2707 {
2708 if (hgs.vcg_ast)
2709 {
2710 expressionToBuffer(e.lowering, buf, hgs);
2711 return;
2712 }
2713
2714 visit(cast(BinExp)e);
2715 }
2716 void visitBin(BinExp e)
2717 {
2718 expToBuffer(e.e1, precedence[e.op], buf, hgs);
2719 buf.writeByte(' ');
2720 buf.writestring(EXPtoString(e.op));
2721 buf.writeByte(' ');
2722 expToBuffer(e.e2, cast(PREC)(precedence[e.op] + 1), buf, hgs);
2723 }
2724
2725 void visitComma(CommaExp e)
2726 {
2727 // CommaExp is generated by the compiler so it shouldn't
2728 // appear in error messages or header files.
2729 // For now, this treats the case where the compiler
2730 // generates CommaExp for temporaries by calling
2731 // the `sideeffect.copyToTemp` function.
2732 auto ve = e.e2.isVarExp();
2733
2734 // Not a CommaExp introduced for temporaries, or -vcg-ast,
2735 // print the full comma
2736 if (!ve || !(ve.var.storage_class & STC.temp) || hgs.vcg_ast)
2737 {
2738 visitBin(cast(BinExp)e);
2739 return;
2740 }
2741
2742 // CommaExp that contain temporaries inserted via
2743 // `copyToTemp` are usually of the form
2744 // ((T __temp = exp), __tmp).
2745 // Asserts are here to easily spot
2746 // missing cases where CommaExp
2747 // are used for other constructs
2748 auto vd = ve.var.isVarDeclaration();
2749 assert(vd && vd._init);
2750
2751 if (auto ei = vd._init.isExpInitializer())
2752 {
2753 Expression commaExtract;
2754 auto exp = ei.exp;
2755 if (auto ce = exp.isConstructExp())
2756 commaExtract = ce.e2;
2757 else if (auto se = exp.isStructLiteralExp())
2758 commaExtract = se;
2759
2760 if (commaExtract)
2761 {
2762 expToBuffer(commaExtract, precedence[exp.op], buf, hgs);
2763 return;
2764 }
2765 }
2766
2767 // not one of the known cases, go on the old path
2768 visitBin(cast(BinExp)e);
2769 return;
2770 }
2771
2772 void visitMixin(MixinExp e)
2773 {
2774 buf.writestring("mixin(");
2775 argsToBuffer(e.exps, buf, hgs, null);
2776 buf.writeByte(')');
2777 }
2778
2779 void visitImport(ImportExp e)
2780 {
2781 buf.writestring("import(");
2782 expToBuffer(e.e1, PREC.assign, buf, hgs);
2783 buf.writeByte(')');
2784 }
2785
2786 void visitAssert(AssertExp e)
2787 {
2788 buf.writestring("assert(");
2789 expToBuffer(e.e1, PREC.assign, buf, hgs);
2790 if (e.msg)
2791 {
2792 buf.writestring(", ");
2793 expToBuffer(e.msg, PREC.assign, buf, hgs);
2794 }
2795 buf.writeByte(')');
2796 }
2797
2798 void visitThrow(ThrowExp e)
2799 {
2800 buf.writestring("throw ");
2801 expToBuffer(e.e1, PREC.unary, buf, hgs);
2802 }
2803
2804 void visitDotId(DotIdExp e)
2805 {
2806 expToBuffer(e.e1, PREC.primary, buf, hgs);
2807 buf.writeByte('.');
2808 buf.writestring(e.ident.toString());
2809 }
2810
2811 void visitDotTemplate(DotTemplateExp e)
2812 {
2813 expToBuffer(e.e1, PREC.primary, buf, hgs);
2814 buf.writeByte('.');
2815 buf.writestring(e.td.toChars());
2816 }
2817
2818 void visitDotVar(DotVarExp e)
2819 {
2820 expToBuffer(e.e1, PREC.primary, buf, hgs);
2821 buf.writeByte('.');
2822 visitDsymbol(e.var);
2823 }
2824
2825 void visitDotTemplateInstance(DotTemplateInstanceExp e)
2826 {
2827 expToBuffer(e.e1, PREC.primary, buf, hgs);
2828 buf.writeByte('.');
2829 e.ti.dsymbolToBuffer(buf, hgs);
2830 }
2831
2832 void visitDelegate(DelegateExp e)
2833 {
2834 buf.writeByte('&');
2835 if (!e.func.isNested() || e.func.needThis())
2836 {
2837 expToBuffer(e.e1, PREC.primary, buf, hgs);
2838 buf.writeByte('.');
2839 }
2840 buf.writestring(e.func.toChars());
2841 }
2842
2843 void visitDotType(DotTypeExp e)
2844 {
2845 expToBuffer(e.e1, PREC.primary, buf, hgs);
2846 buf.writeByte('.');
2847 buf.writestring(e.sym.toChars());
2848 }
2849
2850 void visitCall(CallExp e)
2851 {
2852 if (e.e1.op == EXP.type)
2853 {
2854 /* Avoid parens around type to prevent forbidden cast syntax:
2855 * (sometype)(arg1)
2856 * This is ok since types in constructor calls
2857 * can never depend on parens anyway
2858 */
2859 e.e1.expressionPrettyPrint(buf, hgs);
2860 }
2861 else
2862 expToBuffer(e.e1, precedence[e.op], buf, hgs);
2863 buf.writeByte('(');
2864 argsToBuffer(e.arguments, buf, hgs, null, e.names);
2865 buf.writeByte(')');
2866 }
2867
2868 void visitPtr(PtrExp e)
2869 {
2870 buf.writeByte('*');
2871 expToBuffer(e.e1, precedence[e.op], buf, hgs);
2872 }
2873
2874 void visitDelete(DeleteExp e)
2875 {
2876 buf.writestring("delete ");
2877 expToBuffer(e.e1, precedence[e.op], buf, hgs);
2878 }
2879
2880 void visitCast(CastExp e)
2881 {
2882 buf.writestring("cast(");
2883 if (e.to)
2884 typeToBuffer(e.to, null, buf, hgs);
2885 else
2886 {
2887 MODtoBuffer(buf, e.mod);
2888 }
2889 buf.writeByte(')');
2890 expToBuffer(e.e1, precedence[e.op], buf, hgs);
2891 }
2892
2893 void visitVector(VectorExp e)
2894 {
2895 buf.writestring("cast(");
2896 typeToBuffer(e.to, null, buf, hgs);
2897 buf.writeByte(')');
2898 expToBuffer(e.e1, precedence[e.op], buf, hgs);
2899 }
2900
2901 void visitVectorArray(VectorArrayExp e)
2902 {
2903 expToBuffer(e.e1, PREC.primary, buf, hgs);
2904 buf.writestring(".array");
2905 }
2906
2907 void visitSlice(SliceExp e)
2908 {
2909 expToBuffer(e.e1, precedence[e.op], buf, hgs);
2910 buf.writeByte('[');
2911 if (e.upr || e.lwr)
2912 {
2913 if (e.lwr)
2914 sizeToBuffer(e.lwr, buf, hgs);
2915 else
2916 buf.writeByte('0');
2917 buf.writestring("..");
2918 if (e.upr)
2919 sizeToBuffer(e.upr, buf, hgs);
2920 else
2921 buf.writeByte('$');
2922 }
2923 buf.writeByte(']');
2924 }
2925
2926 void visitArrayLength(ArrayLengthExp e)
2927 {
2928 expToBuffer(e.e1, PREC.primary, buf, hgs);
2929 buf.writestring(".length");
2930 }
2931
2932 void visitInterval(IntervalExp e)
2933 {
2934 expToBuffer(e.lwr, PREC.assign, buf, hgs);
2935 buf.writestring("..");
2936 expToBuffer(e.upr, PREC.assign, buf, hgs);
2937 }
2938
2939 void visitDelegatePtr(DelegatePtrExp e)
2940 {
2941 expToBuffer(e.e1, PREC.primary, buf, hgs);
2942 buf.writestring(".ptr");
2943 }
2944
2945 void visitDelegateFuncptr(DelegateFuncptrExp e)
2946 {
2947 expToBuffer(e.e1, PREC.primary, buf, hgs);
2948 buf.writestring(".funcptr");
2949 }
2950
2951 void visitArray(ArrayExp e)
2952 {
2953 expToBuffer(e.e1, PREC.primary, buf, hgs);
2954 buf.writeByte('[');
2955 argsToBuffer(e.arguments, buf, hgs);
2956 buf.writeByte(']');
2957 }
2958
2959 void visitDot(DotExp e)
2960 {
2961 expToBuffer(e.e1, PREC.primary, buf, hgs);
2962 buf.writeByte('.');
2963 expToBuffer(e.e2, PREC.primary, buf, hgs);
2964 }
2965
2966 void visitIndex(IndexExp e)
2967 {
2968 expToBuffer(e.e1, PREC.primary, buf, hgs);
2969 buf.writeByte('[');
2970 sizeToBuffer(e.e2, buf, hgs);
2971 buf.writeByte(']');
2972 }
2973
2974 void visitPost(PostExp e)
2975 {
2976 expToBuffer(e.e1, precedence[e.op], buf, hgs);
2977 buf.writestring(EXPtoString(e.op));
2978 }
2979
2980 void visitPre(PreExp e)
2981 {
2982 buf.writestring(EXPtoString(e.op));
2983 expToBuffer(e.e1, precedence[e.op], buf, hgs);
2984 }
2985
2986 void visitRemove(RemoveExp e)
2987 {
2988 expToBuffer(e.e1, PREC.primary, buf, hgs);
2989 buf.writestring(".remove(");
2990 expToBuffer(e.e2, PREC.assign, buf, hgs);
2991 buf.writeByte(')');
2992 }
2993
2994 void visitCond(CondExp e)
2995 {
2996 expToBuffer(e.econd, PREC.oror, buf, hgs);
2997 buf.writestring(" ? ");
2998 expToBuffer(e.e1, PREC.expr, buf, hgs);
2999 buf.writestring(" : ");
3000 expToBuffer(e.e2, PREC.cond, buf, hgs);
3001 }
3002
3003 void visitDefaultInit(DefaultInitExp e)
3004 {
3005 buf.writestring(EXPtoString(e.op));
3006 }
3007
3008 void visitClassReference(ClassReferenceExp e)
3009 {
3010 buf.writestring(e.value.toChars());
3011 }
3012
3013 if (e.rvalue)
3014 buf.writestring("__rvalue(");
3015
3016 scope (exit)
3017 if (e.rvalue)
3018 buf.writeByte(')');
3019
3020 switch (e.op)
3021 {
3022 default:
3023 if (auto be = e.isBinExp())
3024 return visitBin(be);
3025 if (auto ue = e.isUnaExp())
3026 return visitUna(ue);
3027 if (auto de = e.isDefaultInitExp())
3028 return visitDefaultInit(e.isDefaultInitExp());
3029 return visit(e);
3030
3031 case EXP.int64: return visitInteger(e.isIntegerExp());
3032 case EXP.error: return visitError(e.isErrorExp());
3033 case EXP.void_: return visitVoidInit(e.isVoidInitExp());
3034 case EXP.float64: return visitReal(e.isRealExp());
3035 case EXP.complex80: return visitComplex(e.isComplexExp());
3036 case EXP.identifier: return visitIdentifier(e.isIdentifierExp());
3037 case EXP.dSymbol: return visitDsymbolExp(e.isDsymbolExp());
3038 case EXP.this_: return visitThis(e.isThisExp());
3039 case EXP.super_: return visitSuper(e.isSuperExp());
3040 case EXP.null_: return visitNull(e.isNullExp());
3041 case EXP.string_: return visitString(e.isStringExp());
3042 case EXP.interpolated: return visitInterpolation(e.isInterpExp());
3043 case EXP.arrayLiteral: return visitArrayLiteral(e.isArrayLiteralExp());
3044 case EXP.assocArrayLiteral: return visitAssocArrayLiteral(e.isAssocArrayLiteralExp());
3045 case EXP.structLiteral: return visitStructLiteral(e.isStructLiteralExp());
3046 case EXP.compoundLiteral: return visitCompoundLiteral(e.isCompoundLiteralExp());
3047 case EXP.type: return visitType(e.isTypeExp());
3048 case EXP.scope_: return visitScope(e.isScopeExp());
3049 case EXP.template_: return visitTemplate(e.isTemplateExp());
3050 case EXP.new_: return visitNew(e.isNewExp());
3051 case EXP.newAnonymousClass: return visitNewAnonClass(e.isNewAnonClassExp());
3052 case EXP.symbolOffset: return visitSymOff(e.isSymOffExp());
3053 case EXP.variable: return visitVar(e.isVarExp());
3054 case EXP.overloadSet: return visitOver(e.isOverExp());
3055 case EXP.tuple: return visitTuple(e.isTupleExp());
3056 case EXP.function_: return visitFunc(e.isFuncExp());
3057 case EXP.declaration: return visitDeclaration(e.isDeclarationExp());
3058 case EXP.typeid_: return visitTypeid(e.isTypeidExp());
3059 case EXP.traits: return visitTraits(e.isTraitsExp());
3060 case EXP.halt: return visitHalt(e.isHaltExp());
3061 case EXP.is_: return visitIs(e.isIsExp());
3062 case EXP.comma: return visitComma(e.isCommaExp());
3063 case EXP.mixin_: return visitMixin(e.isMixinExp());
3064 case EXP.import_: return visitImport(e.isImportExp());
3065 case EXP.assert_: return visitAssert(e.isAssertExp());
3066 case EXP.throw_: return visitThrow(e.isThrowExp());
3067 case EXP.dotIdentifier: return visitDotId(e.isDotIdExp());
3068 case EXP.dotTemplateDeclaration: return visitDotTemplate(e.isDotTemplateExp());
3069 case EXP.dotVariable: return visitDotVar(e.isDotVarExp());
3070 case EXP.dotTemplateInstance: return visitDotTemplateInstance(e.isDotTemplateInstanceExp());
3071 case EXP.delegate_: return visitDelegate(e.isDelegateExp());
3072 case EXP.dotType: return visitDotType(e.isDotTypeExp());
3073 case EXP.call: return visitCall(e.isCallExp());
3074 case EXP.star: return visitPtr(e.isPtrExp());
3075 case EXP.delete_: return visitDelete(e.isDeleteExp());
3076 case EXP.cast_: return visitCast(e.isCastExp());
3077 case EXP.vector: return visitVector(e.isVectorExp());
3078 case EXP.vectorArray: return visitVectorArray(e.isVectorArrayExp());
3079 case EXP.slice: return visitSlice(e.isSliceExp());
3080 case EXP.arrayLength: return visitArrayLength(e.isArrayLengthExp());
3081 case EXP.interval: return visitInterval(e.isIntervalExp());
3082 case EXP.delegatePointer: return visitDelegatePtr(e.isDelegatePtrExp());
3083 case EXP.delegateFunctionPointer: return visitDelegateFuncptr(e.isDelegateFuncptrExp());
3084 case EXP.array: return visitArray(e.isArrayExp());
3085 case EXP.dot: return visitDot(e.isDotExp());
3086 case EXP.index: return visitIndex(e.isIndexExp());
3087 case EXP.minusMinus:
3088 case EXP.plusPlus: return visitPost(e.isPostExp());
3089 case EXP.preMinusMinus:
3090 case EXP.prePlusPlus: return visitPre(e.isPreExp());
3091 case EXP.remove: return visitRemove(e.isRemoveExp());
3092 case EXP.question: return visitCond(e.isCondExp());
3093 case EXP.classReference: return visitClassReference(e.isClassReferenceExp());
3094 case EXP.loweredAssignExp: return visitLoweredAssignExp(e.isLoweredAssignExp());
3095 }
3096 }
3097
3098 /**
3099 * Formats `value` as a literal of type `type` into `buf`.
3100 *
3101 * Params:
3102 * type = literal type (e.g. Tfloat)
3103 * value = value to print
3104 * buf = target buffer
3105 * allowHex = whether hex floating point literals may be used
3106 * for greater accuracy
3107 */
3108 void floatToBuffer(Type type, const real_t value, ref OutBuffer buf, const bool allowHex)
3109 {
3110 /** sizeof(value)*3 is because each byte of mantissa is max
3111 of 256 (3 characters). The string will be "-M.MMMMe-4932".
3112 (ie, 8 chars more than mantissa). Plus one for trailing \0.
3113 Plus one for rounding. */
3114 const(size_t) BUFFER_LEN = value.sizeof * 3 + 8 + 1 + 1;
3115 char[BUFFER_LEN] buffer = void;
3116 CTFloat.sprint(buffer.ptr, BUFFER_LEN, 'g', value);
3117 assert(strlen(buffer.ptr) < BUFFER_LEN);
3118 if (allowHex)
3119 {
3120 bool isOutOfRange;
3121 real_t r = CTFloat.parse(buffer.ptr, isOutOfRange);
3122 //assert(!isOutOfRange); // test/compilable/test22725.c asserts here
3123 if (r != value) // if exact duplication
3124 CTFloat.sprint(buffer.ptr, BUFFER_LEN, 'a', value);
3125 }
3126 buf.writestring(buffer.ptr);
3127 if (buffer.ptr[strlen(buffer.ptr) - 1] == '.')
3128 buf.remove(buf.length() - 1, 1);
3129
3130 if (type)
3131 {
3132 Type t = type.toBasetype();
3133 switch (t.ty)
3134 {
3135 case Tfloat32:
3136 case Timaginary32:
3137 case Tcomplex32:
3138 buf.writeByte('F');
3139 break;
3140 case Tfloat80:
3141 case Timaginary80:
3142 case Tcomplex80:
3143 buf.writeByte('L');
3144 break;
3145 default:
3146 break;
3147 }
3148 if (t.isImaginary())
3149 buf.writeByte('i');
3150 }
3151 }
3152
3153 void toCBuffer(const TemplateParameter tp, ref OutBuffer buf, ref HdrGenState hgs)
3154 {
3155 scope v = new TemplateParameterPrettyPrintVisitor(&buf, &hgs);
3156 (cast() tp).accept(v);
3157 }
3158
3159 private extern (C++) final class TemplateParameterPrettyPrintVisitor : Visitor
3160 {
3161 alias visit = Visitor.visit;
3162 public:
3163 OutBuffer* buf;
3164 HdrGenState* hgs;
3165
3166 extern (D) this(OutBuffer* buf, HdrGenState* hgs) scope @safe
3167 {
3168 this.buf = buf;
3169 this.hgs = hgs;
3170 }
3171
3172 override void visit(TemplateTypeParameter tp)
3173 {
3174 buf.writestring(tp.ident.toString());
3175 if (tp.specType)
3176 {
3177 buf.writestring(" : ");
3178 typeToBuffer(tp.specType, null, *buf, *hgs);
3179 }
3180 if (tp.defaultType)
3181 {
3182 buf.writestring(" = ");
3183 typeToBuffer(tp.defaultType, null, *buf, *hgs);
3184 }
3185 }
3186
3187 override void visit(TemplateThisParameter tp)
3188 {
3189 buf.writestring("this ");
3190 visit(cast(TemplateTypeParameter)tp);
3191 }
3192
3193 override void visit(TemplateAliasParameter tp)
3194 {
3195 buf.writestring("alias ");
3196 if (tp.specType)
3197 typeToBuffer(tp.specType, tp.ident, *buf, *hgs);
3198 else
3199 buf.writestring(tp.ident.toString());
3200 if (tp.specAlias)
3201 {
3202 buf.writestring(" : ");
3203 objectToBuffer(tp.specAlias, *buf, *hgs);
3204 }
3205 if (tp.defaultAlias)
3206 {
3207 buf.writestring(" = ");
3208 objectToBuffer(tp.defaultAlias, *buf, *hgs);
3209 }
3210 }
3211
3212 override void visit(TemplateValueParameter tp)
3213 {
3214 typeToBuffer(tp.valType, tp.ident, *buf, *hgs);
3215 if (tp.specValue)
3216 {
3217 buf.writestring(" : ");
3218 tp.specValue.expressionToBuffer(*buf, *hgs);
3219 }
3220 if (tp.defaultValue)
3221 {
3222 buf.writestring(" = ");
3223 tp.defaultValue.expressionToBuffer(*buf, *hgs);
3224 }
3225 }
3226
3227 override void visit(TemplateTupleParameter tp)
3228 {
3229 buf.writestring(tp.ident.toString());
3230 buf.writestring("...");
3231 }
3232 }
3233
3234 private void conditionToBuffer(Condition c, ref OutBuffer buf, ref HdrGenState hgs)
3235 {
3236 scope v = new ConditionPrettyPrintVisitor(&buf, &hgs);
3237 c.accept(v);
3238 }
3239
3240 private extern (C++) final class ConditionPrettyPrintVisitor : Visitor
3241 {
3242 alias visit = Visitor.visit;
3243 public:
3244 OutBuffer* buf;
3245 HdrGenState* hgs;
3246
3247 extern (D) this(OutBuffer* buf, HdrGenState* hgs) scope @safe
3248 {
3249 this.buf = buf;
3250 this.hgs = hgs;
3251 }
3252
3253 override void visit(DebugCondition c)
3254 {
3255 buf.writestring("debug (");
3256 buf.writestring(c.ident.toString());
3257 buf.writeByte(')');
3258 }
3259
3260 override void visit(VersionCondition c)
3261 {
3262 buf.writestring("version (");
3263 buf.writestring(c.ident.toString());
3264 buf.writeByte(')');
3265 }
3266
3267 override void visit(StaticIfCondition c)
3268 {
3269 buf.writestring("static if (");
3270 c.exp.expressionToBuffer(*buf, *hgs);
3271 buf.writeByte(')');
3272 }
3273 }
3274
3275 void toCBuffer(const Statement s, ref OutBuffer buf, ref HdrGenState hgs)
3276 {
3277 (cast()s).statementToBuffer(buf, hgs);
3278 }
3279
3280 void toCBuffer(const Type t, ref OutBuffer buf, const Identifier ident, ref HdrGenState hgs)
3281 {
3282 typeToBuffer(cast() t, ident, buf, hgs);
3283 }
3284
3285 // used from TemplateInstance::toChars() and TemplateMixin::toChars()
3286 void toCBufferInstance(const TemplateInstance ti, ref OutBuffer buf, bool qualifyTypes = false)
3287 {
3288 HdrGenState hgs;
3289 hgs.fullQual = qualifyTypes;
3290
3291 buf.writestring(ti.name.toChars());
3292 tiargsToBuffer(cast() ti, buf, hgs);
3293 }
3294
3295 void toCBuffer(const Initializer iz, ref OutBuffer buf, ref HdrGenState hgs)
3296 {
3297 initializerToBuffer(cast() iz, buf, hgs);
3298 }
3299
3300 bool stcToBuffer(ref OutBuffer buf, STC stc) @safe
3301 {
3302 //printf("stc: %llx\n", stc);
3303 bool result = false;
3304
3305 if (stc & STC.scopeinferred)
3306 {
3307 //buf.writestring("scope-inferred ");
3308 stc &= ~(STC.scope_ | STC.scopeinferred);
3309 }
3310 if (stc & STC.returninferred)
3311 {
3312 //buf.writestring((stc & STC.returnScope) ? "return-scope-inferred " : "return-ref-inferred ");
3313 stc &= ~(STC.return_ | STC.returninferred);
3314 }
3315
3316 // ensure `auto ref` keywords are (almost) adjacent
3317 if (stc & STC.auto_)
3318 {
3319 buf.writestring("auto ");
3320 stc &= ~STC.auto_;
3321 }
3322 /* Put scope ref return into a standard order
3323 */
3324 string rrs;
3325 const isout = (stc & STC.out_) != 0;
3326 //printf("bsr = %d %llx\n", buildScopeRef(stc), stc);
3327 final switch (buildScopeRef(stc))
3328 {
3329 case ScopeRef.None:
3330 case ScopeRef.Scope:
3331 case ScopeRef.Return:
3332 break;
3333
3334 case ScopeRef.ReturnScope: rrs = "return scope"; goto L1;
3335 case ScopeRef.ReturnRef: rrs = isout ? "return out" : "return ref"; goto L1;
3336 case ScopeRef.Ref: rrs = isout ? "out" : "ref"; goto L1;
3337 case ScopeRef.RefScope: rrs = isout ? "out scope" : "ref scope"; goto L1;
3338 case ScopeRef.ReturnRef_Scope: rrs = isout ? "return out scope" : "return ref scope"; goto L1;
3339 case ScopeRef.Ref_ReturnScope: rrs = isout ? "out return scope" : "ref return scope"; goto L1;
3340 L1:
3341 buf.writestring(rrs);
3342 result = true;
3343 stc &= ~(STC.out_ | STC.scope_ | STC.ref_ | STC.return_);
3344 break;
3345 }
3346
3347 while (stc)
3348 {
3349 const s = stcToString(stc);
3350 if (!s.length)
3351 break;
3352 if (result)
3353 buf.writeByte(' ');
3354 result = true;
3355 buf.writestring(s);
3356 }
3357
3358 return result;
3359 }
3360
3361 /*************************************************
3362 * Pick off one of the storage classes from stc,
3363 * and return a string representation of it.
3364 * stc is reduced by the one picked.
3365 */
3366 string stcToString(ref STC stc) @safe
3367 {
3368 static struct SCstring
3369 {
3370 STC stc;
3371 string id;
3372 }
3373
3374 // Note: The identifier needs to be `\0` terminated
3375 // as some code assumes it (e.g. when printing error messages)
3376 static immutable SCstring[] table =
3377 [
3378 SCstring(STC.auto_, Token.toString(TOK.auto_)),
3379 SCstring(STC.scope_, Token.toString(TOK.scope_)),
3380 SCstring(STC.static_, Token.toString(TOK.static_)),
3381 SCstring(STC.extern_, Token.toString(TOK.extern_)),
3382 SCstring(STC.const_, Token.toString(TOK.const_)),
3383 SCstring(STC.final_, Token.toString(TOK.final_)),
3384 SCstring(STC.abstract_, Token.toString(TOK.abstract_)),
3385 SCstring(STC.synchronized_, Token.toString(TOK.synchronized_)),
3386 SCstring(STC.deprecated_, Token.toString(TOK.deprecated_)),
3387 SCstring(STC.override_, Token.toString(TOK.override_)),
3388 SCstring(STC.lazy_, Token.toString(TOK.lazy_)),
3389 SCstring(STC.alias_, Token.toString(TOK.alias_)),
3390 SCstring(STC.out_, Token.toString(TOK.out_)),
3391 SCstring(STC.in_, Token.toString(TOK.in_)),
3392 SCstring(STC.manifest, Token.toString(TOK.enum_)),
3393 SCstring(STC.immutable_, Token.toString(TOK.immutable_)),
3394 SCstring(STC.shared_, Token.toString(TOK.shared_)),
3395 SCstring(STC.nothrow_, Token.toString(TOK.nothrow_)),
3396 SCstring(STC.wild, Token.toString(TOK.inout_)),
3397 SCstring(STC.pure_, Token.toString(TOK.pure_)),
3398 SCstring(STC.ref_, Token.toString(TOK.ref_)),
3399 SCstring(STC.return_, Token.toString(TOK.return_)),
3400 SCstring(STC.gshared, Token.toString(TOK.gshared)),
3401 SCstring(STC.nogc, "@nogc"),
3402 SCstring(STC.live, "@live"),
3403 SCstring(STC.property, "@property"),
3404 SCstring(STC.safe, "@safe"),
3405 SCstring(STC.trusted, "@trusted"),
3406 SCstring(STC.system, "@system"),
3407 SCstring(STC.disable, "@disable"),
3408 SCstring(STC.future, "@__future"),
3409 SCstring(STC.local, "__local"),
3410 ];
3411 foreach (ref entry; table)
3412 {
3413 const STC tbl = entry.stc;
3414 assert(tbl & STC.visibleStorageClasses);
3415 if (stc & tbl)
3416 {
3417 stc &= ~tbl;
3418 return entry.id;
3419 }
3420 }
3421 //printf("stc = %llx\n", stc);
3422 return null;
3423 }
3424
3425 private void linkageToBuffer(ref OutBuffer buf, LINK linkage) @safe
3426 {
3427 const s = linkageToString(linkage);
3428 if (s.length)
3429 {
3430 buf.writestring("extern (");
3431 buf.writestring(s);
3432 buf.writeByte(')');
3433 }
3434 }
3435
3436 const(char)* linkageToChars(LINK linkage)
3437 {
3438 /// Works because we return a literal
3439 return linkageToString(linkage).ptr;
3440 }
3441
3442 string linkageToString(LINK linkage) pure nothrow @safe
3443 {
3444 with (LINK)
3445 {
3446 immutable string[7] a = [
3447 default_ : null,
3448 d : "D",
3449 c : "C",
3450 cpp : "C++",
3451 windows : "Windows",
3452 objc : "Objective-C",
3453 system : "System" ];
3454 return a[linkage];
3455 }
3456 }
3457
3458 void visibilityToBuffer(ref OutBuffer buf, Visibility vis)
3459 {
3460 buf.writestring(visibilityToString(vis.kind));
3461 if (vis.kind == Visibility.Kind.package_ && vis.pkg)
3462 {
3463 buf.writeByte('(');
3464 buf.writestring(vis.pkg.toPrettyChars(true));
3465 buf.writeByte(')');
3466 }
3467 }
3468
3469 /**
3470 * Returns:
3471 * a human readable representation of `kind`
3472 */
3473 const(char)* visibilityToChars(Visibility.Kind kind)
3474 {
3475 // Null terminated because we return a literal
3476 return visibilityToString(kind).ptr;
3477 }
3478
3479 /// Ditto
3480 extern (D) string visibilityToString(Visibility.Kind kind) nothrow pure @safe
3481 {
3482 with (Visibility.Kind)
3483 {
3484 immutable string[7] a = [
3485 none : "none",
3486 private_ : "private",
3487 package_ : "package",
3488 protected_ : "protected",
3489 public_ : "public",
3490 export_ : "export" ];
3491 return a[kind];
3492 }
3493 }
3494
3495 // Print the full function signature with correct ident, attributes and template args
3496 void functionToBufferFull(TypeFunction tf, ref OutBuffer buf, const Identifier ident, ref HdrGenState hgs, TemplateDeclaration td)
3497 {
3498 //printf("TypeFunction::toCBuffer() this = %p\n", this);
3499 visitFuncIdentWithPrefix(tf, ident, td, buf, hgs);
3500 }
3501
3502 // ident is inserted before the argument list and will be "function" or "delegate" for a type
3503 void functionToBufferWithIdent(TypeFunction tf, ref OutBuffer buf, const(char)* ident, bool isStatic)
3504 {
3505 HdrGenState hgs;
3506 visitFuncIdentWithPostfix(tf, ident.toDString(), buf, hgs, isStatic);
3507 }
3508
3509 void toCBuffer(const Expression e, ref OutBuffer buf, ref HdrGenState hgs)
3510 {
3511 expressionPrettyPrint(cast()e, buf, hgs);
3512 }
3513
3514 /**************************************************
3515 * Write out argument types to buf.
3516 */
3517 void argExpTypesToCBuffer(ref OutBuffer buf, Expressions* arguments)
3518 {
3519 if (!arguments || !arguments.length)
3520 return;
3521 HdrGenState hgs;
3522 foreach (i, arg; *arguments)
3523 {
3524 if (i)
3525 buf.writestring(", ");
3526 typeToBuffer(arg.type, null, buf, hgs);
3527 }
3528 }
3529
3530 void arrayObjectsToBuffer(ref OutBuffer buf, Objects* objects)
3531 {
3532 if (!objects || !objects.length)
3533 return;
3534 HdrGenState hgs;
3535 foreach (i, o; *objects)
3536 {
3537 if (i)
3538 buf.writestring(", ");
3539 objectToBuffer(o, buf, hgs);
3540 }
3541 }
3542
3543 /*************************************************************
3544 * Pretty print function parameters.
3545 * Params:
3546 * pl = parameter list to print
3547 * Returns: Null-terminated string representing parameters.
3548 */
3549 const(char)* parametersTypeToChars(ParameterList pl)
3550 {
3551 OutBuffer buf;
3552 HdrGenState hgs;
3553 parametersToBuffer(pl, buf, hgs);
3554 return buf.extractChars();
3555 }
3556
3557 /*************************************************************
3558 * Pretty print function parameter.
3559 * Params:
3560 * parameter = parameter to print.
3561 * tf = TypeFunction which holds parameter.
3562 * fullQual = whether to fully qualify types.
3563 * Returns: Null-terminated string representing parameters.
3564 */
3565 const(char)* parameterToChars(Parameter parameter, TypeFunction tf, bool fullQual)
3566 {
3567 OutBuffer buf;
3568 HdrGenState hgs;
3569 hgs.fullQual = fullQual;
3570
3571 parameterToBuffer(parameter, buf, hgs);
3572
3573 if (tf.parameterList.varargs == VarArg.typesafe && parameter == tf.parameterList[tf.parameterList.parameters.length - 1])
3574 {
3575 buf.writestring("...");
3576 }
3577 return buf.extractChars();
3578 }
3579
3580
3581 /*************************************************
3582 * Write ParameterList to buffer.
3583 * Params:
3584 * pl = parameter list to serialize
3585 * buf = buffer to write it to
3586 * hgs = context
3587 */
3588
3589 private void parametersToBuffer(ParameterList pl, ref OutBuffer buf, ref HdrGenState hgs)
3590 {
3591 buf.writeByte('(');
3592 foreach (i; 0 .. pl.length)
3593 {
3594 if (i)
3595 buf.writestring(", ");
3596 pl[i].parameterToBuffer(buf, hgs);
3597 }
3598 final switch (pl.varargs)
3599 {
3600 case VarArg.none:
3601 case VarArg.KRvariadic:
3602 break;
3603
3604 case VarArg.variadic:
3605 if (pl.length)
3606 buf.writestring(", ");
3607
3608 if (stcToBuffer(buf, pl.stc))
3609 buf.writeByte(' ');
3610 goto case VarArg.typesafe;
3611
3612 case VarArg.typesafe:
3613 buf.writestring("...");
3614 break;
3615 }
3616 buf.writeByte(')');
3617 }
3618
3619
3620 /***********************************************************
3621 * Write parameter `p` to buffer `buf`.
3622 * Params:
3623 * p = parameter to serialize
3624 * buf = buffer to write it to
3625 * hgs = context
3626 */
3627 private void parameterToBuffer(Parameter p, ref OutBuffer buf, ref HdrGenState hgs)
3628 {
3629 if (p.userAttribDecl)
3630 {
3631 buf.writeByte('@');
3632
3633 bool isAnonymous = p.userAttribDecl.atts.length > 0 && !(*p.userAttribDecl.atts)[0].isCallExp();
3634 if (isAnonymous)
3635 buf.writeByte('(');
3636
3637 argsToBuffer(p.userAttribDecl.atts, buf, hgs);
3638
3639 if (isAnonymous)
3640 buf.writeByte(')');
3641 buf.writeByte(' ');
3642 }
3643 if (p.storageClass & STC.auto_)
3644 buf.writestring("auto ");
3645
3646 STC stc = p.storageClass;
3647 if (p.storageClass & STC.in_)
3648 {
3649 buf.writestring("in ");
3650 if ((p.storageClass & (STC.constscoperef | STC.ref_)) == (STC.constscoperef | STC.ref_))
3651 stc &= ~STC.ref_;
3652 }
3653 else if (p.storageClass & STC.lazy_)
3654 buf.writestring("lazy ");
3655 else if (p.storageClass & STC.alias_)
3656 buf.writestring("alias ");
3657
3658 if (p.type && p.type.mod & MODFlags.shared_)
3659 stc &= ~STC.shared_;
3660
3661 if (stcToBuffer(buf, stc & (STC.const_ | STC.immutable_ | STC.wild | STC.shared_ |
3662 STC.return_ | STC.returninferred | STC.scope_ | STC.scopeinferred | STC.out_ | STC.ref_ | STC.returnScope)))
3663 buf.writeByte(' ');
3664
3665 const(char)[] s;
3666 if (p.storageClass & STC.alias_)
3667 {
3668 if (p.ident)
3669 buf.writestring(p.ident.toString());
3670 }
3671 else if (p.type.isTypeIdentifier() &&
3672 (s = p.type.isTypeIdentifier().ident.toString()).length > 3 &&
3673 s[0..3] == "__T")
3674 {
3675 // print parameter name, instead of undetermined type parameter
3676 buf.writestring(p.ident.toString());
3677 }
3678 else
3679 {
3680 typeToBuffer(p.type, p.ident, buf, hgs, (stc & STC.in_) ? MODFlags.const_ : 0);
3681 }
3682
3683 if (p.defaultArg)
3684 {
3685 buf.writestring(" = ");
3686 p.defaultArg.expToBuffer(PREC.assign, buf, hgs);
3687 }
3688 }
3689
3690
3691 /**************************************************
3692 * Write out argument list to buf.
3693 * Params:
3694 * expressions = argument list
3695 * buf = buffer to write to
3696 * hgs = context
3697 * basis = replace `null`s in argument list with this expression (for sparse array literals)
3698 * names = if non-null, use these as the names for the arguments
3699 */
3700 private void argsToBuffer(Expressions* expressions, ref OutBuffer buf, ref HdrGenState hgs, Expression basis = null, Identifiers* names = null)
3701 {
3702 if (!expressions || !expressions.length)
3703 return;
3704 version (all)
3705 {
3706 foreach (i, el; *expressions)
3707 {
3708 if (i)
3709 buf.writestring(", ");
3710
3711 if (names && i < names.length && (*names)[i])
3712 {
3713 buf.writestring((*names)[i].toString());
3714 buf.writestring(": ");
3715 }
3716 if (!el)
3717 el = basis;
3718 if (el)
3719 expToBuffer(el, PREC.assign, buf, hgs);
3720 }
3721 }
3722 else
3723 {
3724 // Sparse style formatting, for debug use only
3725 // [0..length: basis, 1: e1, 5: e5]
3726 if (basis)
3727 {
3728 buf.writestring("0..");
3729 buf.print(expressions.length);
3730 buf.writestring(": ");
3731 expToBuffer(basis, PREC.assign, buf, hgs);
3732 }
3733 foreach (i, el; *expressions)
3734 {
3735 if (el)
3736 {
3737 if (basis)
3738 {
3739 buf.writestring(", ");
3740 buf.print(i);
3741 buf.writestring(": ");
3742 }
3743 else if (i)
3744 buf.writestring(", ");
3745 expToBuffer(el, PREC.assign, buf, hgs);
3746 }
3747 }
3748 }
3749 }
3750
3751 private void sizeToBuffer(Expression e, ref OutBuffer buf, ref HdrGenState hgs)
3752 {
3753 if (e.type == Type.tsize_t)
3754 {
3755 Expression ex = (e.op == EXP.cast_ ? (cast(CastExp)e).e1 : e);
3756 ex = ex.optimize(WANTvalue);
3757 const ulong uval = ex.op == EXP.int64 ? ex.toInteger() : cast(ulong)-1;
3758 if (cast(long)uval >= 0)
3759 {
3760 if (uval <= 0xFFFFU)
3761 {
3762 buf.print(uval);
3763 return;
3764 }
3765 if (uval <= 0x7FFF_FFFF_FFFF_FFFFUL)
3766 {
3767 buf.writestring("cast(size_t)");
3768 buf.print(uval);
3769 return;
3770 }
3771 }
3772 }
3773 expToBuffer(e, PREC.assign, buf, hgs);
3774 }
3775
3776 private void expressionToBuffer(Expression e, ref OutBuffer buf, ref HdrGenState hgs)
3777 {
3778 expressionPrettyPrint(e, buf, hgs);
3779 }
3780
3781 /**************************************************
3782 * Write expression out to buf, but wrap it
3783 * in ( ) if its precedence is less than pr.
3784 */
3785 private void expToBuffer(Expression e, PREC pr, ref OutBuffer buf, ref HdrGenState hgs)
3786 {
3787 debug
3788 {
3789 if (precedence[e.op] == PREC.zero)
3790 printf("precedence not defined for token '%s'\n", EXPtoString(e.op).ptr);
3791 }
3792 if (e.op == 0xFF)
3793 {
3794 buf.writestring("<FF>");
3795 return;
3796 }
3797 assert(precedence[e.op] != PREC.zero);
3798 assert(pr != PREC.zero);
3799 /* Despite precedence, we don't allow a<b<c expressions.
3800 * They must be parenthesized.
3801 */
3802 if (precedence[e.op] < pr || (pr == PREC.rel && precedence[e.op] == pr)
3803 || (pr >= PREC.or && pr <= PREC.and && precedence[e.op] == PREC.rel))
3804 {
3805 buf.writeByte('(');
3806 e.expressionToBuffer(buf, hgs);
3807 buf.writeByte(')');
3808 }
3809 else
3810 {
3811 e.expressionToBuffer(buf, hgs);
3812 }
3813 }
3814
3815
3816 /**************************************************
3817 * An entry point to pretty-print type.
3818 */
3819 private void typeToBuffer(Type t, const Identifier ident, ref OutBuffer buf, ref HdrGenState hgs,
3820 ubyte modMask = 0)
3821 {
3822 if (auto tf = t.isTypeFunction())
3823 {
3824 visitFuncIdentWithPrefix(tf, ident, null, buf, hgs);
3825 return;
3826 }
3827 visitWithMask(t, modMask, buf, hgs);
3828 if (ident)
3829 {
3830 buf.writeByte(' ');
3831 buf.writestring(ident.toString());
3832 }
3833 }
3834
3835 private void visitWithMask(Type t, ubyte modMask, ref OutBuffer buf, ref HdrGenState hgs)
3836 {
3837 // Tuples and functions don't use the type constructor syntax
3838 if (modMask == t.mod || t.ty == Tfunction || t.ty == Ttuple)
3839 {
3840 typeToBufferx(t, buf, hgs);
3841 }
3842 else
3843 {
3844 ubyte m = t.mod & ~(t.mod & modMask);
3845 if (m & MODFlags.shared_)
3846 {
3847 MODtoBuffer(buf, MODFlags.shared_);
3848 buf.writeByte('(');
3849 }
3850 if (m & MODFlags.wild)
3851 {
3852 MODtoBuffer(buf, MODFlags.wild);
3853 buf.writeByte('(');
3854 }
3855 if (m & (MODFlags.const_ | MODFlags.immutable_))
3856 {
3857 MODtoBuffer(buf, m & (MODFlags.const_ | MODFlags.immutable_));
3858 buf.writeByte('(');
3859 }
3860 typeToBufferx(t, buf, hgs);
3861 if (m & (MODFlags.const_ | MODFlags.immutable_))
3862 buf.writeByte(')');
3863 if (m & MODFlags.wild)
3864 buf.writeByte(')');
3865 if (m & MODFlags.shared_)
3866 buf.writeByte(')');
3867 }
3868 }
3869
3870
3871 private void dumpTemplateInstance(TemplateInstance ti, ref OutBuffer buf, ref HdrGenState hgs)
3872 {
3873 buf.writeByte('{');
3874 buf.writenl();
3875 buf.level++;
3876
3877 if (ti.aliasdecl)
3878 {
3879 ti.aliasdecl.dsymbolToBuffer(buf, hgs);
3880 buf.writenl();
3881 }
3882 else if (ti.members)
3883 {
3884 foreach(m;*ti.members)
3885 m.dsymbolToBuffer(buf, hgs);
3886 }
3887
3888 buf.level--;
3889 buf.writeByte('}');
3890 buf.writenl();
3891
3892 }
3893
3894 private void tiargsToBuffer(TemplateInstance ti, ref OutBuffer buf, ref HdrGenState hgs)
3895 {
3896 buf.writeByte('!');
3897 if (ti.nest)
3898 {
3899 buf.writestring("(...)");
3900 return;
3901 }
3902 if (!ti.tiargs)
3903 {
3904 buf.writestring("()");
3905 return;
3906 }
3907 if (ti.tiargs.length == 1)
3908 {
3909 RootObject oarg = (*ti.tiargs)[0];
3910 if (Type t = isType(oarg))
3911 {
3912 if (t.equals(Type.tstring) || t.equals(Type.twstring) || t.equals(Type.tdstring) || t.mod == 0 && (t.isTypeBasic() || t.ty == Tident && (cast(TypeIdentifier)t).idents.length == 0))
3913 {
3914 HdrGenState hgs2; // re-examine need for new hgs
3915 hgs2.fullQual = (t.ty == Tclass && !t.mod);
3916 toCBuffer(t, buf, null, hgs2);
3917 return;
3918 }
3919 }
3920 else if (Expression e = isExpression(oarg))
3921 {
3922 if (!(e.type && e.type.isTypeEnum()) && e.op == EXP.int64 || e.op == EXP.float64 ||
3923 e.op == EXP.null_ || e.op == EXP.string_ || e.op == EXP.this_)
3924 {
3925 toCBuffer(e, buf, hgs);
3926 return;
3927 }
3928 }
3929 }
3930 buf.writeByte('(');
3931 ti.nestUp();
3932 foreach (i, arg; *ti.tiargs)
3933 {
3934 if (i)
3935 buf.writestring(", ");
3936 objectToBuffer(arg, buf, hgs);
3937 }
3938 ti.nestDown();
3939 buf.writeByte(')');
3940 }
3941
3942 /****************************************
3943 * This makes a 'pretty' version of the template arguments.
3944 * It's analogous to genIdent() which makes a mangled version.
3945 */
3946 private void objectToBuffer(RootObject oarg, ref OutBuffer buf, ref HdrGenState hgs)
3947 {
3948 //printf("objectToBuffer()\n");
3949 /* The logic of this should match what genIdent() does. The _dynamic_cast()
3950 * function relies on all the pretty strings to be unique for different classes
3951 * See https://issues.dlang.org/show_bug.cgi?id=7375
3952 * Perhaps it would be better to demangle what genIdent() does.
3953 */
3954 if (auto t = isType(oarg))
3955 {
3956 //printf("\tt: %s ty = %d\n", t.toChars(), t.ty);
3957 typeToBuffer(t, null, buf, hgs);
3958 }
3959 else if (auto e = isExpression(oarg))
3960 {
3961 if (e.op == EXP.variable)
3962 e = e.optimize(WANTvalue); // added to fix https://issues.dlang.org/show_bug.cgi?id=7375
3963 expToBuffer(e, PREC.assign, buf, hgs);
3964 }
3965 else if (Dsymbol s = isDsymbol(oarg))
3966 {
3967 if (s.ident)
3968 buf.writestring(s.ident.toString());
3969 else
3970 buf.writestring(s.toChars());
3971 }
3972 else if (auto v = isTuple(oarg))
3973 {
3974 auto args = &v.objects;
3975 foreach (i, arg; *args)
3976 {
3977 if (i)
3978 buf.writestring(", ");
3979 objectToBuffer(arg, buf, hgs);
3980 }
3981 }
3982 else if (auto p = isParameter(oarg))
3983 {
3984 parameterToBuffer(p, buf, hgs);
3985 }
3986 else if (!oarg)
3987 {
3988 buf.writestring("NULL");
3989 }
3990 else
3991 {
3992 debug
3993 {
3994 printf("bad Object = %p\n", oarg);
3995 }
3996 assert(0);
3997 }
3998 }
3999
4000
4001 private void visitFuncIdentWithPostfix(TypeFunction t, const char[] ident, ref OutBuffer buf, ref HdrGenState hgs, bool isStatic)
4002 {
4003 if (t.inuse)
4004 {
4005 t.inuse = 2; // flag error to caller
4006 return;
4007 }
4008 t.inuse++;
4009 if (t.linkage > LINK.d && hgs.ddoc != 1 && !hgs.hdrgen)
4010 {
4011 linkageToBuffer(buf, t.linkage);
4012 buf.writeByte(' ');
4013 }
4014 if (t.linkage == LINK.objc && isStatic)
4015 buf.write("static ");
4016 if (t.next)
4017 {
4018 typeToBuffer(t.next, null, buf, hgs);
4019 if (ident)
4020 buf.writeByte(' ');
4021 }
4022 else if (hgs.ddoc)
4023 buf.writestring("auto ");
4024 if (ident)
4025 buf.writestring(ident);
4026 parametersToBuffer(t.parameterList, buf, hgs);
4027 /* Use postfix style for attributes
4028 */
4029 if (t.mod)
4030 {
4031 buf.writeByte(' ');
4032 MODtoBuffer(buf, t.mod);
4033 }
4034
4035 void dg(string str)
4036 {
4037 buf.writeByte(' ');
4038 buf.writestring(str);
4039 }
4040 t.attributesApply(&dg);
4041
4042 t.inuse--;
4043 }
4044
4045 private void visitFuncIdentWithPrefix(TypeFunction t, const Identifier ident, TemplateDeclaration td,
4046 ref OutBuffer buf, ref HdrGenState hgs)
4047 {
4048 if (t.inuse)
4049 {
4050 t.inuse = 2; // flag error to caller
4051 return;
4052 }
4053 t.inuse++;
4054
4055 /* Use 'storage class' (prefix) style for attributes
4056 */
4057 if (t.mod && !(hgs.ddoc || hgs.hdrgen))
4058 {
4059 MODtoBuffer(buf, t.mod);
4060 buf.writeByte(' ');
4061 }
4062
4063 void dg(string str)
4064 {
4065 if (str != "return" && str != "scope")
4066 {
4067 // don't write 'ref' for ctors
4068 if ((ident == Id.ctor) && str == "ref")
4069 return;
4070 buf.writestring(str);
4071 buf.writeByte(' ');
4072 }
4073 }
4074 t.attributesApply(&dg);
4075
4076 if (t.linkage > LINK.d && hgs.ddoc != 1 && !hgs.hdrgen)
4077 {
4078 linkageToBuffer(buf, t.linkage);
4079 buf.writeByte(' ');
4080 }
4081 if (ident && ident.toHChars2() != ident.toChars())
4082 {
4083 // Don't print return type for ctor, dtor, unittest, etc
4084 }
4085 else if (t.next)
4086 {
4087 typeToBuffer(t.next, null, buf, hgs);
4088 if (ident)
4089 buf.writeByte(' ');
4090 }
4091 else if (hgs.ddoc)
4092 buf.writestring("auto ");
4093 if (ident)
4094 buf.writestring(ident.toHChars2());
4095 if (td)
4096 {
4097 buf.writeByte('(');
4098 foreach (i, p; *td.origParameters)
4099 {
4100 if (i)
4101 buf.writestring(", ");
4102 toCBuffer(p, buf, hgs);
4103 }
4104 buf.writeByte(')');
4105 }
4106 parametersToBuffer(t.parameterList, buf, hgs);
4107 // postfix this attributes are more readable
4108 if (t.mod && (hgs.ddoc || hgs.hdrgen))
4109 {
4110 buf.writeByte(' ');
4111 MODtoBuffer(buf, t.mod);
4112 }
4113 if (t.isReturnScope && !t.isReturnInferred)
4114 {
4115 buf.writestring(" return scope");
4116 }
4117 else if (t.isScopeQual && !t.isScopeInferred)
4118 {
4119 buf.writestring(" scope");
4120 }
4121 if (t.isReturn && !t.isReturnScope && !t.isReturnInferred)
4122 {
4123 buf.writestring(" return");
4124 }
4125 t.inuse--;
4126 }
4127
4128
4129 private void initializerToBuffer(Initializer inx, ref OutBuffer buf, ref HdrGenState hgs)
4130 {
4131 void visitError(ErrorInitializer iz)
4132 {
4133 buf.writestring("__error__");
4134 }
4135
4136 void visitVoid(VoidInitializer iz)
4137 {
4138 buf.writestring("void");
4139 }
4140
4141 void visitDefault(DefaultInitializer iz)
4142 {
4143 buf.writestring("{ }");
4144 }
4145
4146 void visitStruct(StructInitializer si)
4147 {
4148 //printf("StructInitializer::toCBuffer()\n");
4149 buf.writeByte('{');
4150 foreach (i, const id; si.field)
4151 {
4152 if (i)
4153 buf.writestring(", ");
4154 if (id)
4155 {
4156 buf.writestring(id.toString());
4157 buf.writeByte(':');
4158 }
4159 if (auto iz = si.value[i])
4160 initializerToBuffer(iz, buf, hgs);
4161 }
4162 buf.writeByte('}');
4163 }
4164
4165 void visitArray(ArrayInitializer ai)
4166 {
4167 buf.writeByte('[');
4168 foreach (i, ex; ai.index)
4169 {
4170 if (i)
4171 buf.writestring(", ");
4172 if (ex)
4173 {
4174 ex.expressionToBuffer(buf, hgs);
4175 buf.writeByte(':');
4176 }
4177 if (auto iz = ai.value[i])
4178 initializerToBuffer(iz, buf, hgs);
4179 }
4180 buf.writeByte(']');
4181 }
4182
4183 void visitExp(ExpInitializer ei)
4184 {
4185 ei.exp.expressionToBuffer(buf, hgs);
4186 }
4187
4188 void visitC(CInitializer ci)
4189 {
4190 buf.writeByte('{');
4191 foreach (i, ref DesigInit di; ci.initializerList)
4192 {
4193 if (i)
4194 buf.writestring(", ");
4195 if (di.designatorList)
4196 {
4197 foreach (ref Designator d; (*di.designatorList)[])
4198 {
4199 if (d.exp)
4200 {
4201 buf.writeByte('[');
4202 toCBuffer(d.exp, buf, hgs);
4203 buf.writeByte(']');
4204 }
4205 else
4206 {
4207 buf.writeByte('.');
4208 buf.writestring(d.ident.toString());
4209 }
4210 }
4211 buf.writeByte('=');
4212 }
4213 initializerToBuffer(di.initializer, buf, hgs);
4214 }
4215 buf.writeByte('}');
4216 }
4217
4218 mixin VisitInitializer!void visit;
4219 visit.VisitInitializer(inx);
4220 }
4221
4222
4223 private void typeToBufferx(Type t, ref OutBuffer buf, ref HdrGenState hgs)
4224 {
4225 void visitType(Type t)
4226 {
4227 printf("t = %p, ty = %d\n", t, t.ty);
4228 assert(0);
4229 }
4230
4231 void visitError(TypeError t)
4232 {
4233 buf.writestring("_error_");
4234 }
4235
4236 void visitBasic(TypeBasic t)
4237 {
4238 //printf("TypeBasic::toCBuffer2(t.mod = %d)\n", t.mod);
4239 buf.writestring(t.dstring);
4240 }
4241
4242 void visitTraits(TypeTraits t)
4243 {
4244 //printf("TypeBasic::toCBuffer2(t.mod = %d)\n", t.mod);
4245 t.exp.expressionToBuffer(buf, hgs);
4246 }
4247
4248 void visitVector(TypeVector t)
4249 {
4250 //printf("TypeVector::toCBuffer2(t.mod = %d)\n", t.mod);
4251 buf.writestring("__vector(");
4252 visitWithMask(t.basetype, t.mod, buf, hgs);
4253 buf.writestring(")");
4254 }
4255
4256 void visitSArray(TypeSArray t)
4257 {
4258 visitWithMask(t.next, t.mod, buf, hgs);
4259 buf.writeByte('[');
4260 sizeToBuffer(t.dim, buf, hgs);
4261 buf.writeByte(']');
4262 }
4263
4264 void visitDArray(TypeDArray t)
4265 {
4266 Type ut = t.castMod(0);
4267 if (hgs.declstring)
4268 goto L1;
4269 if (ut.equals(Type.tstring))
4270 buf.writestring("string");
4271 else if (ut.equals(Type.twstring))
4272 buf.writestring("wstring");
4273 else if (ut.equals(Type.tdstring))
4274 buf.writestring("dstring");
4275 else
4276 {
4277 L1:
4278 visitWithMask(t.next, t.mod, buf, hgs);
4279 buf.writestring("[]");
4280 }
4281 }
4282
4283 void visitAArray(TypeAArray t)
4284 {
4285 visitWithMask(t.next, t.mod, buf, hgs);
4286 buf.writeByte('[');
4287 visitWithMask(t.index, 0, buf, hgs);
4288 buf.writeByte(']');
4289 }
4290
4291 void visitPointer(TypePointer t)
4292 {
4293 //printf("TypePointer::toCBuffer2() next = %d\n", t.next.ty);
4294 if (t.next.ty == Tfunction)
4295 visitFuncIdentWithPostfix(cast(TypeFunction)t.next, "function", buf, hgs, false);
4296 else
4297 {
4298 visitWithMask(t.next, t.mod, buf, hgs);
4299 buf.writeByte('*');
4300 }
4301 }
4302
4303 void visitReference(TypeReference t)
4304 {
4305 visitWithMask(t.next, t.mod, buf, hgs);
4306 buf.writeByte('&');
4307 }
4308
4309 void visitFunction(TypeFunction t)
4310 {
4311 //printf("TypeFunction::toCBuffer2() t = %p, ref = %d\n", t, t.isRef);
4312 visitFuncIdentWithPostfix(t, null, buf, hgs, false);
4313 }
4314
4315 void visitDelegate(TypeDelegate t)
4316 {
4317 visitFuncIdentWithPostfix(cast(TypeFunction)t.next, "delegate", buf, hgs, false);
4318 }
4319
4320 void visitTypeQualifiedHelper(TypeQualified t)
4321 {
4322 foreach (id; t.idents)
4323 {
4324 switch (id.dyncast()) with (DYNCAST)
4325 {
4326 case dsymbol:
4327 buf.writeByte('.');
4328 TemplateInstance ti = cast(TemplateInstance)id;
4329 ti.dsymbolToBuffer(buf, hgs);
4330 break;
4331 case expression:
4332 buf.writeByte('[');
4333 (cast(Expression)id).expressionToBuffer(buf, hgs);
4334 buf.writeByte(']');
4335 break;
4336 case type:
4337 buf.writeByte('[');
4338 typeToBufferx(cast(Type)id, buf, hgs);
4339 buf.writeByte(']');
4340 break;
4341 default:
4342 buf.writeByte('.');
4343 buf.writestring(id.toString());
4344 }
4345 }
4346 }
4347
4348 void visitIdentifier(TypeIdentifier t)
4349 {
4350 //printf("visitTypeIdentifier() %s\n", t.ident.toChars());
4351 buf.writestring(t.ident.toString());
4352 visitTypeQualifiedHelper(t);
4353 }
4354
4355 void visitInstance(TypeInstance t)
4356 {
4357 t.tempinst.dsymbolToBuffer(buf, hgs);
4358 visitTypeQualifiedHelper(t);
4359 }
4360
4361 void visitTypeof(TypeTypeof t)
4362 {
4363 buf.writestring("typeof(");
4364 t.exp.expressionToBuffer(buf, hgs);
4365 buf.writeByte(')');
4366 visitTypeQualifiedHelper(t);
4367 }
4368
4369 void visitReturn(TypeReturn t)
4370 {
4371 buf.writestring("typeof(return)");
4372 visitTypeQualifiedHelper(t);
4373 }
4374
4375 void visitEnum(TypeEnum t)
4376 {
4377 //printf("visitEnum: %s\n", t.sym.toChars());
4378 buf.writestring(hgs.fullQual ? t.sym.toPrettyChars() : t.sym.toChars());
4379 }
4380
4381 void visitStruct(TypeStruct t)
4382 {
4383 //printf("visitTypeStruct() %s\n", t.sym.toChars());
4384
4385 // https://issues.dlang.org/show_bug.cgi?id=13776
4386 // Don't use ti.toAlias() to avoid forward reference error
4387 // while printing messages.
4388 TemplateInstance ti = t.sym.parent ? t.sym.parent.isTemplateInstance() : null;
4389 if (ti && ti.aliasdecl == t.sym)
4390 buf.writestring(hgs.fullQual ? ti.toPrettyChars() : ti.toChars());
4391 else
4392 buf.writestring(hgs.fullQual ? t.sym.toPrettyChars() : t.sym.toChars());
4393 }
4394
4395 void visitClass(TypeClass t)
4396 {
4397 // https://issues.dlang.org/show_bug.cgi?id=13776
4398 // Don't use ti.toAlias() to avoid forward reference error
4399 // while printing messages.
4400 TemplateInstance ti = t.sym.parent ? t.sym.parent.isTemplateInstance() : null;
4401 if (ti && ti.aliasdecl == t.sym)
4402 buf.writestring(hgs.fullQual ? ti.toPrettyChars() : ti.toChars());
4403 else
4404 buf.writestring(hgs.fullQual ? t.sym.toPrettyChars() : t.sym.toChars());
4405 }
4406
4407 void visitTag(TypeTag t)
4408 {
4409 if (hgs.importcHdr && t.id)
4410 {
4411 // https://issues.dlang.org/show_bug.cgi?id=24670
4412 // `const` must be parenthesized because it can be a return type
4413 if (t.mod & MODFlags.const_)
4414 buf.writestring("const(");
4415
4416 // For C to D translation, `struct S` or `enum S` simply becomes `S`
4417 buf.writestring(t.id.toString());
4418
4419 if (t.mod & MODFlags.const_)
4420 buf.writestring(")");
4421 return;
4422 }
4423 // The following produces something like "const enum E : short"
4424 if (t.mod & MODFlags.const_)
4425 buf.writestring("const ");
4426 buf.writestring(Token.toString(t.tok));
4427 buf.writeByte(' ');
4428 if (t.id)
4429 buf.writestring(t.id.toString());
4430 if (t.tok == TOK.enum_ && t.base && t.base.ty != TY.Tint32)
4431 {
4432 buf.writestring(" : ");
4433 visitWithMask(t.base, t.mod, buf, hgs);
4434 }
4435 }
4436
4437 void visitTuple(TypeTuple t)
4438 {
4439 parametersToBuffer(ParameterList(t.arguments, VarArg.none), buf, hgs);
4440 }
4441
4442 void visitSlice(TypeSlice t)
4443 {
4444 visitWithMask(t.next, t.mod, buf, hgs);
4445 buf.writeByte('[');
4446 sizeToBuffer(t.lwr, buf, hgs);
4447 buf.writestring(" .. ");
4448 sizeToBuffer(t.upr, buf, hgs);
4449 buf.writeByte(']');
4450 }
4451
4452 void visitNull(TypeNull t)
4453 {
4454 buf.writestring("typeof(null)");
4455 }
4456
4457 void visitMixin(TypeMixin t)
4458 {
4459 buf.writestring("mixin(");
4460 argsToBuffer(t.exps, buf, hgs, null);
4461 buf.writeByte(')');
4462 }
4463
4464 void visitNoreturn(TypeNoreturn t)
4465 {
4466 buf.writestring("noreturn");
4467 }
4468
4469 if (hgs.importcHdr && !hgs.inCAlias && t.mcache && t.mcache.typedefIdent)
4470 {
4471 buf.writestring(t.mcache.typedefIdent.toString());
4472 return;
4473 }
4474
4475 switch (t.ty)
4476 {
4477 default: return t.isTypeBasic() ?
4478 visitBasic(cast(TypeBasic)t) :
4479 visitType(t);
4480
4481 case Terror: return visitError(cast(TypeError)t);
4482 case Ttraits: return visitTraits(cast(TypeTraits)t);
4483 case Tvector: return visitVector(cast(TypeVector)t);
4484 case Tsarray: return visitSArray(cast(TypeSArray)t);
4485 case Tarray: return visitDArray(cast(TypeDArray)t);
4486 case Taarray: return visitAArray(cast(TypeAArray)t);
4487 case Tpointer: return visitPointer(cast(TypePointer)t);
4488 case Treference: return visitReference(cast(TypeReference)t);
4489 case Tfunction: return visitFunction(cast(TypeFunction)t);
4490 case Tdelegate: return visitDelegate(cast(TypeDelegate)t);
4491 case Tident: return visitIdentifier(cast(TypeIdentifier)t);
4492 case Tinstance: return visitInstance(cast(TypeInstance)t);
4493 case Ttypeof: return visitTypeof(cast(TypeTypeof)t);
4494 case Treturn: return visitReturn(cast(TypeReturn)t);
4495 case Tenum: return visitEnum(cast(TypeEnum)t);
4496 case Tstruct: return visitStruct(cast(TypeStruct)t);
4497 case Tclass: return visitClass(cast(TypeClass)t);
4498 case Ttuple: return visitTuple (cast(TypeTuple)t);
4499 case Tslice: return visitSlice(cast(TypeSlice)t);
4500 case Tnull: return visitNull(cast(TypeNull)t);
4501 case Tmixin: return visitMixin(cast(TypeMixin)t);
4502 case Tnoreturn: return visitNoreturn(cast(TypeNoreturn)t);
4503 case Ttag: return visitTag(cast(TypeTag)t);
4504 }
4505 }
4506
4507 /****************************************
4508 * Convert EXP to char*.
4509 */
4510
4511 string EXPtoString(EXP op)
4512 {
4513 static immutable char*[EXP.max + 1] strings =
4514 [
4515 EXP.type : "type",
4516 EXP.error : "error",
4517 EXP.objcClassReference : "class",
4518
4519 EXP.mixin_ : "mixin",
4520
4521 EXP.import_ : "import",
4522 EXP.dotVariable : "dotvar",
4523 EXP.scope_ : "scope",
4524 EXP.identifier : "identifier",
4525 EXP.this_ : "this",
4526 EXP.super_ : "super",
4527 EXP.int64 : "long",
4528 EXP.float64 : "double",
4529 EXP.complex80 : "creal",
4530 EXP.null_ : "null",
4531 EXP.string_ : "string",
4532 EXP.arrayLiteral : "arrayliteral",
4533 EXP.assocArrayLiteral : "assocarrayliteral",
4534 EXP.classReference : "classreference",
4535 EXP.file : "__FILE__",
4536 EXP.fileFullPath : "__FILE_FULL_PATH__",
4537 EXP.line : "__LINE__",
4538 EXP.moduleString : "__MODULE__",
4539 EXP.functionString : "__FUNCTION__",
4540 EXP.prettyFunction : "__PRETTY_FUNCTION__",
4541 EXP.typeid_ : "typeid",
4542 EXP.is_ : "is",
4543 EXP.assert_ : "assert",
4544 EXP.halt : "halt",
4545 EXP.template_ : "template",
4546 EXP.dSymbol : "symbol",
4547 EXP.function_ : "function",
4548 EXP.variable : "var",
4549 EXP.symbolOffset : "symoff",
4550 EXP.structLiteral : "structLiteral",
4551 EXP.compoundLiteral : "compoundliteral",
4552 EXP.arrayLength : "arraylength",
4553 EXP.delegatePointer : "delegateptr",
4554 EXP.delegateFunctionPointer : "delegatefuncptr",
4555 EXP.remove : "remove",
4556 EXP.tuple : "sequence",
4557 EXP.traits : "__traits",
4558 EXP.overloadSet : "__overloadset",
4559 EXP.void_ : "void",
4560 EXP.vectorArray : "vectorarray",
4561 EXP._Generic : "_Generic",
4562
4563 // post
4564 EXP.dotTemplateInstance : "dotti",
4565 EXP.dotIdentifier : "dotid",
4566 EXP.dotTemplateDeclaration : "dottd",
4567 EXP.dot : ".",
4568 EXP.dotType : "dottype",
4569 EXP.plusPlus : "++",
4570 EXP.minusMinus : "--",
4571 EXP.prePlusPlus : "++",
4572 EXP.preMinusMinus : "--",
4573 EXP.call : "call",
4574 EXP.slice : "..",
4575 EXP.array : "[]",
4576 EXP.index : "[i]",
4577
4578 EXP.delegate_ : "delegate",
4579 EXP.address : "&",
4580 EXP.star : "*",
4581 EXP.negate : "-",
4582 EXP.uadd : "+",
4583 EXP.not : "!",
4584 EXP.tilde : "~",
4585 EXP.delete_ : "delete",
4586 EXP.new_ : "new",
4587 EXP.newAnonymousClass : "newanonclass",
4588 EXP.cast_ : "cast",
4589
4590 EXP.vector : "__vector",
4591 EXP.pow : "^^",
4592
4593 EXP.mul : "*",
4594 EXP.div : "/",
4595 EXP.mod : "%",
4596
4597 EXP.add : "+",
4598 EXP.min : "-",
4599 EXP.concatenate : "~",
4600
4601 EXP.leftShift : "<<",
4602 EXP.rightShift : ">>",
4603 EXP.unsignedRightShift : ">>>",
4604
4605 EXP.lessThan : "<",
4606 EXP.lessOrEqual : "<=",
4607 EXP.greaterThan : ">",
4608 EXP.greaterOrEqual : ">=",
4609 EXP.in_ : "in",
4610
4611 EXP.equal : "==",
4612 EXP.notEqual : "!=",
4613 EXP.identity : "is",
4614 EXP.notIdentity : "!is",
4615
4616 EXP.and : "&",
4617 EXP.xor : "^",
4618 EXP.or : "|",
4619
4620 EXP.andAnd : "&&",
4621 EXP.orOr : "||",
4622
4623 EXP.question : "?",
4624
4625 EXP.assign : "=",
4626 EXP.construct : "=",
4627 EXP.blit : "=",
4628 EXP.addAssign : "+=",
4629 EXP.minAssign : "-=",
4630 EXP.concatenateAssign : "~=",
4631 EXP.concatenateElemAssign : "~=",
4632 EXP.concatenateDcharAssign : "~=",
4633 EXP.mulAssign : "*=",
4634 EXP.divAssign : "/=",
4635 EXP.modAssign : "%=",
4636 EXP.powAssign : "^^=",
4637 EXP.leftShiftAssign : "<<=",
4638 EXP.rightShiftAssign : ">>=",
4639 EXP.unsignedRightShiftAssign : ">>>=",
4640 EXP.andAssign : "&=",
4641 EXP.orAssign : "|=",
4642 EXP.xorAssign : "^=",
4643
4644 EXP.comma : ",",
4645 EXP.declaration : "declaration",
4646
4647 EXP.interval : "interval",
4648 EXP.loweredAssignExp : "=",
4649
4650 EXP.thrownException : "CTFE ThrownException",
4651 EXP.cantExpression : "<cant>",
4652 EXP.voidExpression : "cast(void)0",
4653 EXP.showCtfeContext : "<error>",
4654 EXP.break_ : "<break>",
4655 EXP.continue_ : "<continue>",
4656 EXP.goto_ : "<goto>",
4657 ];
4658 const p = strings[op];
4659 if (!p)
4660 {
4661 printf("error: EXP %d has no string\n", op);
4662 return "XXXXX";
4663 //assert(0);
4664 }
4665 assert(p);
4666 return p[0 .. strlen(p)];
4667 }