forked from ldc-developers/ldc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoc.d
5296 lines (4923 loc) · 175 KB
/
doc.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Ddoc documentation generation.
*
* Specification: $(LINK2 https://dlang.org/spec/ddoc.html, Documentation Generator)
*
* Copyright: Copyright (C) 1999-2024 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/doc.d, _doc.d)
* Documentation: https://dlang.org/phobos/dmd_doc.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/doc.d
*/
module dmd.doc;
import core.stdc.ctype;
import core.stdc.stdlib;
import core.stdc.stdio;
import core.stdc.string;
import core.stdc.time;
import dmd.aggregate;
import dmd.arraytypes;
import dmd.astenums;
import dmd.attrib;
import dmd.cond;
import dmd.dclass;
import dmd.declaration;
import dmd.denum;
import dmd.dimport;
import dmd.dmacro;
import dmd.dmodule;
import dmd.dscope;
import dmd.dstruct;
import dmd.dsymbol;
import dmd.dsymbolsem;
import dmd.dtemplate;
import dmd.errorsink;
import dmd.func;
import dmd.globals;
import dmd.hdrgen;
import dmd.id;
import dmd.identifier;
import dmd.lexer;
import dmd.location;
import dmd.mtype;
import dmd.root.array;
import dmd.root.file;
import dmd.root.filename;
import dmd.common.outbuffer;
import dmd.root.port;
import dmd.root.rmem;
import dmd.root.string;
import dmd.root.utf;
import dmd.tokens;
import dmd.visitor;
private:
public
struct Escape
{
const(char)[][char.max] strings;
/***************************************
* Find character string to replace c with.
*/
const(char)[] escapeChar(char c) @safe
{
version (all)
{
//printf("escapeChar('%c') => %p, %p\n", c, strings, strings[c].ptr);
return strings[c];
}
else
{
const(char)[] s;
switch (c)
{
case '<':
s = "<";
break;
case '>':
s = ">";
break;
case '&':
s = "&";
break;
default:
s = null;
break;
}
return s;
}
}
}
/***********************************************************
*/
class Section
{
const(char)[] name;
const(char)[] body_;
int nooutput;
override string toString() const
{
assert(0);
}
void write(Loc loc, DocComment* dc, Scope* sc, Dsymbols* a, ref OutBuffer buf)
{
assert(a.length);
if (name.length)
{
static immutable table =
[
"AUTHORS",
"BUGS",
"COPYRIGHT",
"DATE",
"DEPRECATED",
"EXAMPLES",
"HISTORY",
"LICENSE",
"RETURNS",
"SEE_ALSO",
"STANDARDS",
"THROWS",
"VERSION",
];
foreach (entry; table)
{
if (iequals(entry, name))
{
buf.printf("$(DDOC_%s ", entry.ptr);
goto L1;
}
}
buf.writestring("$(DDOC_SECTION ");
// Replace _ characters with spaces
buf.writestring("$(DDOC_SECTION_H ");
size_t o = buf.length;
foreach (char c; name)
buf.writeByte((c == '_') ? ' ' : c);
escapeStrayParenthesis(loc, buf, o, false, sc.eSink);
buf.writestring(")");
}
else
{
buf.writestring("$(DDOC_DESCRIPTION ");
}
L1:
size_t o = buf.length;
buf.write(body_);
escapeStrayParenthesis(loc, buf, o, true, sc.eSink);
highlightText(sc, a, loc, buf, o);
buf.writestring(")");
}
}
/***********************************************************
*/
final class ParamSection : Section
{
override void write(Loc loc, DocComment* dc, Scope* sc, Dsymbols* a, ref OutBuffer buf)
{
assert(a.length);
Dsymbol s = (*a)[0]; // test
const(char)* p = body_.ptr;
size_t len = body_.length;
const(char)* pend = p + len;
const(char)* tempstart = null;
size_t templen = 0;
const(char)* namestart = null;
size_t namelen = 0; // !=0 if line continuation
const(char)* textstart = null;
size_t textlen = 0;
size_t paramcount = 0;
buf.writestring("$(DDOC_PARAMS ");
while (p < pend)
{
// Skip to start of macro
while (1)
{
switch (*p)
{
case ' ':
case '\t':
p++;
continue;
case '\n':
p++;
goto Lcont;
default:
if (isIdStart(p) || isCVariadicArg(p[0 .. cast(size_t)(pend - p)]))
break;
if (namelen)
goto Ltext;
// continuation of prev macro
goto Lskipline;
}
break;
}
tempstart = p;
while (isIdTail(p))
p += utfStride(p);
if (isCVariadicArg(p[0 .. cast(size_t)(pend - p)]))
p += 3;
templen = p - tempstart;
while (*p == ' ' || *p == '\t')
p++;
if (*p != '=')
{
if (namelen)
goto Ltext;
// continuation of prev macro
goto Lskipline;
}
p++;
if (namelen)
{
// Output existing param
L1:
//printf("param '%.*s' = '%.*s'\n", cast(int)namelen, namestart, cast(int)textlen, textstart);
++paramcount;
HdrGenState hgs;
buf.writestring("$(DDOC_PARAM_ROW ");
{
buf.writestring("$(DDOC_PARAM_ID ");
{
size_t o = buf.length;
Parameter fparam = isFunctionParameter(a, namestart[0 .. namelen]);
if (!fparam)
{
// Comments on a template might refer to function parameters within.
// Search the parameters of nested eponymous functions (with the same name.)
fparam = isEponymousFunctionParameter(a, namestart[0 .. namelen]);
}
bool isCVariadic = isCVariadicParameter(a, namestart[0 .. namelen]);
if (isCVariadic)
{
buf.writestring("...");
}
else if (fparam && fparam.type && fparam.ident)
{
toCBuffer(fparam.type, buf, fparam.ident, hgs);
}
else
{
if (isTemplateParameter(a, namestart, namelen))
{
// 10236: Don't count template parameters for params check
--paramcount;
}
else if (!fparam)
{
sc.eSink.warning(s.loc, "Ddoc: function declaration has no parameter '%.*s'", cast(int)namelen, namestart);
}
buf.write(namestart[0 .. namelen]);
}
escapeStrayParenthesis(loc, buf, o, true, sc.eSink);
highlightCode(sc, a, buf, o);
}
buf.writestring(")");
buf.writestring("$(DDOC_PARAM_DESC ");
{
size_t o = buf.length;
buf.write(textstart[0 .. textlen]);
escapeStrayParenthesis(loc, buf, o, true, sc.eSink);
highlightText(sc, a, loc, buf, o);
}
buf.writestring(")");
}
buf.writestring(")");
namelen = 0;
if (p >= pend)
break;
}
namestart = tempstart;
namelen = templen;
while (*p == ' ' || *p == '\t')
p++;
textstart = p;
Ltext:
while (*p != '\n')
p++;
textlen = p - textstart;
p++;
Lcont:
continue;
Lskipline:
// Ignore this line
while (*p++ != '\n')
{
}
}
if (namelen)
goto L1;
// write out last one
buf.writestring(")");
TypeFunction tf = a.length == 1 ? isTypeFunction(s) : null;
if (tf)
{
size_t pcount = (tf.parameterList.parameters ? tf.parameterList.parameters.length : 0) +
cast(int)(tf.parameterList.varargs == VarArg.variadic);
if (pcount != paramcount)
{
sc.eSink.warning(s.loc, "Ddoc: parameter count mismatch, expected %llu, got %llu",
cast(ulong) pcount, cast(ulong) paramcount);
if (paramcount == 0)
{
// Chances are someone messed up the format
sc.eSink.warningSupplemental(s.loc, "Note that the format is `param = description`");
}
}
}
}
}
/***********************************************************
*/
final class MacroSection : Section
{
override void write(Loc loc, DocComment* dc, Scope* sc, Dsymbols* a, ref OutBuffer buf)
{
//printf("MacroSection::write()\n");
DocComment.parseMacros(dc.escapetable, *dc.pmacrotable, body_);
}
}
alias Sections = Array!(Section);
// Workaround for missing Parameter instance for variadic params. (it's unnecessary to instantiate one).
bool isCVariadicParameter(Dsymbols* a, const(char)[] p) @safe
{
foreach (member; *a)
{
TypeFunction tf = isTypeFunction(member);
if (tf && tf.parameterList.varargs == VarArg.variadic && p == "...")
return true;
}
return false;
}
Dsymbol getEponymousMember(TemplateDeclaration td) @safe
{
if (!td.onemember)
return null;
if (AggregateDeclaration ad = td.onemember.isAggregateDeclaration())
return ad;
if (FuncDeclaration fd = td.onemember.isFuncDeclaration())
return fd;
if (auto em = td.onemember.isEnumMember())
return null; // Keep backward compatibility. See compilable/ddoc9.d
if (VarDeclaration vd = td.onemember.isVarDeclaration())
return td.constraint ? null : vd;
return null;
}
TemplateDeclaration getEponymousParent(Dsymbol s) @safe
{
if (!s.parent)
return null;
TemplateDeclaration td = s.parent.isTemplateDeclaration();
return (td && getEponymousMember(td)) ? td : null;
}
immutable ddoc_default = import("default_ddoc_theme." ~ ddoc_ext);
immutable ddoc_decl_s = "$(DDOC_DECL ";
immutable ddoc_decl_e = ")\n";
immutable ddoc_decl_dd_s = "$(DDOC_DECL_DD ";
immutable ddoc_decl_dd_e = ")\n";
/****************************************************
* Generate Ddoc file for Module m.
* Params:
* m = Module
* ddoctext_ptr = combined text of .ddoc files for macro definitions
* ddoctext_length = extant of ddoctext_ptr
* datetime = charz returned by ctime()
* eSink = send error messages to eSink
* outbuf = append the Ddoc text to this
*/
public
void gendocfile(Module m, const char* ddoctext_ptr, size_t ddoctext_length, const char* datetime, ErrorSink eSink, ref OutBuffer outbuf)
{
gendocfile(m, ddoctext_ptr[0 .. ddoctext_length], datetime, eSink, outbuf);
}
/****************************************************
* Generate Ddoc text for Module `m` and append it to `outbuf`.
* Params:
* m = Module
* ddoctext = combined text of .ddoc files for macro definitions
* datetime = charz returned by ctime()
* eSink = send error messages to eSink
* outbuf = append the Ddoc text to this
*/
public
void gendocfile(Module m, const char[] ddoctext, const char* datetime, ErrorSink eSink, ref OutBuffer outbuf)
{
version (IN_LLVM)
{
m.checkAndAddOutputFile(m.docfile);
}
// Load internal default macros first
DocComment.parseMacros(m.escapetable, m.macrotable, ddoc_default[]);
// Ddoc files override default macros
DocComment.parseMacros(m.escapetable, m.macrotable, ddoctext);
Scope* sc = Scope.createGlobal(m, eSink); // create root scope
DocComment* dc = DocComment.parse(m, m.comment);
dc.pmacrotable = &m.macrotable;
dc.escapetable = m.escapetable;
sc.lastdc = dc;
// Generate predefined macros
// Set the title to be the name of the module
{
const p = m.toPrettyChars().toDString;
m.macrotable.define("TITLE", p);
}
// Set time macros
m.macrotable.define("DATETIME", datetime[0 .. 26]);
m.macrotable.define("YEAR", datetime[20 .. 20 + 4]);
const srcfilename = m.srcfile.toString();
m.macrotable.define("SRCFILENAME", srcfilename);
const docfilename = m.docfile.toString();
m.macrotable.define("DOCFILENAME", docfilename);
if (dc.copyright)
{
dc.copyright.nooutput = 1;
m.macrotable.define("COPYRIGHT", dc.copyright.body_);
}
OutBuffer buf;
if (m.filetype == FileType.ddoc)
{
const ploc = m.md ? &m.md.loc : &m.loc;
Loc loc = *ploc;
if (!loc.filename)
loc.filename = srcfilename.ptr;
size_t commentlen = m.comment ? strlen(cast(char*)m.comment) : 0;
Dsymbols a;
// https://issues.dlang.org/show_bug.cgi?id=9764
// Don't push m in a, to prevent emphasize ddoc file name.
if (dc.macros)
{
commentlen = dc.macros.name.ptr - m.comment;
dc.macros.write(loc, dc, sc, &a, buf);
}
buf.write(m.comment[0 .. commentlen]);
highlightText(sc, &a, loc, buf, 0);
}
else
{
Dsymbols a;
a.push(m);
dc.writeSections(sc, &a, buf);
emitMemberComments(m, buf, sc);
}
//printf("BODY= '%.*s'\n", cast(int)buf.length, buf.data);
m.macrotable.define("BODY", buf[]);
OutBuffer buf2;
buf2.writestring("$(DDOC)");
size_t end = buf2.length;
// Expand buf in place with macro expansions
const success = m.macrotable.expand(buf2, 0, end, null, global.recursionLimit, &isIdStart, &isIdTail);
if (!success)
eSink.error(Loc.initial, "DDoc macro expansion limit exceeded; more than %d expansions.", global.recursionLimit);
/* Remove all the escape sequences from buf,
* and make CR-LF the newline.
*/
const slice = buf2[];
outbuf.reserve(slice.length);
auto p = slice.ptr;
for (size_t j = 0; j < slice.length; j++)
{
char c = p[j];
if (c == 0xFF && j + 1 < slice.length)
{
j++;
continue;
}
if (c == '\n')
outbuf.writeByte('\r');
else if (c == '\r')
{
outbuf.writestring("\r\n");
if (j + 1 < slice.length && p[j + 1] == '\n')
{
j++;
}
continue;
}
outbuf.writeByte(c);
}
}
/****************************************************
* Having unmatched parentheses can hose the output of Ddoc,
* as the macros depend on properly nested parentheses.
* This function replaces all ( with $(LPAREN) and ) with $(RPAREN)
* to preserve text literally. This also means macros in the
* text won't be expanded.
*/
public
void escapeDdocString(ref OutBuffer buf, size_t start)
{
for (size_t u = start; u < buf.length; u++)
{
char c = buf[u];
switch (c)
{
case '$':
buf.remove(u, 1);
buf.insert(u, "$(DOLLAR)");
u += 8;
break;
case '(':
buf.remove(u, 1); //remove the (
buf.insert(u, "$(LPAREN)"); //insert this instead
u += 8; //skip over newly inserted macro
break;
case ')':
buf.remove(u, 1); //remove the )
buf.insert(u, "$(RPAREN)"); //insert this instead
u += 8; //skip over newly inserted macro
break;
default:
break;
}
}
}
/****************************************************
* Having unmatched parentheses can hose the output of Ddoc,
* as the macros depend on properly nested parentheses.
*
* Fix by replacing unmatched ( with $(LPAREN) and unmatched ) with $(RPAREN).
*
* Params:
* loc = source location of start of text. It is a mutable copy to allow incrementing its linenum, for printing the correct line number when an error is encountered in a multiline block of ddoc.
* buf = an OutBuffer containing the DDoc
* start = the index within buf to start replacing unmatched parentheses
* respectBackslashEscapes = if true, always replace parentheses that are
* directly preceeded by a backslash with $(LPAREN) or $(RPAREN) instead of
* counting them as stray parentheses
*/
private void escapeStrayParenthesis(Loc loc, ref OutBuffer buf, size_t start, bool respectBackslashEscapes, ErrorSink eSink)
{
uint par_open = 0;
char inCode = 0;
bool atLineStart = true;
for (size_t u = start; u < buf.length; u++)
{
char c = buf[u];
switch (c)
{
case '(':
if (!inCode)
par_open++;
atLineStart = false;
break;
case ')':
if (!inCode)
{
if (par_open == 0)
{
//stray ')'
eSink.warning(loc, "Ddoc: Stray ')'. This may cause incorrect Ddoc output. Use $(RPAREN) instead for unpaired right parentheses.");
buf.remove(u, 1); //remove the )
buf.insert(u, "$(RPAREN)"); //insert this instead
u += 8; //skip over newly inserted macro
}
else
par_open--;
}
atLineStart = false;
break;
case '\n':
atLineStart = true;
version (none)
{
// For this to work, loc must be set to the beginning of the passed
// text which is currently not possible
// (loc is set to the Loc of the Dsymbol)
loc.linnum++;
}
break;
case ' ':
case '\r':
case '\t':
break;
case '-':
case '`':
case '~':
// Issue 15465: don't try to escape unbalanced parens inside code
// blocks.
int numdash = 1;
for (++u; u < buf.length && buf[u] == c; ++u)
++numdash;
--u;
if (c == '`' || (atLineStart && numdash >= 3))
{
if (inCode == c)
inCode = 0;
else if (!inCode)
inCode = c;
}
atLineStart = false;
break;
case '\\':
// replace backslash-escaped parens with their macros
if (!inCode && respectBackslashEscapes && u+1 < buf.length)
{
if (buf[u+1] == '(' || buf[u+1] == ')')
{
const paren = buf[u+1] == '(' ? "$(LPAREN)" : "$(RPAREN)";
buf.remove(u, 2); //remove the \)
buf.insert(u, paren); //insert this instead
u += 8; //skip over newly inserted macro
}
else if (buf[u+1] == '\\')
++u;
}
break;
default:
atLineStart = false;
break;
}
}
if (par_open) // if any unmatched lparens
{
par_open = 0;
for (size_t u = buf.length; u > start;)
{
u--;
char c = buf[u];
switch (c)
{
case ')':
par_open++;
break;
case '(':
if (par_open == 0)
{
//stray '('
eSink.warning(loc, "Ddoc: Stray '('. This may cause incorrect Ddoc output. Use $(LPAREN) instead for unpaired left parentheses.");
buf.remove(u, 1); //remove the (
buf.insert(u, "$(LPAREN)"); //insert this instead
}
else
par_open--;
break;
default:
break;
}
}
}
}
// Basically, this is to skip over things like private{} blocks in a struct or
// class definition that don't add any components to the qualified name.
Scope* skipNonQualScopes(Scope* sc) @safe
{
while (sc && !sc.scopesym)
sc = sc.enclosing;
return sc;
}
bool emitAnchorName(ref OutBuffer buf, Dsymbol s, Scope* sc, bool includeParent)
{
if (!s || s.isPackage() || s.isModule())
return false;
// Add parent names first
bool dot = false;
auto eponymousParent = getEponymousParent(s);
if (includeParent && s.parent || eponymousParent)
dot = emitAnchorName(buf, s.parent, sc, includeParent);
else if (includeParent && sc)
dot = emitAnchorName(buf, sc.scopesym, skipNonQualScopes(sc.enclosing), includeParent);
// Eponymous template members can share the parent anchor name
if (eponymousParent)
return dot;
if (dot)
buf.writeByte('.');
// Use "this" not "__ctor"
TemplateDeclaration td;
if (s.isCtorDeclaration() || ((td = s.isTemplateDeclaration()) !is null && td.onemember && td.onemember.isCtorDeclaration()))
{
buf.writestring("this");
}
else
{
/* We just want the identifier, not overloads like TemplateDeclaration::toChars.
* We don't want the template parameter list and constraints. */
buf.writestring(s.Dsymbol.toChars());
}
return true;
}
void emitAnchor(ref OutBuffer buf, Dsymbol s, Scope* sc, bool forHeader = false)
{
Identifier ident;
{
OutBuffer anc;
emitAnchorName(anc, s, skipNonQualScopes(sc), true);
ident = Identifier.idPool(anc[]);
}
auto pcount = cast(void*)ident in sc.anchorCounts;
typeof(*pcount) count;
if (!forHeader)
{
if (pcount)
{
// Existing anchor,
// don't write an anchor for matching consecutive ditto symbols
TemplateDeclaration td = getEponymousParent(s);
if (sc.prevAnchor == ident && sc.lastdc && (isDitto(s.comment) || (td && isDitto(td.comment))))
return;
count = ++*pcount;
}
else
{
sc.anchorCounts[cast(void*)ident] = 1;
count = 1;
}
}
// cache anchor name
sc.prevAnchor = ident;
auto macroName = forHeader ? "DDOC_HEADER_ANCHOR" : "DDOC_ANCHOR";
if (auto imp = s.isImport())
{
// For example: `public import core.stdc.string : memcpy, memcmp;`
if (imp.aliases.length > 0)
{
for(int i = 0; i < imp.aliases.length; i++)
{
// Need to distinguish between
// `public import core.stdc.string : memcpy, memcmp;` and
// `public import core.stdc.string : copy = memcpy, compare = memcmp;`
auto a = imp.aliases[i];
auto id = a ? a : imp.names[i];
auto loc = Loc.init;
Dsymbol pscopesym;
if (auto symFromId = sc.search(loc, id, pscopesym))
{
emitAnchor(buf, symFromId, sc, forHeader);
}
}
}
else
{
// For example: `public import str = core.stdc.string;`
if (imp.aliasId)
{
auto symbolName = imp.aliasId.toString();
buf.printf("$(%.*s %.*s", cast(int) macroName.length, macroName.ptr,
cast(int) symbolName.length, symbolName.ptr);
if (forHeader)
{
buf.printf(", %.*s", cast(int) symbolName.length, symbolName.ptr);
}
}
else
{
// The general case: `public import core.stdc.string;`
// fully qualify imports so `core.stdc.string` doesn't appear as `core`
void printFullyQualifiedImport()
{
foreach (const pid; imp.packages)
{
buf.printf("%s.", pid.toChars());
}
buf.writestring(imp.id.toString());
}
buf.printf("$(%.*s ", cast(int) macroName.length, macroName.ptr);
printFullyQualifiedImport();
if (forHeader)
{
buf.printf(", ");
printFullyQualifiedImport();
}
}
buf.writeByte(')');
}
}
else
{
auto symbolName = ident.toString();
buf.printf("$(%.*s %.*s", cast(int) macroName.length, macroName.ptr,
cast(int) symbolName.length, symbolName.ptr);
// only append count once there's a duplicate
if (count > 1)
buf.printf(".%u", count);
if (forHeader)
{
Identifier shortIdent;
{
OutBuffer anc;
emitAnchorName(anc, s, skipNonQualScopes(sc), false);
shortIdent = Identifier.idPool(anc[]);
}
auto shortName = shortIdent.toString();
buf.printf(", %.*s", cast(int) shortName.length, shortName.ptr);
}
buf.writeByte(')');
}
}
/******************************* emitComment **********************************/
/** Get leading indentation from 'src' which represents lines of code. */
size_t getCodeIndent(const(char)* src)
{
while (src && (*src == '\r' || *src == '\n'))
++src; // skip until we find the first non-empty line
size_t codeIndent = 0;
while (src && (*src == ' ' || *src == '\t'))
{
codeIndent++;
src++;
}
return codeIndent;
}
/** Recursively expand template mixin member docs into the scope. */
void expandTemplateMixinComments(TemplateMixin tm, ref OutBuffer buf, Scope* sc)
{
if (!tm.semanticRun)
tm.dsymbolSemantic(sc);
TemplateDeclaration td = (tm && tm.tempdecl) ? tm.tempdecl.isTemplateDeclaration() : null;
if (td && td.members)
{
for (size_t i = 0; i < td.members.length; i++)
{
Dsymbol sm = (*td.members)[i];
TemplateMixin tmc = sm.isTemplateMixin();
if (tmc && tmc.comment)
expandTemplateMixinComments(tmc, buf, sc);
else
emitComment(sm, buf, sc);
}
}
}
void emitMemberComments(ScopeDsymbol sds, ref OutBuffer buf, Scope* sc)
{
if (!sds.members)
return;
//printf("ScopeDsymbol::emitMemberComments() %s\n", toChars());
const(char)[] m = "$(DDOC_MEMBERS ";
if (sds.isTemplateDeclaration())
m = "$(DDOC_TEMPLATE_MEMBERS ";
else if (sds.isClassDeclaration())
m = "$(DDOC_CLASS_MEMBERS ";
else if (sds.isStructDeclaration())
m = "$(DDOC_STRUCT_MEMBERS ";
else if (sds.isEnumDeclaration())
m = "$(DDOC_ENUM_MEMBERS ";
else if (sds.isModule())
m = "$(DDOC_MODULE_MEMBERS ";
size_t offset1 = buf.length; // save starting offset
buf.writestring(m);
size_t offset2 = buf.length; // to see if we write anything
sc = sc.push(sds);
for (size_t i = 0; i < sds.members.length; i++)
{
Dsymbol s = (*sds.members)[i];
//printf("\ts = '%s'\n", s.toChars());
// only expand if parent is a non-template (semantic won't work)
if (s.comment && s.isTemplateMixin() && s.parent && !s.parent.isTemplateDeclaration())
expandTemplateMixinComments(cast(TemplateMixin)s, buf, sc);
emitComment(s, buf, sc);
}
emitComment(null, buf, sc);
sc.pop();
if (buf.length == offset2)
{
/* Didn't write out any members, so back out last write
*/
buf.setsize(offset1);
}
else
buf.writestring(")");
}
void emitVisibility(ref OutBuffer buf, Import i)
{
// imports are private by default, which is different from other declarations
// so they should explicitly show their visibility
emitVisibility(buf, i.visibility);
}
void emitVisibility(ref OutBuffer buf, Declaration d)
{
auto vis = d.visibility;
if (vis.kind != Visibility.Kind.undefined && vis.kind != Visibility.Kind.public_)
{
emitVisibility(buf, vis);
}
}
void emitVisibility(ref OutBuffer buf, Visibility vis)
{
visibilityToBuffer(buf, vis);
buf.writeByte(' ');
}
void emitComment(Dsymbol s, ref OutBuffer buf, Scope* sc)
{
extern (C++) final class EmitComment : Visitor
{
alias visit = Visitor.visit;
public:
OutBuffer* buf;
Scope* sc;
extern (D) this(ref OutBuffer buf, Scope* sc) scope
{
this.buf = &buf;
this.sc = sc;
}
override void visit(Dsymbol)
{
}
override void visit(InvariantDeclaration)
{
}
override void visit(UnitTestDeclaration)
{
}
override void visit(PostBlitDeclaration)
{
}
override void visit(DtorDeclaration)
{
}
override void visit(StaticCtorDeclaration)
{
}
override void visit(StaticDtorDeclaration)
{
}
override void visit(TypeInfoDeclaration)
{
}
void emit(Scope* sc, Dsymbol s, const(char)* com)
{
if (s && sc.lastdc && isDitto(com))
{
sc.lastdc.a.push(s);
return;
}
// Put previous doc comment if exists
if (DocComment* dc = sc.lastdc)
{
assert(dc.a.length > 0, "Expects at least one declaration for a" ~
"documentation comment");
auto symbol = dc.a[0];
buf.writestring("$(DDOC_MEMBER");
buf.writestring("$(DDOC_MEMBER_HEADER");
emitAnchor(*buf, symbol, sc, true);
buf.writeByte(')');
// Put the declaration signatures as the document 'title'
buf.writestring(ddoc_decl_s);
for (size_t i = 0; i < dc.a.length; i++)