Debian Codegraph @

gcc/d/dmd/doc.d

raw
1 /**
2 * Ddoc documentation generation.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/ddoc.html, Documentation Generator)
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/doc.d, _doc.d)
10 * Documentation: https://dlang.org/phobos/dmd_doc.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/doc.d
12 */
13
14 module dmd.doc;
15
16 import core.stdc.ctype;
17 import core.stdc.stdlib;
18 import core.stdc.stdio;
19 import core.stdc.string;
20 import core.stdc.time;
21 import dmd.aggregate;
22 import dmd.arraytypes;
23 import dmd.astenums;
24 import dmd.attrib;
25 import dmd.cond;
26 import dmd.dclass;
27 import dmd.declaration;
28 import dmd.denum;
29 import dmd.dimport;
30 import dmd.dmacro;
31 import dmd.dmodule;
32 import dmd.dscope;
33 import dmd.dstruct;
34 import dmd.dsymbol;
35 import dmd.dsymbolsem;
36 import dmd.dtemplate;
37 import dmd.errorsink;
38 import dmd.func;
39 import dmd.globals;
40 import dmd.hdrgen;
41 import dmd.id;
42 import dmd.identifier;
43 import dmd.lexer;
44 import dmd.location;
45 import dmd.mtype;
46 import dmd.root.array;
47 import dmd.root.file;
48 import dmd.root.filename;
49 import dmd.common.outbuffer;
50 import dmd.root.port;
51 import dmd.root.rmem;
52 import dmd.root.string;
53 import dmd.root.utf;
54 import dmd.tokens;
55 import dmd.visitor;
56
57 private:
58
59 public
60 struct Escape
61 {
62 const(char)[][char.max] strings;
63
64 /***************************************
65 * Find character string to replace c with.
66 */
67 const(char)[] escapeChar(char c) @safe
68 {
69 version (all)
70 {
71 //printf("escapeChar('%c') => %p, %p\n", c, strings, strings[c].ptr);
72 return strings[c];
73 }
74 else
75 {
76 const(char)[] s;
77 switch (c)
78 {
79 case '<':
80 s = "&lt;";
81 break;
82 case '>':
83 s = "&gt;";
84 break;
85 case '&':
86 s = "&amp;";
87 break;
88 default:
89 s = null;
90 break;
91 }
92 return s;
93 }
94 }
95 }
96
97 /***********************************************************
98 */
99 class Section
100 {
101 const(char)[] name;
102 const(char)[] body_;
103 int nooutput;
104
105 override string toString() const
106 {
107 assert(0);
108 }
109
110 void write(Loc loc, DocComment* dc, Scope* sc, Dsymbols* a, ref OutBuffer buf)
111 {
112 assert(a.length);
113 if (name.length)
114 {
115 static immutable table =
116 [
117 "AUTHORS",
118 "BUGS",
119 "COPYRIGHT",
120 "DATE",
121 "DEPRECATED",
122 "EXAMPLES",
123 "HISTORY",
124 "LICENSE",
125 "RETURNS",
126 "SEE_ALSO",
127 "STANDARDS",
128 "THROWS",
129 "VERSION",
130 ];
131 foreach (entry; table)
132 {
133 if (iequals(entry, name))
134 {
135 buf.printf("$(DDOC_%s ", entry.ptr);
136 goto L1;
137 }
138 }
139 buf.writestring("$(DDOC_SECTION ");
140 // Replace _ characters with spaces
141 buf.writestring("$(DDOC_SECTION_H ");
142 size_t o = buf.length;
143 foreach (char c; name)
144 buf.writeByte((c == '_') ? ' ' : c);
145 escapeStrayParenthesis(loc, buf, o, false, sc.eSink);
146 buf.writestring(")");
147 }
148 else
149 {
150 buf.writestring("$(DDOC_DESCRIPTION ");
151 }
152 L1:
153 size_t o = buf.length;
154 buf.write(body_);
155 escapeStrayParenthesis(loc, buf, o, true, sc.eSink);
156 highlightText(sc, a, loc, buf, o);
157 buf.writestring(")");
158 }
159 }
160
161 /***********************************************************
162 */
163 final class ParamSection : Section
164 {
165 override void write(Loc loc, DocComment* dc, Scope* sc, Dsymbols* a, ref OutBuffer buf)
166 {
167 assert(a.length);
168 Dsymbol s = (*a)[0]; // test
169 const(char)* p = body_.ptr;
170 size_t len = body_.length;
171 const(char)* pend = p + len;
172 const(char)* tempstart = null;
173 size_t templen = 0;
174 const(char)* namestart = null;
175 size_t namelen = 0; // !=0 if line continuation
176 const(char)* textstart = null;
177 size_t textlen = 0;
178 size_t paramcount = 0;
179 buf.writestring("$(DDOC_PARAMS ");
180 while (p < pend)
181 {
182 // Skip to start of macro
183 while (1)
184 {
185 switch (*p)
186 {
187 case ' ':
188 case '\t':
189 p++;
190 continue;
191 case '\n':
192 p++;
193 goto Lcont;
194 default:
195 if (isIdStart(p) || isCVariadicArg(p[0 .. cast(size_t)(pend - p)]))
196 break;
197 if (namelen)
198 goto Ltext;
199 // continuation of prev macro
200 goto Lskipline;
201 }
202 break;
203 }
204 tempstart = p;
205 while (isIdTail(p))
206 p += utfStride(p);
207 if (isCVariadicArg(p[0 .. cast(size_t)(pend - p)]))
208 p += 3;
209 templen = p - tempstart;
210 while (*p == ' ' || *p == '\t')
211 p++;
212 if (*p != '=')
213 {
214 if (namelen)
215 goto Ltext;
216 // continuation of prev macro
217 goto Lskipline;
218 }
219 p++;
220 if (namelen)
221 {
222 // Output existing param
223 L1:
224 //printf("param '%.*s' = '%.*s'\n", cast(int)namelen, namestart, cast(int)textlen, textstart);
225 ++paramcount;
226 HdrGenState hgs;
227 buf.writestring("$(DDOC_PARAM_ROW ");
228 {
229 buf.writestring("$(DDOC_PARAM_ID ");
230 {
231 size_t o = buf.length;
232 Parameter fparam = isFunctionParameter(a, namestart[0 .. namelen]);
233 if (!fparam)
234 {
235 // Comments on a template might refer to function parameters within.
236 // Search the parameters of nested eponymous functions (with the same name.)
237 fparam = isEponymousFunctionParameter(a, namestart[0 .. namelen]);
238 }
239 bool isCVariadic = isCVariadicParameter(a, namestart[0 .. namelen]);
240 if (isCVariadic)
241 {
242 buf.writestring("...");
243 }
244 else if (fparam && fparam.type && fparam.ident)
245 {
246 toCBuffer(fparam.type, buf, fparam.ident, hgs);
247 }
248 else
249 {
250 if (isTemplateParameter(a, namestart, namelen))
251 {
252 // 10236: Don't count template parameters for params check
253 --paramcount;
254 }
255 else if (!fparam)
256 {
257 sc.eSink.warning(s.loc, "Ddoc: function declaration has no parameter '%.*s'", cast(int)namelen, namestart);
258 }
259 buf.write(namestart[0 .. namelen]);
260 }
261 escapeStrayParenthesis(loc, buf, o, true, sc.eSink);
262 highlightCode(sc, a, buf, o);
263 }
264 buf.writestring(")");
265 buf.writestring("$(DDOC_PARAM_DESC ");
266 {
267 size_t o = buf.length;
268 buf.write(textstart[0 .. textlen]);
269 escapeStrayParenthesis(loc, buf, o, true, sc.eSink);
270 highlightText(sc, a, loc, buf, o);
271 }
272 buf.writestring(")");
273 }
274 buf.writestring(")");
275 namelen = 0;
276 if (p >= pend)
277 break;
278 }
279 namestart = tempstart;
280 namelen = templen;
281 while (*p == ' ' || *p == '\t')
282 p++;
283 textstart = p;
284 Ltext:
285 while (*p != '\n')
286 p++;
287 textlen = p - textstart;
288 p++;
289 Lcont:
290 continue;
291 Lskipline:
292 // Ignore this line
293 while (*p++ != '\n')
294 {
295 }
296 }
297 if (namelen)
298 goto L1;
299 // write out last one
300 buf.writestring(")");
301 TypeFunction tf = a.length == 1 ? isTypeFunction(s) : null;
302 if (tf)
303 {
304 size_t pcount = (tf.parameterList.parameters ? tf.parameterList.parameters.length : 0) +
305 cast(int)(tf.parameterList.varargs == VarArg.variadic);
306 if (pcount != paramcount)
307 {
308 sc.eSink.warning(s.loc, "Ddoc: parameter count mismatch, expected %llu, got %llu",
309 cast(ulong) pcount, cast(ulong) paramcount);
310 if (paramcount == 0)
311 {
312 // Chances are someone messed up the format
313 sc.eSink.warningSupplemental(s.loc, "Note that the format is `param = description`");
314 }
315 }
316 }
317 }
318 }
319
320 /***********************************************************
321 */
322 final class MacroSection : Section
323 {
324 override void write(Loc loc, DocComment* dc, Scope* sc, Dsymbols* a, ref OutBuffer buf)
325 {
326 //printf("MacroSection::write()\n");
327 DocComment.parseMacros(dc.escapetable, *dc.pmacrotable, body_);
328 }
329 }
330
331 alias Sections = Array!(Section);
332
333 // Workaround for missing Parameter instance for variadic params. (it's unnecessary to instantiate one).
334 bool isCVariadicParameter(Dsymbols* a, const(char)[] p) @safe
335 {
336 foreach (member; *a)
337 {
338 TypeFunction tf = isTypeFunction(member);
339 if (tf && tf.parameterList.varargs == VarArg.variadic && p == "...")
340 return true;
341 }
342 return false;
343 }
344
345 Dsymbol getEponymousMember(TemplateDeclaration td) @safe
346 {
347 if (!td.onemember)
348 return null;
349 if (AggregateDeclaration ad = td.onemember.isAggregateDeclaration())
350 return ad;
351 if (FuncDeclaration fd = td.onemember.isFuncDeclaration())
352 return fd;
353 if (auto em = td.onemember.isEnumMember())
354 return null; // Keep backward compatibility. See compilable/ddoc9.d
355 if (VarDeclaration vd = td.onemember.isVarDeclaration())
356 return td.constraint ? null : vd;
357 return null;
358 }
359
360 TemplateDeclaration getEponymousParent(Dsymbol s) @safe
361 {
362 if (!s.parent)
363 return null;
364 TemplateDeclaration td = s.parent.isTemplateDeclaration();
365 return (td && getEponymousMember(td)) ? td : null;
366 }
367
368 immutable ddoc_default = import("default_ddoc_theme." ~ ddoc_ext);
369 immutable ddoc_decl_s = "$(DDOC_DECL ";
370 immutable ddoc_decl_e = ")\n";
371 immutable ddoc_decl_dd_s = "$(DDOC_DECL_DD ";
372 immutable ddoc_decl_dd_e = ")\n";
373
374 /****************************************************
375 * Generate Ddoc file for Module m.
376 * Params:
377 * m = Module
378 * ddoctext_ptr = combined text of .ddoc files for macro definitions
379 * ddoctext_length = extant of ddoctext_ptr
380 * datetime = charz returned by ctime()
381 * eSink = send error messages to eSink
382 * outbuf = append the Ddoc text to this
383 */
384 public
385 void gendocfile(Module m, const char* ddoctext_ptr, size_t ddoctext_length, const char* datetime, ErrorSink eSink, ref OutBuffer outbuf)
386 {
387 gendocfile(m, ddoctext_ptr[0 .. ddoctext_length], datetime, eSink, outbuf);
388 }
389
390 /****************************************************
391 * Generate Ddoc text for Module `m` and append it to `outbuf`.
392 * Params:
393 * m = Module
394 * ddoctext = combined text of .ddoc files for macro definitions
395 * datetime = charz returned by ctime()
396 * eSink = send error messages to eSink
397 * outbuf = append the Ddoc text to this
398 */
399 public
400 void gendocfile(Module m, const char[] ddoctext, const char* datetime, ErrorSink eSink, ref OutBuffer outbuf)
401 {
402 // Load internal default macros first
403 DocComment.parseMacros(m.escapetable, m.macrotable, ddoc_default[]);
404
405 // Ddoc files override default macros
406 DocComment.parseMacros(m.escapetable, m.macrotable, ddoctext);
407
408 Scope* sc = Scope.createGlobal(m, eSink); // create root scope
409 DocComment* dc = DocComment.parse(m, m.comment);
410 dc.pmacrotable = &m.macrotable;
411 dc.escapetable = m.escapetable;
412 sc.lastdc = dc;
413 // Generate predefined macros
414 // Set the title to be the name of the module
415 {
416 const p = m.toPrettyChars().toDString;
417 m.macrotable.define("TITLE", p);
418 }
419 // Set time macros
420 m.macrotable.define("DATETIME", datetime[0 .. 26]);
421 m.macrotable.define("YEAR", datetime[20 .. 20 + 4]);
422
423 const srcfilename = m.srcfile.toString();
424 m.macrotable.define("SRCFILENAME", srcfilename);
425 const docfilename = m.docfile.toString();
426 m.macrotable.define("DOCFILENAME", docfilename);
427 if (dc.copyright)
428 {
429 dc.copyright.nooutput = 1;
430 m.macrotable.define("COPYRIGHT", dc.copyright.body_);
431 }
432
433 OutBuffer buf;
434 if (m.filetype == FileType.ddoc)
435 {
436 Loc loc = m.md ? m.md.loc : m.loc;
437
438 size_t commentlen = m.comment ? strlen(cast(char*)m.comment) : 0;
439 Dsymbols a;
440 // https://issues.dlang.org/show_bug.cgi?id=9764
441 // Don't push m in a, to prevent emphasize ddoc file name.
442 if (dc.macros)
443 {
444 commentlen = dc.macros.name.ptr - m.comment;
445 dc.macros.write(loc, dc, sc, &a, buf);
446 }
447 buf.write(m.comment[0 .. commentlen]);
448 highlightText(sc, &a, loc, buf, 0);
449 }
450 else
451 {
452 Dsymbols a;
453 a.push(m);
454 dc.writeSections(sc, &a, buf);
455 emitMemberComments(m, buf, sc);
456 }
457 //printf("BODY= '%.*s'\n", cast(int)buf.length, buf.data);
458 m.macrotable.define("BODY", buf[]);
459
460 OutBuffer buf2;
461 buf2.writestring("$(DDOC)");
462 size_t end = buf2.length;
463
464 // Expand buf in place with macro expansions
465 const success = m.macrotable.expand(buf2, 0, end, null, global.recursionLimit, &isIdStart, &isIdTail);
466 if (!success)
467 eSink.error(Loc.initial, "DDoc macro expansion limit exceeded; more than %d expansions.", global.recursionLimit);
468
469 /* Remove all the escape sequences from buf,
470 * and make CR-LF the newline.
471 */
472 const slice = buf2[];
473 outbuf.reserve(slice.length);
474 auto p = slice.ptr;
475 for (size_t j = 0; j < slice.length; j++)
476 {
477 const c = p[j];
478 if (c == 0xFF && j + 1 < slice.length)
479 {
480 j++;
481 continue;
482 }
483 if (c == '\n')
484 outbuf.writeByte('\r');
485 else if (c == '\r')
486 {
487 outbuf.writestring("\r\n");
488 if (j + 1 < slice.length && p[j + 1] == '\n')
489 {
490 j++;
491 }
492 continue;
493 }
494 outbuf.writeByte(c);
495 }
496 }
497
498 /****************************************************
499 * Having unmatched parentheses can hose the output of Ddoc,
500 * as the macros depend on properly nested parentheses.
501 * This function replaces all ( with $(LPAREN) and ) with $(RPAREN)
502 * to preserve text literally. This also means macros in the
503 * text won't be expanded.
504 */
505 public
506 void escapeDdocString(ref OutBuffer buf, size_t start)
507 {
508 for (size_t u = start; u < buf.length; u++)
509 {
510 const c = buf[u];
511 switch (c)
512 {
513 case '$':
514 buf.remove(u, 1);
515 buf.insert(u, "$(DOLLAR)");
516 u += 8;
517 break;
518 case '(':
519 buf.remove(u, 1); //remove the (
520 buf.insert(u, "$(LPAREN)"); //insert this instead
521 u += 8; //skip over newly inserted macro
522 break;
523 case ')':
524 buf.remove(u, 1); //remove the )
525 buf.insert(u, "$(RPAREN)"); //insert this instead
526 u += 8; //skip over newly inserted macro
527 break;
528 default:
529 break;
530 }
531 }
532 }
533
534 /****************************************************
535 * Having unmatched parentheses can hose the output of Ddoc,
536 * as the macros depend on properly nested parentheses.
537 *
538 * Fix by replacing unmatched ( with $(LPAREN) and unmatched ) with $(RPAREN).
539 *
540 * Params:
541 * 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.
542 * buf = an OutBuffer containing the DDoc
543 * start = the index within buf to start replacing unmatched parentheses
544 * respectBackslashEscapes = if true, always replace parentheses that are
545 * directly preceeded by a backslash with $(LPAREN) or $(RPAREN) instead of
546 * counting them as stray parentheses
547 */
548 private void escapeStrayParenthesis(Loc loc, ref OutBuffer buf, size_t start, bool respectBackslashEscapes, ErrorSink eSink)
549 {
550 uint par_open = 0;
551 char inCode = 0;
552 bool atLineStart = true;
553 for (size_t u = start; u < buf.length; u++)
554 {
555 char c = buf[u];
556 switch (c)
557 {
558 case '(':
559 if (!inCode)
560 par_open++;
561 atLineStart = false;
562 break;
563 case ')':
564 if (!inCode)
565 {
566 if (par_open == 0)
567 {
568 //stray ')'
569 eSink.warning(loc, "Ddoc: Stray ')'. This may cause incorrect Ddoc output. Use $(RPAREN) instead for unpaired right parentheses.");
570 buf.remove(u, 1); //remove the )
571 buf.insert(u, "$(RPAREN)"); //insert this instead
572 u += 8; //skip over newly inserted macro
573 }
574 else
575 par_open--;
576 }
577 atLineStart = false;
578 break;
579 case '\n':
580 atLineStart = true;
581 version (none)
582 {
583 // For this to work, loc must be set to the beginning of the passed
584 // text which is currently not possible
585 // (loc is set to the Loc of the Dsymbol)
586 loc.linnum++;
587 }
588 break;
589 case ' ':
590 case '\r':
591 case '\t':
592 break;
593 case '-':
594 case '`':
595 case '~':
596 // Issue 15465: don't try to escape unbalanced parens inside code
597 // blocks.
598 int numdash = 1;
599 for (++u; u < buf.length && buf[u] == c; ++u)
600 ++numdash;
601 --u;
602 if (c == '`' || (atLineStart && numdash >= 3))
603 {
604 if (inCode == c)
605 inCode = 0;
606 else if (!inCode)
607 inCode = c;
608 }
609 atLineStart = false;
610 break;
611 case '\\':
612 // replace backslash-escaped parens with their macros
613 if (!inCode && respectBackslashEscapes && u+1 < buf.length)
614 {
615 if (buf[u+1] == '(' || buf[u+1] == ')')
616 {
617 const paren = buf[u+1] == '(' ? "$(LPAREN)" : "$(RPAREN)";
618 buf.remove(u, 2); //remove the \)
619 buf.insert(u, paren); //insert this instead
620 u += 8; //skip over newly inserted macro
621 }
622 else if (buf[u+1] == '\\')
623 ++u;
624 }
625 break;
626 default:
627 atLineStart = false;
628 break;
629 }
630 }
631 if (par_open) // if any unmatched lparens
632 {
633 par_open = 0;
634 for (size_t u = buf.length; u > start;)
635 {
636 u--;
637 const c = buf[u];
638 switch (c)
639 {
640 case ')':
641 par_open++;
642 break;
643 case '(':
644 if (par_open == 0)
645 {
646 //stray '('
647 eSink.warning(loc, "Ddoc: Stray '('. This may cause incorrect Ddoc output. Use $(LPAREN) instead for unpaired left parentheses.");
648 buf.remove(u, 1); //remove the (
649 buf.insert(u, "$(LPAREN)"); //insert this instead
650 }
651 else
652 par_open--;
653 break;
654 default:
655 break;
656 }
657 }
658 }
659 }
660
661 // Basically, this is to skip over things like private{} blocks in a struct or
662 // class definition that don't add any components to the qualified name.
663 Scope* skipNonQualScopes(Scope* sc) @safe
664 {
665 while (sc && !sc.scopesym)
666 sc = sc.enclosing;
667 return sc;
668 }
669
670 bool emitAnchorName(ref OutBuffer buf, Dsymbol s, Scope* sc, bool includeParent)
671 {
672 if (!s || s.isPackage() || s.isModule())
673 return false;
674 // Add parent names first
675 bool dot = false;
676 auto eponymousParent = getEponymousParent(s);
677 if (includeParent && s.parent || eponymousParent)
678 dot = emitAnchorName(buf, s.parent, sc, includeParent);
679 else if (includeParent && sc)
680 dot = emitAnchorName(buf, sc.scopesym, skipNonQualScopes(sc.enclosing), includeParent);
681 // Eponymous template members can share the parent anchor name
682 if (eponymousParent)
683 return dot;
684 if (dot)
685 buf.writeByte('.');
686 // Use "this" not "__ctor"
687 TemplateDeclaration td;
688 if (s.isCtorDeclaration() || ((td = s.isTemplateDeclaration()) !is null && td.onemember && td.onemember.isCtorDeclaration()))
689 {
690 buf.writestring("this");
691 }
692 else
693 {
694 buf.writestring(s.ident ? s.ident.toString : "__anonymous");
695 }
696 return true;
697 }
698
699 void emitAnchor(ref OutBuffer buf, Dsymbol s, Scope* sc, bool forHeader = false)
700 {
701 Identifier ident;
702 {
703 OutBuffer anc;
704 emitAnchorName(anc, s, skipNonQualScopes(sc), true);
705 ident = Identifier.idPool(anc[]);
706 }
707
708 auto pcount = cast(void*)ident in sc.anchorCounts;
709 typeof(*pcount) count;
710 if (!forHeader)
711 {
712 if (pcount)
713 {
714 // Existing anchor,
715 // don't write an anchor for matching consecutive ditto symbols
716 TemplateDeclaration td = getEponymousParent(s);
717 if (sc.prevAnchor == ident && sc.lastdc && (isDitto(s.comment) || (td && isDitto(td.comment))))
718 return;
719
720 count = ++*pcount;
721 }
722 else
723 {
724 sc.anchorCounts[cast(void*)ident] = 1;
725 count = 1;
726 }
727 }
728
729 // cache anchor name
730 sc.prevAnchor = ident;
731 auto macroName = forHeader ? "DDOC_HEADER_ANCHOR" : "DDOC_ANCHOR";
732
733 if (auto imp = s.isImport())
734 {
735 // For example: `public import core.stdc.string : memcpy, memcmp;`
736 if (imp.aliases.length > 0)
737 {
738 for(int i = 0; i < imp.aliases.length; i++)
739 {
740 // Need to distinguish between
741 // `public import core.stdc.string : memcpy, memcmp;` and
742 // `public import core.stdc.string : copy = memcpy, compare = memcmp;`
743 auto a = imp.aliases[i];
744 auto id = a ? a : imp.names[i];
745 auto loc = Loc.init;
746 Dsymbol pscopesym;
747 if (auto symFromId = sc.search(loc, id, pscopesym))
748 {
749 emitAnchor(buf, symFromId, sc, forHeader);
750 }
751 }
752 }
753 else
754 {
755 // For example: `public import str = core.stdc.string;`
756 if (imp.aliasId)
757 {
758 auto symbolName = imp.aliasId.toString();
759
760 buf.printf("$(%.*s %.*s", cast(int) macroName.length, macroName.ptr,
761 cast(int) symbolName.length, symbolName.ptr);
762
763 if (forHeader)
764 {
765 buf.printf(", %.*s", cast(int) symbolName.length, symbolName.ptr);
766 }
767 }
768 else
769 {
770 // The general case: `public import core.stdc.string;`
771
772 // fully qualify imports so `core.stdc.string` doesn't appear as `core`
773 void printFullyQualifiedImport()
774 {
775 foreach (const pid; imp.packages)
776 {
777 buf.printf("%s.", pid.toChars());
778 }
779 buf.writestring(imp.id.toString());
780 }
781
782 buf.printf("$(%.*s ", cast(int) macroName.length, macroName.ptr);
783 printFullyQualifiedImport();
784
785 if (forHeader)
786 {
787 buf.printf(", ");
788 printFullyQualifiedImport();
789 }
790 }
791
792 buf.writeByte(')');
793 }
794 }
795 else
796 {
797 // buf.writestring("<<<");
798 // buf.writestring(typeof(ident).stringof);
799 // buf.writestring(">>>");
800 // auto symbolName = ident.toString();
801 auto symbolName = ident.toChars().toDString();
802 buf.printf("$(%.*s %.*s", cast(int) macroName.length, macroName.ptr,
803 cast(int) symbolName.length, symbolName.ptr);
804
805 // only append count once there's a duplicate
806 if (count > 1)
807 buf.printf(".%u", count);
808
809 if (forHeader)
810 {
811 Identifier shortIdent;
812 {
813 OutBuffer anc;
814 emitAnchorName(anc, s, skipNonQualScopes(sc), false);
815 shortIdent = Identifier.idPool(anc[]);
816 }
817
818 auto shortName = shortIdent.toString();
819 buf.printf(", %.*s", cast(int) shortName.length, shortName.ptr);
820 }
821
822 buf.writeByte(')');
823 }
824 }
825
826 /******************************* emitComment **********************************/
827
828 /** Get leading indentation from 'src' which represents lines of code. */
829 size_t getCodeIndent(const(char)* src)
830 {
831 while (src && (*src == '\r' || *src == '\n'))
832 ++src; // skip until we find the first non-empty line
833 size_t codeIndent = 0;
834 while (src && (*src == ' ' || *src == '\t'))
835 {
836 codeIndent++;
837 src++;
838 }
839 return codeIndent;
840 }
841
842 /** Recursively expand template mixin member docs into the scope. */
843 void expandTemplateMixinComments(TemplateMixin tm, ref OutBuffer buf, Scope* sc)
844 {
845 if (!tm.semanticRun)
846 tm.dsymbolSemantic(sc);
847 TemplateDeclaration td = (tm && tm.tempdecl) ? tm.tempdecl.isTemplateDeclaration() : null;
848 if (td && td.members)
849 {
850 for (size_t i = 0; i < td.members.length; i++)
851 {
852 Dsymbol sm = (*td.members)[i];
853 TemplateMixin tmc = sm.isTemplateMixin();
854 if (tmc && tmc.comment)
855 expandTemplateMixinComments(tmc, buf, sc);
856 else
857 emitComment(sm, buf, sc);
858 }
859 }
860 }
861
862 void emitMemberComments(ScopeDsymbol sds, ref OutBuffer buf, Scope* sc)
863 {
864 if (!sds.members)
865 return;
866 //printf("ScopeDsymbol::emitMemberComments() %s\n", toChars());
867 const(char)[] m = "$(DDOC_MEMBERS ";
868 if (sds.isTemplateDeclaration())
869 m = "$(DDOC_TEMPLATE_MEMBERS ";
870 else if (sds.isClassDeclaration())
871 m = "$(DDOC_CLASS_MEMBERS ";
872 else if (sds.isStructDeclaration())
873 m = "$(DDOC_STRUCT_MEMBERS ";
874 else if (sds.isEnumDeclaration())
875 m = "$(DDOC_ENUM_MEMBERS ";
876 else if (sds.isModule())
877 m = "$(DDOC_MODULE_MEMBERS ";
878 size_t offset1 = buf.length; // save starting offset
879 buf.writestring(m);
880 size_t offset2 = buf.length; // to see if we write anything
881 sc = sc.push(sds);
882 for (size_t i = 0; i < sds.members.length; i++)
883 {
884 Dsymbol s = (*sds.members)[i];
885 //printf("\ts = '%s'\n", s.toChars());
886 // only expand if parent is a non-template (semantic won't work)
887 if (s.comment && s.isTemplateMixin() && s.parent && !s.parent.isTemplateDeclaration())
888 expandTemplateMixinComments(cast(TemplateMixin)s, buf, sc);
889 emitComment(s, buf, sc);
890 }
891 emitComment(null, buf, sc);
892 sc.pop();
893 if (buf.length == offset2)
894 {
895 /* Didn't write out any members, so back out last write
896 */
897 buf.setsize(offset1);
898 }
899 else
900 buf.writestring(")");
901 }
902
903 void emitVisibility(ref OutBuffer buf, Import i)
904 {
905 // imports are private by default, which is different from other declarations
906 // so they should explicitly show their visibility
907 emitVisibility(buf, i.visibility);
908 }
909
910 void emitVisibility(ref OutBuffer buf, Declaration d)
911 {
912 auto vis = d.visibility;
913 if (vis.kind != Visibility.Kind.undefined && vis.kind != Visibility.Kind.public_)
914 {
915 emitVisibility(buf, vis);
916 }
917 }
918
919 void emitVisibility(ref OutBuffer buf, Visibility vis)
920 {
921 visibilityToBuffer(buf, vis);
922 buf.writeByte(' ');
923 }
924
925 void emitComment(Dsymbol s, ref OutBuffer buf, Scope* sc)
926 {
927 extern (C++) final class EmitComment : Visitor
928 {
929 alias visit = Visitor.visit;
930 public:
931 OutBuffer* buf;
932 Scope* sc;
933
934 extern (D) this(ref OutBuffer buf, Scope* sc) scope
935 {
936 this.buf = &buf;
937 this.sc = sc;
938 }
939
940 override void visit(Dsymbol)
941 {
942 }
943
944 override void visit(InvariantDeclaration)
945 {
946 }
947
948 override void visit(UnitTestDeclaration)
949 {
950 }
951
952 override void visit(PostBlitDeclaration)
953 {
954 }
955
956 override void visit(DtorDeclaration)
957 {
958 }
959
960 override void visit(StaticCtorDeclaration)
961 {
962 }
963
964 override void visit(StaticDtorDeclaration)
965 {
966 }
967
968 override void visit(TypeInfoDeclaration)
969 {
970 }
971
972 void emit(Scope* sc, Dsymbol s, const(char)* com)
973 {
974 if (s && sc.lastdc && isDitto(com))
975 {
976 sc.lastdc.a.push(s);
977 return;
978 }
979 // Put previous doc comment if exists
980 if (DocComment* dc = sc.lastdc)
981 {
982 assert(dc.a.length > 0, "Expects at least one declaration for a" ~
983 "documentation comment");
984
985 auto symbol = dc.a[0];
986
987 buf.writestring("$(DDOC_MEMBER");
988 buf.writestring("$(DDOC_MEMBER_HEADER");
989 emitAnchor(*buf, symbol, sc, true);
990 buf.writeByte(')');
991
992 // Put the declaration signatures as the document 'title'
993 buf.writestring(ddoc_decl_s);
994 for (size_t i = 0; i < dc.a.length; i++)
995 {
996 Dsymbol sx = dc.a[i];
997 // the added linebreaks in here make looking at multiple
998 // signatures more appealing
999 if (i == 0)
1000 {
1001 size_t o = buf.length;
1002 toDocBuffer(sx, *buf, sc);
1003 highlightCode(sc, sx, *buf, o);
1004 buf.writestring("$(DDOC_OVERLOAD_SEPARATOR)");
1005 continue;
1006 }
1007 buf.writestring("$(DDOC_DITTO ");
1008 {
1009 size_t o = buf.length;
1010 toDocBuffer(sx, *buf, sc);
1011 highlightCode(sc, sx, *buf, o);
1012 }
1013 buf.writestring("$(DDOC_OVERLOAD_SEPARATOR)");
1014 buf.writeByte(')');
1015 }
1016 buf.writestring(ddoc_decl_e);
1017 // Put the ddoc comment as the document 'description'
1018 buf.writestring(ddoc_decl_dd_s);
1019 {
1020 dc.writeSections(sc, &dc.a, *buf);
1021 if (ScopeDsymbol sds = dc.a[0].isScopeDsymbol())
1022 emitMemberComments(sds, *buf, sc);
1023 }
1024 buf.writestring(ddoc_decl_dd_e);
1025 buf.writeByte(')');
1026 //printf("buf.2 = [[%.*s]]\n", cast(int)(buf.length - o0), buf.data + o0);
1027 }
1028 if (s)
1029 {
1030 DocComment* dc = DocComment.parse(s, com);
1031 dc.pmacrotable = &sc._module.macrotable;
1032 sc.lastdc = dc;
1033 }
1034 }
1035
1036 override void visit(Import imp)
1037 {
1038 if (imp.visible().kind != Visibility.Kind.public_ && sc.visibility.kind != Visibility.Kind.export_)
1039 return;
1040
1041 if (imp.comment)
1042 emit(sc, imp, imp.comment);
1043 }
1044
1045 override void visit(Declaration d)
1046 {
1047 //printf("Declaration::emitComment(%p '%s'), comment = '%s'\n", d, d.toChars(), d.comment);
1048 //printf("type = %p\n", d.type);
1049 const(char)* com = d.comment;
1050 if (TemplateDeclaration td = getEponymousParent(d))
1051 {
1052 if (isDitto(td.comment))
1053 com = td.comment;
1054 else
1055 com = Lexer.combineComments(td.comment.toDString(), com.toDString(), true);
1056 }
1057 else
1058 {
1059 if (!d.ident)
1060 return;
1061 if (!d.type)
1062 {
1063 if (!d.isCtorDeclaration() &&
1064 !d.isAliasDeclaration() &&
1065 !d.isVarDeclaration())
1066 {
1067 return;
1068 }
1069 }
1070 if (d.visibility.kind == Visibility.Kind.private_ || sc.visibility.kind == Visibility.Kind.private_)
1071 return;
1072 }
1073 if (!com)
1074 return;
1075 emit(sc, d, com);
1076 }
1077
1078 override void visit(AggregateDeclaration ad)
1079 {
1080 //printf("AggregateDeclaration::emitComment() '%s'\n", ad.toChars());
1081 const(char)* com = ad.comment;
1082 if (TemplateDeclaration td = getEponymousParent(ad))
1083 {
1084 if (isDitto(td.comment))
1085 com = td.comment;
1086 else
1087 com = Lexer.combineComments(td.comment.toDString(), com.toDString(), true);
1088 }
1089 else
1090 {
1091 if (ad.visible().kind == Visibility.Kind.private_ || sc.visibility.kind == Visibility.Kind.private_)
1092 return;
1093 if (!ad.comment)
1094 return;
1095 }
1096 if (!com)
1097 return;
1098 emit(sc, ad, com);
1099 }
1100
1101 override void visit(TemplateDeclaration td)
1102 {
1103 //printf("TemplateDeclaration::emitComment() '%s', kind = %s\n", td.toChars(), td.kind());
1104 if (td.visible().kind == Visibility.Kind.private_ || sc.visibility.kind == Visibility.Kind.private_)
1105 return;
1106 if (!td.comment)
1107 return;
1108 if (Dsymbol ss = getEponymousMember(td))
1109 {
1110 ss.accept(this);
1111 return;
1112 }
1113 emit(sc, td, td.comment);
1114 }
1115
1116 override void visit(EnumDeclaration ed)
1117 {
1118 if (ed.visible().kind == Visibility.Kind.private_ || sc.visibility.kind == Visibility.Kind.private_)
1119 return;
1120 if (ed.isAnonymous() && ed.members)
1121 {
1122 for (size_t i = 0; i < ed.members.length; i++)
1123 {
1124 Dsymbol s = (*ed.members)[i];
1125 emitComment(s, *buf, sc);
1126 }
1127 return;
1128 }
1129 if (!ed.comment)
1130 return;
1131 if (ed.isAnonymous())
1132 return;
1133 emit(sc, ed, ed.comment);
1134 }
1135
1136 override void visit(EnumMember em)
1137 {
1138 //printf("EnumMember::emitComment(%p '%s'), comment = '%s'\n", em, em.toChars(), em.comment);
1139 if (em.visible().kind == Visibility.Kind.private_ || sc.visibility.kind == Visibility.Kind.private_)
1140 return;
1141 if (!em.comment)
1142 return;
1143 emit(sc, em, em.comment);
1144 }
1145
1146 override void visit(AttribDeclaration ad)
1147 {
1148 //printf("AttribDeclaration::emitComment(sc = %p)\n", sc);
1149 /* A general problem with this,
1150 * illustrated by https://issues.dlang.org/show_bug.cgi?id=2516
1151 * is that attributes are not transmitted through to the underlying
1152 * member declarations for template bodies, because semantic analysis
1153 * is not done for template declaration bodies
1154 * (only template instantiations).
1155 * Hence, Ddoc omits attributes from template members.
1156 */
1157 Dsymbols* d = ad.include(null);
1158 if (d)
1159 {
1160 for (size_t i = 0; i < d.length; i++)
1161 {
1162 Dsymbol s = (*d)[i];
1163 //printf("AttribDeclaration::emitComment %s\n", s.toChars());
1164 emitComment(s, *buf, sc);
1165 }
1166 }
1167 }
1168
1169 override void visit(VisibilityDeclaration pd)
1170 {
1171 if (pd.decl)
1172 {
1173 Scope* scx = sc;
1174 sc = sc.copy();
1175 sc.visibility = pd.visibility;
1176 visit(cast(AttribDeclaration)pd);
1177 scx.lastdc = sc.lastdc;
1178 sc = sc.pop();
1179 }
1180 }
1181
1182 override void visit(ConditionalDeclaration cd)
1183 {
1184 //printf("ConditionalDeclaration::emitComment(sc = %p)\n", sc);
1185 if (cd.condition.inc != Include.notComputed)
1186 {
1187 visit(cast(AttribDeclaration)cd);
1188 return;
1189 }
1190 /* If generating doc comment, be careful because if we're inside
1191 * a template, then include(null) will fail.
1192 */
1193 Dsymbols* d = cd.decl ? cd.decl : cd.elsedecl;
1194 for (size_t i = 0; i < d.length; i++)
1195 {
1196 Dsymbol s = (*d)[i];
1197 emitComment(s, *buf, sc);
1198 }
1199 }
1200 }
1201
1202 scope EmitComment v = new EmitComment(buf, sc);
1203 if (!s)
1204 v.emit(sc, null, null);
1205 else
1206 s.accept(v);
1207 }
1208
1209 void toDocBuffer(Dsymbol s, ref OutBuffer buf, Scope* sc)
1210 {
1211 extern (C++) final class ToDocBuffer : Visitor
1212 {
1213 alias visit = Visitor.visit;
1214 public:
1215 OutBuffer* buf;
1216 Scope* sc;
1217
1218 extern (D) this(ref OutBuffer buf, Scope* sc) scope
1219 {
1220 this.buf = &buf;
1221 this.sc = sc;
1222 }
1223
1224 override void visit(Dsymbol s)
1225 {
1226 //printf("Dsymbol::toDocbuffer() %s\n", s.toChars());
1227 HdrGenState hgs;
1228 hgs.ddoc = true;
1229 toCBuffer(s, *buf, hgs);
1230 }
1231
1232 void prefix(Dsymbol s)
1233 {
1234 if (s.isDeprecated())
1235 buf.writestring("deprecated ");
1236 if (Declaration d = s.isDeclaration())
1237 {
1238 emitVisibility(*buf, d);
1239 if (d.isStatic())
1240 buf.writestring("static ");
1241 else if (d.isFinal())
1242 buf.writestring("final ");
1243 else if (d.isAbstract())
1244 buf.writestring("abstract ");
1245
1246 if (d.isFuncDeclaration()) // functionToBufferFull handles this
1247 return;
1248
1249 if (d.isImmutable())
1250 buf.writestring("immutable ");
1251 if (d.storage_class & STC.shared_)
1252 buf.writestring("shared ");
1253 if (d.isWild())
1254 buf.writestring("inout ");
1255 if (d.isConst())
1256 buf.writestring("const ");
1257
1258 if (d.isSynchronized())
1259 buf.writestring("synchronized ");
1260
1261 if (d.storage_class & STC.manifest)
1262 buf.writestring("enum ");
1263
1264 // Add "auto" for the untyped variable in template members
1265 if (!d.type && d.isVarDeclaration() &&
1266 !d.isImmutable() && !(d.storage_class & STC.shared_) && !d.isWild() && !d.isConst() &&
1267 !d.isSynchronized())
1268 {
1269 buf.writestring("auto ");
1270 }
1271 }
1272 }
1273
1274 override void visit(Import i)
1275 {
1276 HdrGenState hgs;
1277 hgs.ddoc = true;
1278 emitVisibility(*buf, i);
1279 toCBuffer(i, *buf, hgs);
1280 }
1281
1282 override void visit(Declaration d)
1283 {
1284 if (!d.ident)
1285 return;
1286 TemplateDeclaration td = getEponymousParent(d);
1287 //printf("Declaration::toDocbuffer() %s, originalType = %s, td = %s\n", d.toChars(), d.originalType ? d.originalType.toChars() : "--", td ? td.toChars() : "--");
1288 HdrGenState hgs;
1289 hgs.ddoc = true;
1290 if (d.isDeprecated())
1291 buf.writestring("$(DEPRECATED ");
1292 prefix(d);
1293 if (d.type)
1294 {
1295 Type origType = d.originalType ? d.originalType : d.type;
1296 if (origType.ty == Tfunction)
1297 {
1298 functionToBufferFull(cast(TypeFunction)origType, *buf, d.ident, hgs, td);
1299 }
1300 else
1301 toCBuffer(origType, *buf, d.ident, hgs);
1302 }
1303 else
1304 buf.writestring(d.ident.toString());
1305 if (d.isVarDeclaration() && td)
1306 {
1307 buf.writeByte('(');
1308 if (td.origParameters && td.origParameters.length)
1309 {
1310 for (size_t i = 0; i < td.origParameters.length; i++)
1311 {
1312 if (i)
1313 buf.writestring(", ");
1314 toCBuffer((*td.origParameters)[i], *buf, hgs);
1315 }
1316 }
1317 buf.writeByte(')');
1318 }
1319 // emit constraints if declaration is a templated declaration
1320 if (td && td.constraint)
1321 {
1322 bool noFuncDecl = td.isFuncDeclaration() is null;
1323 if (noFuncDecl)
1324 {
1325 buf.writestring("$(DDOC_CONSTRAINT ");
1326 }
1327
1328 toCBuffer(td.constraint, *buf, hgs);
1329
1330 if (noFuncDecl)
1331 {
1332 buf.writestring(")");
1333 }
1334 }
1335 if (d.isDeprecated())
1336 buf.writestring(")");
1337 buf.writestring(";\n");
1338 }
1339
1340 override void visit(AliasDeclaration ad)
1341 {
1342 //printf("AliasDeclaration::toDocbuffer() %s\n", ad.toChars());
1343 if (!ad.ident)
1344 return;
1345 if (ad.isDeprecated())
1346 buf.writestring("deprecated ");
1347 emitVisibility(*buf, ad);
1348 buf.printf("alias %s = ", ad.toChars());
1349 if (Dsymbol s = ad.aliassym) // ident alias
1350 {
1351 prettyPrintDsymbol(s, ad.parent);
1352 }
1353 else if (Type type = ad.getType()) // type alias
1354 {
1355 if (type.ty == Tclass || type.ty == Tstruct || type.ty == Tenum)
1356 {
1357 import dmd.typesem : toDsymbol;
1358 if (Dsymbol s = type.toDsymbol(null)) // elaborate type
1359 prettyPrintDsymbol(s, ad.parent);
1360 else
1361 buf.writestring(type.toChars());
1362 }
1363 else
1364 {
1365 // simple type
1366 buf.writestring(type.toChars());
1367 }
1368 }
1369 buf.writestring(";\n");
1370 }
1371
1372 void parentToBuffer(Dsymbol s)
1373 {
1374 if (s && !s.isPackage() && !s.isModule())
1375 {
1376 parentToBuffer(s.parent);
1377 buf.writestring(s.toChars());
1378 buf.writestring(".");
1379 }
1380 }
1381
1382 static bool inSameModule(Dsymbol s, Dsymbol p) @safe
1383 {
1384 for (; s; s = s.parent)
1385 {
1386 if (s.isModule())
1387 break;
1388 }
1389 for (; p; p = p.parent)
1390 {
1391 if (p.isModule())
1392 break;
1393 }
1394 return s == p;
1395 }
1396
1397 void prettyPrintDsymbol(Dsymbol s, Dsymbol parent)
1398 {
1399 if (s.parent && (s.parent == parent)) // in current scope -> naked name
1400 {
1401 buf.writestring(s.toChars());
1402 }
1403 else if (!inSameModule(s, parent)) // in another module -> full name
1404 {
1405 buf.writestring(s.toPrettyChars());
1406 }
1407 else // nested in a type in this module -> full name w/o module name
1408 {
1409 // if alias is nested in a user-type use module-scope lookup
1410 if (!parent.isModule() && !parent.isPackage())
1411 buf.writestring(".");
1412 parentToBuffer(s.parent);
1413 buf.writestring(s.toChars());
1414 }
1415 }
1416
1417 override void visit(AggregateDeclaration ad)
1418 {
1419 if (!ad.ident)
1420 return;
1421 version (none)
1422 {
1423 emitVisibility(buf, ad);
1424 }
1425 buf.printf("%s %s", ad.kind(), ad.toChars());
1426 buf.writestring(";\n");
1427 }
1428
1429 override void visit(StructDeclaration sd)
1430 {
1431 //printf("StructDeclaration::toDocbuffer() %s\n", sd.toChars());
1432 if (!sd.ident)
1433 return;
1434 version (none)
1435 {
1436 emitVisibility(buf, sd);
1437 }
1438 if (TemplateDeclaration td = getEponymousParent(sd))
1439 {
1440 toDocBuffer(td, *buf, sc);
1441 }
1442 else
1443 {
1444 buf.printf("%s %s", sd.kind(), sd.toChars());
1445 }
1446 buf.writestring(";\n");
1447 }
1448
1449 override void visit(ClassDeclaration cd)
1450 {
1451 //printf("ClassDeclaration::toDocbuffer() %s\n", cd.toChars());
1452 if (!cd.ident)
1453 return;
1454 version (none)
1455 {
1456 emitVisibility(*buf, cd);
1457 }
1458 if (TemplateDeclaration td = getEponymousParent(cd))
1459 {
1460 toDocBuffer(td, *buf, sc);
1461 }
1462 else
1463 {
1464 if (!cd.isInterfaceDeclaration() && cd.isAbstract())
1465 buf.writestring("abstract ");
1466 buf.printf("%s %s", cd.kind(), cd.toChars());
1467 }
1468 int any = 0;
1469 for (size_t i = 0; i < cd.baseclasses.length; i++)
1470 {
1471 BaseClass* bc = (*cd.baseclasses)[i];
1472 if (bc.sym && bc.sym.ident == Id.Object)
1473 continue;
1474 if (any)
1475 buf.writestring(", ");
1476 else
1477 {
1478 buf.writestring(": ");
1479 any = 1;
1480 }
1481
1482 if (bc.sym)
1483 {
1484 buf.printf("$(DDOC_PSUPER_SYMBOL %s)", bc.sym.toPrettyChars());
1485 }
1486 else
1487 {
1488 HdrGenState hgs;
1489 toCBuffer(bc.type, *buf, null, hgs);
1490 }
1491 }
1492 buf.writestring(";\n");
1493 }
1494
1495 override void visit(EnumDeclaration ed)
1496 {
1497 if (!ed.ident)
1498 return;
1499 buf.printf("%s %s", ed.kind(), ed.toChars());
1500 if (ed.memtype)
1501 {
1502 buf.writestring(": $(DDOC_ENUM_BASETYPE ");
1503 HdrGenState hgs;
1504 toCBuffer(ed.memtype, *buf, null, hgs);
1505 buf.writestring(")");
1506 }
1507 buf.writestring(";\n");
1508 }
1509
1510 override void visit(EnumMember em)
1511 {
1512 if (!em.ident)
1513 return;
1514 buf.writestring(em.toChars());
1515 }
1516 }
1517
1518 scope ToDocBuffer v = new ToDocBuffer(buf, sc);
1519 s.accept(v);
1520 }
1521
1522 /***********************************************************
1523 */
1524 public
1525 struct DocComment
1526 {
1527 Sections sections; // Section*[]
1528 Section summary;
1529 Section copyright;
1530 Section macros;
1531 MacroTable* pmacrotable;
1532 Escape* escapetable;
1533 Dsymbols a;
1534
1535 static DocComment* parse(Dsymbol s, const(char)* comment)
1536 {
1537 //printf("parse(%s): '%s'\n", s.toChars(), comment);
1538 auto dc = new DocComment();
1539 dc.a.push(s);
1540 if (!comment)
1541 return dc;
1542 dc.parseSections(comment);
1543 for (size_t i = 0; i < dc.sections.length; i++)
1544 {
1545 Section sec = dc.sections[i];
1546 if (iequals("copyright", sec.name))
1547 {
1548 dc.copyright = sec;
1549 }
1550 if (iequals("macros", sec.name))
1551 {
1552 dc.macros = sec;
1553 }
1554 }
1555 return dc;
1556 }
1557
1558 /************************************************
1559 * Parse macros out of Macros: section.
1560 * Macros are of the form:
1561 * name1 = value1
1562 *
1563 * name2 = value2
1564 */
1565 extern(D) static void parseMacros(
1566 Escape* escapetable, ref MacroTable pmacrotable, const(char)[] m)
1567 {
1568 const(char)* p = m.ptr;
1569 size_t len = m.length;
1570 const(char)* pend = p + len;
1571 const(char)* tempstart = null;
1572 size_t templen = 0;
1573 const(char)* namestart = null;
1574 size_t namelen = 0; // !=0 if line continuation
1575 const(char)* textstart = null;
1576 size_t textlen = 0;
1577 while (p < pend)
1578 {
1579 // Skip to start of macro
1580 while (1)
1581 {
1582 if (p >= pend)
1583 goto Ldone;
1584 switch (*p)
1585 {
1586 case ' ':
1587 case '\t':
1588 p++;
1589 continue;
1590 case '\r':
1591 case '\n':
1592 p++;
1593 goto Lcont;
1594 default:
1595 if (isIdStart(p))
1596 break;
1597 if (namelen)
1598 goto Ltext; // continuation of prev macro
1599 goto Lskipline;
1600 }
1601 break;
1602 }
1603 tempstart = p;
1604 while (1)
1605 {
1606 if (p >= pend)
1607 goto Ldone;
1608 if (!isIdTail(p))
1609 break;
1610 p += utfStride(p);
1611 }
1612 templen = p - tempstart;
1613 while (1)
1614 {
1615 if (p >= pend)
1616 goto Ldone;
1617 if (!(*p == ' ' || *p == '\t'))
1618 break;
1619 p++;
1620 }
1621 if (*p != '=')
1622 {
1623 if (namelen)
1624 goto Ltext; // continuation of prev macro
1625 goto Lskipline;
1626 }
1627 p++;
1628 if (p >= pend)
1629 goto Ldone;
1630 if (namelen)
1631 {
1632 // Output existing macro
1633 L1:
1634 //printf("macro '%.*s' = '%.*s'\n", cast(int)namelen, namestart, cast(int)textlen, textstart);
1635 if (iequals("ESCAPES", namestart[0 .. namelen]))
1636 parseEscapes(escapetable, textstart[0 .. textlen]);
1637 else
1638 pmacrotable.define(namestart[0 .. namelen], textstart[0 .. textlen]);
1639 namelen = 0;
1640 if (p >= pend)
1641 break;
1642 }
1643 namestart = tempstart;
1644 namelen = templen;
1645 while (p < pend && (*p == ' ' || *p == '\t'))
1646 p++;
1647 textstart = p;
1648 Ltext:
1649 while (p < pend && *p != '\r' && *p != '\n')
1650 p++;
1651 textlen = p - textstart;
1652 p++;
1653 //printf("p = %p, pend = %p\n", p, pend);
1654 Lcont:
1655 continue;
1656 Lskipline:
1657 // Ignore this line
1658 while (p < pend && *p != '\r' && *p != '\n')
1659 p++;
1660 }
1661 Ldone:
1662 if (namelen)
1663 goto L1; // write out last one
1664 }
1665
1666 /**************************************
1667 * Parse escapes of the form:
1668 * /c/string/
1669 * where c is a single character.
1670 * Multiple escapes can be separated
1671 * by whitespace and/or commas.
1672 */
1673 static void parseEscapes(Escape* escapetable, const(char)[] text)
1674 {
1675 if (!escapetable)
1676 {
1677 escapetable = new Escape();
1678 memset(escapetable, 0, Escape.sizeof);
1679 }
1680 //printf("parseEscapes('%.*s') pescapetable = %p\n", cast(int)text.length, text.ptr, escapetable);
1681 const(char)* p = text.ptr;
1682 const(char)* pend = p + text.length;
1683 while (1)
1684 {
1685 while (1)
1686 {
1687 if (p + 4 >= pend)
1688 return;
1689 if (!(*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n' || *p == ','))
1690 break;
1691 p++;
1692 }
1693 if (p[0] != '/' || p[2] != '/')
1694 return;
1695 char c = p[1];
1696 p += 3;
1697 const(char)* start = p;
1698 while (1)
1699 {
1700 if (p >= pend)
1701 return;
1702 if (*p == '/')
1703 break;
1704 p++;
1705 }
1706 size_t len = p - start;
1707 char* s = cast(char*)memcpy(mem.xmalloc(len + 1), start, len);
1708 s[len] = 0;
1709 escapetable.strings[c] = s[0 .. len];
1710 //printf("\t%c = '%s'\n", c, s);
1711 p++;
1712 }
1713 }
1714
1715 /*****************************************
1716 * Parse next paragraph out of *pcomment.
1717 * Update *pcomment to point past paragraph.
1718 * Returns NULL if no more paragraphs.
1719 * If paragraph ends in 'identifier:',
1720 * then (*pcomment)[0 .. idlen] is the identifier.
1721 */
1722 void parseSections(const(char)* comment)
1723 {
1724 const(char)* p;
1725 const(char)* pstart;
1726 const(char)* pend;
1727 const(char)* idstart = null; // dead-store to prevent spurious warning
1728 size_t idlen;
1729 const(char)* name = null;
1730 size_t namelen = 0;
1731 //printf("parseSections('%s')\n", comment);
1732 p = comment;
1733 while (*p)
1734 {
1735 const(char)* pstart0 = p;
1736 p = skipwhitespace(p);
1737 pstart = p;
1738 pend = p;
1739
1740 // Undo indent if starting with a list item
1741 if ((*p == '-' || *p == '+' || *p == '*') && (*(p+1) == ' ' || *(p+1) == '\t'))
1742 pstart = pstart0;
1743 else
1744 {
1745 const(char)* pitem = p;
1746 while (*pitem >= '0' && *pitem <= '9')
1747 ++pitem;
1748 if (pitem > p && *pitem == '.' && (*(pitem+1) == ' ' || *(pitem+1) == '\t'))
1749 pstart = pstart0;
1750 }
1751
1752 /* Find end of section, which is ended by one of:
1753 * 'identifier:' (but not inside a code section)
1754 * '\0'
1755 */
1756 idlen = 0;
1757 int inCode = 0;
1758 while (1)
1759 {
1760 // Check for start/end of a code section
1761 if (*p == '-' || *p == '`' || *p == '~')
1762 {
1763 char c = *p;
1764 int numdash = 0;
1765 while (*p == c)
1766 {
1767 ++numdash;
1768 p++;
1769 }
1770 // BUG: handle UTF PS and LS too
1771 if ((!*p || *p == '\r' || *p == '\n' || (!inCode && c != '-')) && numdash >= 3)
1772 {
1773 inCode = inCode == c ? false : c;
1774 if (inCode)
1775 {
1776 // restore leading indentation
1777 while (pstart0 < pstart && isIndentWS(pstart - 1))
1778 --pstart;
1779 }
1780 }
1781 pend = p;
1782 }
1783 if (!inCode && isIdStart(p))
1784 {
1785 const(char)* q = p + utfStride(p);
1786 while (isIdTail(q))
1787 q += utfStride(q);
1788
1789 // Detected tag ends it
1790 if (*q == ':' && isupper(*p)
1791 && (isspace(q[1]) || q[1] == 0))
1792 {
1793 idlen = q - p;
1794 idstart = p;
1795 for (pend = p; pend > pstart; pend--)
1796 {
1797 if (pend[-1] == '\n')
1798 break;
1799 }
1800 p = q + 1;
1801 break;
1802 }
1803 }
1804 while (1)
1805 {
1806 if (!*p)
1807 goto L1;
1808 if (*p == '\n')
1809 {
1810 p++;
1811 if (*p == '\n' && !summary && !namelen && !inCode)
1812 {
1813 pend = p;
1814 p++;
1815 goto L1;
1816 }
1817 break;
1818 }
1819 p++;
1820 pend = p;
1821 }
1822 p = skipwhitespace(p);
1823 }
1824 L1:
1825 if (namelen || pstart < pend)
1826 {
1827 Section s;
1828 if (iequals("Params", name[0 .. namelen]))
1829 s = new ParamSection();
1830 else if (iequals("Macros", name[0 .. namelen]))
1831 s = new MacroSection();
1832 else
1833 s = new Section();
1834 s.name = name[0 .. namelen];
1835 s.body_ = pstart[0 .. pend - pstart];
1836 s.nooutput = 0;
1837 //printf("Section: '%.*s' = '%.*s'\n", cast(int)s.namelen, s.name, cast(int)s.bodylen, s.body);
1838 sections.push(s);
1839 if (!summary && !namelen)
1840 summary = s;
1841 }
1842 if (idlen)
1843 {
1844 name = idstart;
1845 namelen = idlen;
1846 }
1847 else
1848 {
1849 name = null;
1850 namelen = 0;
1851 if (!*p)
1852 break;
1853 }
1854 }
1855 }
1856
1857 void writeSections(Scope* sc, Dsymbols* a, ref OutBuffer buf)
1858 {
1859 assert(a.length);
1860 //printf("DocComment::writeSections()\n");
1861 Loc loc = (*a)[0].loc;
1862 if (Module m = (*a)[0].isModule())
1863 {
1864 if (m.md)
1865 loc = m.md.loc;
1866 }
1867 size_t offset1 = buf.length;
1868 buf.writestring("$(DDOC_SECTIONS ");
1869 size_t offset2 = buf.length;
1870 for (size_t i = 0; i < sections.length; i++)
1871 {
1872 Section sec = sections[i];
1873 if (sec.nooutput)
1874 continue;
1875 //printf("Section: '%.*s' = '%.*s'\n", cast(int)sec.namelen, sec.name, cast(int)sec.bodylen, sec.body);
1876 if (!sec.name.length && i == 0)
1877 {
1878 buf.writestring("$(DDOC_SUMMARY ");
1879 size_t o = buf.length;
1880 buf.write(sec.body_);
1881 escapeStrayParenthesis(loc, buf, o, true, sc.eSink);
1882 highlightText(sc, a, loc, buf, o);
1883 buf.writestring(")");
1884 }
1885 else
1886 sec.write(loc, &this, sc, a, buf);
1887 }
1888 for (size_t i = 0; i < a.length; i++)
1889 {
1890 Dsymbol s = (*a)[i];
1891 if (Dsymbol td = getEponymousParent(s))
1892 s = td;
1893 for (UnitTestDeclaration utd = s.ddocUnittest; utd; utd = utd.ddocUnittest)
1894 {
1895 if (utd.visibility.kind == Visibility.Kind.private_ || !utd.comment || !utd.fbody)
1896 continue;
1897 // Strip whitespaces to avoid showing empty summary
1898 const(char)* c = utd.comment;
1899 while (*c == ' ' || *c == '\t' || *c == '\n' || *c == '\r')
1900 ++c;
1901 buf.writestring("$(DDOC_EXAMPLES ");
1902 size_t o = buf.length;
1903 buf.writestring(cast(char*)c);
1904 if (utd.codedoc)
1905 {
1906 auto codedoc = utd.codedoc.stripLeadingNewlines;
1907 size_t n = getCodeIndent(codedoc);
1908 while (n--)
1909 buf.writeByte(' ');
1910 buf.writestring("----\n");
1911 buf.writestring(codedoc);
1912 buf.writestring("----\n");
1913 highlightText(sc, a, loc, buf, o);
1914 }
1915 buf.writestring(")");
1916 }
1917 }
1918 if (buf.length == offset2)
1919 {
1920 /* Didn't write out any sections, so back out last write
1921 */
1922 buf.setsize(offset1);
1923 buf.writestring("\n");
1924 }
1925 else
1926 buf.writestring(")");
1927 }
1928 }
1929
1930 /*****************************************
1931 * Return true if comment consists entirely of "ditto".
1932 */
1933 bool isDitto(const(char)* comment)
1934 {
1935 if (comment)
1936 {
1937 const(char)* p = skipwhitespace(comment);
1938 if (Port.memicmp(p, "ditto", 5) == 0 && *skipwhitespace(p + 5) == 0)
1939 return true;
1940 }
1941 return false;
1942 }
1943
1944 /**********************************************
1945 * Skip white space.
1946 */
1947 const(char)* skipwhitespace(const(char)* p)
1948 {
1949 return skipwhitespace(p.toDString).ptr;
1950 }
1951
1952 /// Ditto
1953 const(char)[] skipwhitespace(const(char)[] p) @safe
1954 {
1955 foreach (idx, char c; p)
1956 {
1957 switch (c)
1958 {
1959 case ' ':
1960 case '\t':
1961 case '\n':
1962 continue;
1963 default:
1964 return p[idx .. $];
1965 }
1966 }
1967 return p[$ .. $];
1968 }
1969
1970 /************************************************
1971 * Scan past all instances of the given characters.
1972 * Params:
1973 * buf = an OutBuffer containing the DDoc
1974 * i = the index within `buf` to start scanning from
1975 * chars = the characters to skip; order is unimportant
1976 * Returns: the index after skipping characters.
1977 */
1978 size_t skipChars(ref OutBuffer buf, size_t i, string chars) @safe
1979 {
1980 Outer:
1981 foreach (j, c; buf[][i..$])
1982 {
1983 foreach (d; chars)
1984 {
1985 if (d == c)
1986 continue Outer;
1987 }
1988 return i + j;
1989 }
1990 return buf.length;
1991 }
1992
1993 unittest {
1994 OutBuffer buf;
1995 string data = "test ---\r\n\r\nend";
1996 buf.write(data);
1997
1998 assert(skipChars(buf, 0, "-") == 0);
1999 assert(skipChars(buf, 4, "-") == 4);
2000 assert(skipChars(buf, 4, " -") == 8);
2001 assert(skipChars(buf, 8, "\r\n") == 12);
2002 assert(skipChars(buf, 12, "dne") == 15);
2003 }
2004
2005 /****************************************************
2006 * Replace all instances of `c` with `r` in the given string
2007 * Params:
2008 * s = the string to do replacements in
2009 * c = the character to look for
2010 * r = the string to replace `c` with
2011 * Returns: `s` with `c` replaced with `r`
2012 */
2013 inout(char)[] replaceChar(inout(char)[] s, char c, string r) pure @safe
2014 {
2015 int count = 0;
2016 foreach (char sc; s)
2017 if (sc == c)
2018 ++count;
2019 if (count == 0)
2020 return s;
2021
2022 char[] result;
2023 result.reserve(s.length - count + (r.length * count));
2024 size_t start = 0;
2025 foreach (i, char sc; s)
2026 {
2027 if (sc == c)
2028 {
2029 result ~= s[start..i];
2030 result ~= r;
2031 start = i+1;
2032 }
2033 }
2034 result ~= s[start..$];
2035 return result;
2036 }
2037
2038 ///
2039 unittest
2040 {
2041 assert("".replaceChar(',', "$(COMMA)") == "");
2042 assert("ab".replaceChar(',', "$(COMMA)") == "ab");
2043 assert("a,b".replaceChar(',', "$(COMMA)") == "a$(COMMA)b");
2044 assert("a,,b".replaceChar(',', "$(COMMA)") == "a$(COMMA)$(COMMA)b");
2045 assert(",ab".replaceChar(',', "$(COMMA)") == "$(COMMA)ab");
2046 assert("ab,".replaceChar(',', "$(COMMA)") == "ab$(COMMA)");
2047 }
2048
2049 /**
2050 * Return a lowercased copy of a string.
2051 * Params:
2052 * s = the string to lowercase
2053 * Returns: the lowercase version of the string or the original if already lowercase
2054 */
2055 string toLowercase(string s) pure @safe
2056 {
2057 string lower;
2058 foreach (size_t i; 0..s.length)
2059 {
2060 char c = s[i];
2061 // TODO: maybe unicode lowercase, somehow
2062 if (c >= 'A' && c <= 'Z')
2063 {
2064 if (!lower.length)
2065 lower.reserve(s.length);
2066
2067 lower ~= s[lower.length..i];
2068 c += 'a' - 'A';
2069 lower ~= c;
2070 }
2071 }
2072 if (lower.length)
2073 lower ~= s[lower.length..$];
2074 else
2075 lower = s;
2076 return lower;
2077 }
2078
2079 ///
2080 unittest
2081 {
2082 assert("".toLowercase == "");
2083 assert("abc".toLowercase == "abc");
2084 assert("ABC".toLowercase == "abc");
2085 assert("aBc".toLowercase == "abc");
2086 }
2087
2088 /************************************************
2089 * Get the indent from one index to another, counting tab stops as four spaces wide
2090 * per the Markdown spec.
2091 * Params:
2092 * buf = an OutBuffer containing the DDoc
2093 * from = the index within `buf` to start counting from, inclusive
2094 * to = the index within `buf` to stop counting at, exclusive
2095 * Returns: the indent
2096 */
2097 int getMarkdownIndent(ref OutBuffer buf, size_t from, size_t to) @safe
2098 {
2099 const slice = buf[];
2100 if (to > slice.length)
2101 to = slice.length;
2102 int indent = 0;
2103 foreach (const c; slice[from..to])
2104 indent += (c == '\t') ? 4 - (indent % 4) : 1;
2105 return indent;
2106 }
2107
2108 /************************************************
2109 * Scan forward past end of identifier.
2110 */
2111 size_t skippastident(ref OutBuffer buf, size_t i) @safe
2112 {
2113 import dmd.common.charactertables;
2114
2115 const slice = buf[];
2116 while (i < slice.length)
2117 {
2118 dchar c;
2119 size_t oi = i;
2120 if (utf_decodeChar(slice, i, c))
2121 {
2122 /* Ignore UTF errors, but still consume input
2123 */
2124 break;
2125 }
2126 if (c >= 0x80)
2127 {
2128 // we don't care if it is start/continue here
2129 if (isAnyIdentifierCharacter(c))
2130 continue;
2131 }
2132 else if (isalnum(c) || c == '_')
2133 continue;
2134 i = oi;
2135 break;
2136 }
2137 return i;
2138 }
2139
2140 /************************************************
2141 * Scan forward past end of an identifier that might
2142 * contain dots (e.g. `abc.def`)
2143 */
2144 size_t skipPastIdentWithDots(ref OutBuffer buf, size_t i) @safe
2145 {
2146 import dmd.common.charactertables;
2147
2148 const slice = buf[];
2149 bool lastCharWasDot;
2150 while (i < slice.length)
2151 {
2152 dchar c;
2153 size_t oi = i;
2154 if (utf_decodeChar(slice, i, c))
2155 {
2156 /* Ignore UTF errors, but still consume input
2157 */
2158 break;
2159 }
2160 if (c == '.')
2161 {
2162 // We need to distinguish between `abc.def`, abc..def`, and `abc.`
2163 // Only `abc.def` is a valid identifier
2164
2165 if (lastCharWasDot)
2166 {
2167 i = oi;
2168 break;
2169 }
2170
2171 lastCharWasDot = true;
2172 continue;
2173 }
2174 else
2175 {
2176 if (c >= 0x80)
2177 {
2178 // we don't care if it is start/continue here
2179 if (isAnyIdentifierCharacter(c))
2180 {
2181 lastCharWasDot = false;
2182 continue;
2183 }
2184 }
2185 else if (isalnum(c) || c == '_')
2186 {
2187 lastCharWasDot = false;
2188 continue;
2189 }
2190 i = oi;
2191 break;
2192 }
2193 }
2194
2195 // if `abc.`
2196 if (lastCharWasDot)
2197 return i - 1;
2198
2199 return i;
2200 }
2201
2202 /************************************************
2203 * Scan forward past URL starting at i.
2204 * We don't want to highlight parts of a URL.
2205 * Returns:
2206 * i if not a URL
2207 * index just past it if it is a URL
2208 */
2209 size_t skippastURL(ref OutBuffer buf, size_t i)
2210 {
2211 const slice = buf[][i .. $];
2212 size_t j;
2213 bool sawdot = false;
2214 if (slice.length > 7 && Port.memicmp(slice.ptr, "http://", 7) == 0)
2215 {
2216 j = 7;
2217 }
2218 else if (slice.length > 8 && Port.memicmp(slice.ptr, "https://", 8) == 0)
2219 {
2220 j = 8;
2221 }
2222 else
2223 goto Lno;
2224 for (; j < slice.length; j++)
2225 {
2226 const c = slice[j];
2227 if (isalnum(c))
2228 continue;
2229 if (c == '-' || c == '_' || c == '?' || c == '=' || c == '%' ||
2230 c == '&' || c == '/' || c == '+' || c == '#' || c == '~')
2231 continue;
2232 if (c == '.')
2233 {
2234 sawdot = true;
2235 continue;
2236 }
2237 break;
2238 }
2239 if (sawdot)
2240 return i + j;
2241 Lno:
2242 return i;
2243 }
2244
2245 /****************************************************
2246 * Remove a previously-inserted blank line macro.
2247 * Params:
2248 * buf = an OutBuffer containing the DDoc
2249 * iAt = the index within `buf` of the start of the `$(DDOC_BLANKLINE)`
2250 * macro. Upon function return its value is set to `0`.
2251 * i = an index within `buf`. If `i` is after `iAt` then it gets
2252 * reduced by the length of the removed macro.
2253 */
2254 void removeBlankLineMacro(ref OutBuffer buf, ref size_t iAt, ref size_t i)
2255 {
2256 if (!iAt)
2257 return;
2258
2259 enum macroLength = "$(DDOC_BLANKLINE)".length;
2260 buf.remove(iAt, macroLength);
2261 if (i > iAt)
2262 i -= macroLength;
2263 iAt = 0;
2264 }
2265
2266 /****************************************************
2267 * Attempt to detect and replace a Markdown thematic break (HR). These are three
2268 * or more of the same delimiter, optionally with spaces or tabs between any of
2269 * them, e.g. `\n- - -\n` becomes `\n$(HR)\n`
2270 * Params:
2271 * buf = an OutBuffer containing the DDoc
2272 * i = the index within `buf` of the first character of a potential
2273 * thematic break. If the replacement is made `i` changes to
2274 * point to the closing parenthesis of the `$(HR)` macro.
2275 * iLineStart = the index within `buf` that the thematic break's line starts at
2276 * Returns: whether a thematic break was replaced
2277 */
2278 bool replaceMarkdownThematicBreak(ref OutBuffer buf, ref size_t i, size_t iLineStart)
2279 {
2280
2281 const slice = buf[];
2282 const c = buf[i];
2283 size_t j = i + 1;
2284 int repeat = 1;
2285 for (; j < slice.length; j++)
2286 {
2287 if (buf[j] == c)
2288 ++repeat;
2289 else if (buf[j] != ' ' && buf[j] != '\t')
2290 break;
2291 }
2292 if (repeat >= 3)
2293 {
2294 if (j >= buf.length || buf[j] == '\n' || buf[j] == '\r')
2295 {
2296 buf.remove(iLineStart, j - iLineStart);
2297 i = buf.insert(iLineStart, "$(HR)") - 1;
2298 return true;
2299 }
2300 }
2301 return false;
2302 }
2303
2304 /****************************************************
2305 * Detect the level of an ATX-style heading, e.g. `## This is a heading` would
2306 * have a level of `2`.
2307 * Params:
2308 * buf = an OutBuffer containing the DDoc
2309 * i = the index within `buf` of the first `#` character
2310 * Returns:
2311 * the detected heading level from 1 to 6, or
2312 * 0 if not at an ATX heading
2313 */
2314 int detectAtxHeadingLevel(ref OutBuffer buf, const size_t i) @safe
2315 {
2316 const iHeadingStart = i;
2317 const iAfterHashes = skipChars(buf, i, "#");
2318 const headingLevel = cast(int) (iAfterHashes - iHeadingStart);
2319 if (headingLevel > 6)
2320 return 0;
2321
2322 const iTextStart = skipChars(buf, iAfterHashes, " \t");
2323 const emptyHeading = buf[iTextStart] == '\r' || buf[iTextStart] == '\n';
2324
2325 // require whitespace
2326 if (!emptyHeading && iTextStart == iAfterHashes)
2327 return 0;
2328
2329 return headingLevel;
2330 }
2331
2332 /****************************************************
2333 * Remove any trailing `##` suffix from an ATX-style heading.
2334 * Params:
2335 * buf = an OutBuffer containing the DDoc
2336 * i = the index within `buf` to start looking for a suffix at
2337 */
2338 void removeAnyAtxHeadingSuffix(ref OutBuffer buf, size_t i)
2339 {
2340 size_t j = i;
2341 size_t iSuffixStart = 0;
2342 size_t iWhitespaceStart = j;
2343 const slice = buf[];
2344 for (; j < slice.length; j++)
2345 {
2346 switch (slice[j])
2347 {
2348 case '#':
2349 if (iWhitespaceStart && !iSuffixStart)
2350 iSuffixStart = j;
2351 continue;
2352 case ' ':
2353 case '\t':
2354 if (!iWhitespaceStart)
2355 iWhitespaceStart = j;
2356 continue;
2357 case '\r':
2358 case '\n':
2359 break;
2360 default:
2361 iSuffixStart = 0;
2362 iWhitespaceStart = 0;
2363 continue;
2364 }
2365 break;
2366 }
2367 if (iSuffixStart)
2368 buf.remove(iWhitespaceStart, j - iWhitespaceStart);
2369 }
2370
2371 /****************************************************
2372 * Wrap text in a Markdown heading macro, e.g. `$(H2 heading text`).
2373 * Params:
2374 * buf = an OutBuffer containing the DDoc
2375 * iStart = the index within `buf` that the Markdown heading starts at
2376 * iEnd = the index within `buf` of the character after the last
2377 * heading character. Is incremented by the length of the
2378 * inserted heading macro when this function ends.
2379 * headingLevel = the level (1-6) of heading to end. Is set to `0` when this
2380 * function ends.
2381 */
2382 void endMarkdownHeading(ref OutBuffer buf, size_t iStart, ref size_t iEnd, ref int headingLevel)
2383 {
2384 char[5] heading = "$(H0 ";
2385 heading[3] = cast(char) ('0' + headingLevel);
2386 buf.insert(iStart, heading);
2387 iEnd += 5;
2388 size_t iBeforeNewline = iEnd;
2389 while (buf[iBeforeNewline-1] == '\r' || buf[iBeforeNewline-1] == '\n')
2390 --iBeforeNewline;
2391 buf.insert(iBeforeNewline, ")");
2392 headingLevel = 0;
2393 }
2394
2395 /****************************************************
2396 * End all nested Markdown quotes, if inside any.
2397 * Params:
2398 * buf = an OutBuffer containing the DDoc
2399 * i = the index within `buf` of the character after the quote text.
2400 * quoteLevel = the current quote level. Is set to `0` when this function ends.
2401 * Returns: the amount that `i` was moved
2402 */
2403 size_t endAllMarkdownQuotes(ref OutBuffer buf, size_t i, ref int quoteLevel)
2404 {
2405 const length = quoteLevel;
2406 for (; quoteLevel > 0; --quoteLevel)
2407 i = buf.insert(i, ")");
2408 return length;
2409 }
2410
2411 /****************************************************
2412 * Convenience function to end all Markdown lists and quotes, if inside any, and
2413 * set `quoteMacroLevel` to `0`.
2414 * Params:
2415 * buf = an OutBuffer containing the DDoc
2416 * i = the index within `buf` of the character after the list and/or
2417 * quote text. Is adjusted when this function ends if any lists
2418 * and/or quotes were ended.
2419 * nestedLists = a set of nested lists. Upon return it will be empty.
2420 * quoteLevel = the current quote level. Is set to `0` when this function ends.
2421 * quoteMacroLevel = the macro level that the quote was started at. Is set to
2422 * `0` when this function ends.
2423 * Returns: the amount that `i` was moved
2424 */
2425 size_t endAllListsAndQuotes(ref OutBuffer buf, ref size_t i, ref MarkdownList[] nestedLists, ref int quoteLevel, out int quoteMacroLevel)
2426 {
2427 quoteMacroLevel = 0;
2428 const i0 = i;
2429 i += MarkdownList.endAllNestedLists(buf, i, nestedLists);
2430 i += endAllMarkdownQuotes(buf, i, quoteLevel);
2431 return i - i0;
2432 }
2433
2434 /****************************************************
2435 * Replace Markdown emphasis with the appropriate macro,
2436 * e.g. `*very* **nice**` becomes `$(EM very) $(STRONG nice)`.
2437 * Params:
2438 * buf = an OutBuffer containing the DDoc
2439 * inlineDelimiters = the collection of delimiters found within a paragraph. When this function returns its length will be reduced to `downToLevel`.
2440 * downToLevel = the length within `inlineDelimiters`` to reduce emphasis to
2441 * Returns: the number of characters added to the buffer by the replacements
2442 */
2443 size_t replaceMarkdownEmphasis(ref OutBuffer buf, ref MarkdownDelimiter[] inlineDelimiters, int downToLevel = 0)
2444 {
2445 size_t replaceEmphasisPair(ref MarkdownDelimiter start, ref MarkdownDelimiter end)
2446 {
2447 immutable count = start.count == 1 || end.count == 1 ? 1 : 2;
2448
2449 size_t iStart = start.iStart;
2450 size_t iEnd = end.iStart;
2451 end.count -= count;
2452 start.count -= count;
2453 iStart += start.count;
2454
2455 if (!start.count)
2456 start.type = 0;
2457 if (!end.count)
2458 end.type = 0;
2459
2460 buf.remove(iStart, count);
2461 iEnd -= count;
2462 buf.remove(iEnd, count);
2463
2464 string macroName = count >= 2 ? "$(STRONG " : "$(EM ";
2465 buf.insert(iEnd, ")");
2466 buf.insert(iStart, macroName);
2467
2468 const delta = 1 + macroName.length - (count + count);
2469 end.iStart += count;
2470 return delta;
2471 }
2472
2473 size_t delta = 0;
2474 int start = (cast(int) inlineDelimiters.length) - 1;
2475 while (start >= downToLevel)
2476 {
2477 // find start emphasis
2478 while (start >= downToLevel &&
2479 (inlineDelimiters[start].type != '*' || !inlineDelimiters[start].leftFlanking))
2480 --start;
2481 if (start < downToLevel)
2482 break;
2483
2484 // find the nearest end emphasis
2485 int end = start + 1;
2486 while (end < inlineDelimiters.length &&
2487 (inlineDelimiters[end].type != inlineDelimiters[start].type ||
2488 inlineDelimiters[end].macroLevel != inlineDelimiters[start].macroLevel ||
2489 !inlineDelimiters[end].rightFlanking))
2490 ++end;
2491 if (end == inlineDelimiters.length)
2492 {
2493 // the start emphasis has no matching end; if it isn't an end itself then kill it
2494 if (!inlineDelimiters[start].rightFlanking)
2495 inlineDelimiters[start].type = 0;
2496 --start;
2497 continue;
2498 }
2499
2500 // multiple-of-3 rule
2501 if (((inlineDelimiters[start].leftFlanking && inlineDelimiters[start].rightFlanking) ||
2502 (inlineDelimiters[end].leftFlanking && inlineDelimiters[end].rightFlanking)) &&
2503 (inlineDelimiters[start].count + inlineDelimiters[end].count) % 3 == 0)
2504 {
2505 --start;
2506 continue;
2507 }
2508
2509 immutable delta0 = replaceEmphasisPair(inlineDelimiters[start], inlineDelimiters[end]);
2510
2511 for (; end < inlineDelimiters.length; ++end)
2512 inlineDelimiters[end].iStart += delta0;
2513 delta += delta0;
2514 }
2515
2516 inlineDelimiters.length = downToLevel;
2517 return delta;
2518 }
2519
2520 /****************************************************
2521 */
2522 bool isIdentifier(Dsymbols* a, const(char)[] s) @safe
2523 {
2524 foreach (member; *a)
2525 {
2526 if (auto imp = member.isImport())
2527 {
2528 // For example: `public import str = core.stdc.string;`
2529 // This checks if `s` is equal to `str`
2530 if (imp.aliasId)
2531 {
2532 if (s == imp.aliasId.toString())
2533 return true;
2534 }
2535 else
2536 {
2537 // The general case: `public import core.stdc.string;`
2538
2539 // fully qualify imports so `core.stdc.string` doesn't appear as `core`
2540 string fullyQualifiedImport;
2541 foreach (const pid; imp.packages)
2542 {
2543 fullyQualifiedImport ~= pid.toString() ~ ".";
2544 }
2545 fullyQualifiedImport ~= imp.id.toString();
2546
2547 // Check if `s` == `core.stdc.string`
2548 if (s == fullyQualifiedImport)
2549 return true;
2550 }
2551 }
2552 else if (member.ident)
2553 {
2554 if (s == member.ident.toString())
2555 return true;
2556 }
2557
2558 }
2559 return false;
2560 }
2561
2562 /****************************************************
2563 */
2564 bool isKeyword(const(char)[] str) @safe
2565 {
2566 immutable string[3] table = ["true", "false", "null"];
2567 foreach (s; table)
2568 {
2569 if (str == s)
2570 return true;
2571 }
2572 return false;
2573 }
2574
2575 /****************************************************
2576 */
2577 TypeFunction isTypeFunction(Dsymbol s) @safe
2578 {
2579 FuncDeclaration f = s.isFuncDeclaration();
2580 /* f.type may be NULL for template members.
2581 */
2582 if (f && f.type)
2583 {
2584 Type t = f.originalType ? f.originalType : f.type;
2585 if (t.ty == Tfunction)
2586 return (() @trusted => cast(TypeFunction)t)();
2587 }
2588 return null;
2589 }
2590
2591 /****************************************************
2592 */
2593 Parameter isFunctionParameter(Dsymbol s, const(char)[] str) @safe
2594 {
2595 TypeFunction tf = isTypeFunction(s);
2596 if (tf && tf.parameterList.parameters)
2597 {
2598 foreach (fparam; *tf.parameterList.parameters)
2599 {
2600 if (fparam.ident && str == fparam.ident.toString())
2601 {
2602 return fparam;
2603 }
2604 }
2605 }
2606 return null;
2607 }
2608
2609 /****************************************************
2610 */
2611 Parameter isFunctionParameter(Dsymbols* a, const(char)[] p) @safe
2612 {
2613 foreach (Dsymbol sym; *a)
2614 {
2615 Parameter fparam = isFunctionParameter(sym, p);
2616 if (fparam)
2617 {
2618 return fparam;
2619 }
2620 }
2621 return null;
2622 }
2623
2624 /****************************************************
2625 */
2626 Parameter isEponymousFunctionParameter(Dsymbols* a, const(char)[] p) @safe
2627 {
2628 foreach (Dsymbol dsym; *a)
2629 {
2630 TemplateDeclaration td = dsym.isTemplateDeclaration();
2631 if (td && td.onemember)
2632 {
2633 /* Case 1: we refer to a template declaration inside the template
2634
2635 /// ...ddoc...
2636 template case1(T) {
2637 void case1(R)() {}
2638 }
2639 */
2640 td = td.onemember.isTemplateDeclaration();
2641 }
2642 if (!td)
2643 {
2644 /* Case 2: we're an alias to a template declaration
2645
2646 /// ...ddoc...
2647 alias case2 = case1!int;
2648 */
2649 AliasDeclaration ad = dsym.isAliasDeclaration();
2650 if (ad && ad.aliassym)
2651 {
2652 td = ad.aliassym.isTemplateDeclaration();
2653 }
2654 }
2655 while (td)
2656 {
2657 Dsymbol sym = getEponymousMember(td);
2658 if (sym)
2659 {
2660 Parameter fparam = isFunctionParameter(sym, p);
2661 if (fparam)
2662 {
2663 return fparam;
2664 }
2665 }
2666 td = td.overnext;
2667 }
2668 }
2669 return null;
2670 }
2671
2672 /****************************************************
2673 */
2674 TemplateParameter isTemplateParameter(Dsymbols* a, const(char)* p, size_t len)
2675 {
2676 for (size_t i = 0; i < a.length; i++)
2677 {
2678 TemplateDeclaration td = (*a)[i].isTemplateDeclaration();
2679 // Check for the parent, if the current symbol is not a template declaration.
2680 if (!td)
2681 td = getEponymousParent((*a)[i]);
2682 if (td && td.origParameters)
2683 {
2684 foreach (tp; *td.origParameters)
2685 {
2686 if (tp.ident && p[0 .. len] == tp.ident.toString())
2687 {
2688 return tp;
2689 }
2690 }
2691 }
2692 }
2693 return null;
2694 }
2695
2696 /****************************************************
2697 * Return true if str is a reserved symbol name
2698 * that starts with a double underscore.
2699 */
2700 bool isReservedName(const(char)[] str) @safe
2701 {
2702 immutable string[] table =
2703 [
2704 "__ctor",
2705 "__dtor",
2706 "__postblit",
2707 "__invariant",
2708 "__unitTest",
2709 "__require",
2710 "__ensure",
2711 "__dollar",
2712 "__ctfe",
2713 "__withSym",
2714 "__result",
2715 "__returnLabel",
2716 "__vptr",
2717 "__monitor",
2718 "__gate",
2719 "__xopEquals",
2720 "__xopCmp",
2721 "__LINE__",
2722 "__FILE__",
2723 "__MODULE__",
2724 "__FUNCTION__",
2725 "__PRETTY_FUNCTION__",
2726 "__DATE__",
2727 "__TIME__",
2728 "__TIMESTAMP__",
2729 "__VENDOR__",
2730 "__VERSION__",
2731 "__EOF__",
2732 "__CXXLIB__",
2733 "__LOCAL_SIZE",
2734 "__entrypoint",
2735 ];
2736 foreach (s; table)
2737 {
2738 if (str == s)
2739 return true;
2740 }
2741 return false;
2742 }
2743
2744 /****************************************************
2745 * A delimiter for Markdown inline content like emphasis and links.
2746 */
2747 struct MarkdownDelimiter
2748 {
2749 size_t iStart; /// the index where this delimiter starts
2750 int count; /// the length of this delimeter's start sequence
2751 int macroLevel; /// the count of nested DDoc macros when the delimiter is started
2752 bool leftFlanking; /// whether the delimiter is left-flanking, as defined by the CommonMark spec
2753 bool rightFlanking; /// whether the delimiter is right-flanking, as defined by the CommonMark spec
2754 bool atParagraphStart; /// whether the delimiter is at the start of a paragraph
2755 char type; /// the type of delimiter, defined by its starting character
2756
2757 /// whether this describes a valid delimiter
2758 @property bool isValid() const @safe { return count != 0; }
2759
2760 /// flag this delimiter as invalid
2761 void invalidate() @safe { count = 0; }
2762 }
2763
2764 /****************************************************
2765 * Info about a Markdown list.
2766 */
2767 struct MarkdownList
2768 {
2769 string orderedStart; /// an optional start number--if present then the list starts at this number
2770 size_t iStart; /// the index where the list item starts
2771 size_t iContentStart; /// the index where the content starts after the list delimiter
2772 int delimiterIndent; /// the level of indent the list delimiter starts at
2773 int contentIndent; /// the level of indent the content starts at
2774 int macroLevel; /// the count of nested DDoc macros when the list is started
2775 char type; /// the type of list, defined by its starting character
2776
2777 /// whether this describes a valid list
2778 @property bool isValid() const @safe { return type != type.init; }
2779
2780 /****************************************************
2781 * Try to parse a list item, returning whether successful.
2782 * Params:
2783 * buf = an OutBuffer containing the DDoc
2784 * iLineStart = the index within `buf` of the first character of the line
2785 * i = the index within `buf` of the potential list item
2786 * Returns: the parsed list item. Its `isValid` property describes whether parsing succeeded.
2787 */
2788 static MarkdownList parseItem(ref OutBuffer buf, size_t iLineStart, size_t i) @safe
2789 {
2790 if (buf[i] == '+' || buf[i] == '-' || buf[i] == '*')
2791 return parseUnorderedListItem(buf, iLineStart, i);
2792 else
2793 return parseOrderedListItem(buf, iLineStart, i);
2794 }
2795
2796 /****************************************************
2797 * Return whether the context is at a list item of the same type as this list.
2798 * Params:
2799 * buf = an OutBuffer containing the DDoc
2800 * iLineStart = the index within `buf` of the first character of the line
2801 * i = the index within `buf` of the list item
2802 * Returns: whether `i` is at a list item of the same type as this list
2803 */
2804 private bool isAtItemInThisList(ref OutBuffer buf, size_t iLineStart, size_t i) @safe
2805 {
2806 MarkdownList item = (type == '.' || type == ')') ?
2807 parseOrderedListItem(buf, iLineStart, i) :
2808 parseUnorderedListItem(buf, iLineStart, i);
2809 if (item.type == type)
2810 return item.delimiterIndent < contentIndent && item.contentIndent > delimiterIndent;
2811 return false;
2812 }
2813
2814 /****************************************************
2815 * Start a Markdown list item by creating/deleting nested lists and starting the item.
2816 * Params:
2817 * buf = an OutBuffer containing the DDoc
2818 * iLineStart = the index within `buf` of the first character of the line. If this function succeeds it will be adjuested to equal `i`.
2819 * i = the index within `buf` of the list item. If this function succeeds `i` will be adjusted to fit the inserted macro.
2820 * iPrecedingBlankLine = the index within `buf` of the preceeding blank line. If non-zero and a new list was started, the preceeding blank line is removed and this value is set to `0`.
2821 * nestedLists = a set of nested lists. If this function succeeds it may contain a new nested list.
2822 * Returns: `true` if a list was created
2823 */
2824 bool startItem(ref OutBuffer buf, ref size_t iLineStart, ref size_t i, ref size_t iPrecedingBlankLine, ref MarkdownList[] nestedLists)
2825 {
2826 buf.remove(iStart, iContentStart - iStart);
2827
2828 if (!nestedLists.length ||
2829 delimiterIndent >= nestedLists[$-1].contentIndent ||
2830 buf[iLineStart - 4..iLineStart] == "$(LI")
2831 {
2832 // start a list macro
2833 nestedLists ~= this;
2834 if (type == '.')
2835 {
2836 if (orderedStart.length)
2837 {
2838 iStart = buf.insert(iStart, "$(OL_START ");
2839 iStart = buf.insert(iStart, orderedStart);
2840 iStart = buf.insert(iStart, ",\n");
2841 }
2842 else
2843 iStart = buf.insert(iStart, "$(OL\n");
2844 }
2845 else
2846 iStart = buf.insert(iStart, "$(UL\n");
2847
2848 removeBlankLineMacro(buf, iPrecedingBlankLine, iStart);
2849 }
2850 else if (nestedLists.length)
2851 {
2852 nestedLists[$-1].delimiterIndent = delimiterIndent;
2853 nestedLists[$-1].contentIndent = contentIndent;
2854 }
2855
2856 iStart = buf.insert(iStart, "$(LI\n");
2857 i = iStart - 1;
2858 iLineStart = i;
2859
2860 return true;
2861 }
2862
2863 /****************************************************
2864 * End all nested Markdown lists.
2865 * Params:
2866 * buf = an OutBuffer containing the DDoc
2867 * i = the index within `buf` to end lists at.
2868 * nestedLists = a set of nested lists. Upon return it will be empty.
2869 * Returns: the amount that `i` changed
2870 */
2871 static size_t endAllNestedLists(ref OutBuffer buf, size_t i, ref MarkdownList[] nestedLists)
2872 {
2873 const iStart = i;
2874 for (; nestedLists.length; --nestedLists.length)
2875 i = buf.insert(i, ")\n)");
2876 return i - iStart;
2877 }
2878
2879 /****************************************************
2880 * Look for a sibling list item or the end of nested list(s).
2881 * Params:
2882 * buf = an OutBuffer containing the DDoc
2883 * i = the index within `buf` to end lists at. If there was a sibling or ending lists `i` will be adjusted to fit the macro endings.
2884 * iParagraphStart = the index within `buf` to start the next paragraph at at. May be adjusted upon return.
2885 * nestedLists = a set of nested lists. Some nested lists may have been removed from it upon return.
2886 */
2887 static void handleSiblingOrEndingList(ref OutBuffer buf, ref size_t i, ref size_t iParagraphStart, ref MarkdownList[] nestedLists)
2888 {
2889 size_t iAfterSpaces = skipChars(buf, i + 1, " \t");
2890
2891 if (nestedLists[$-1].isAtItemInThisList(buf, i + 1, iAfterSpaces))
2892 {
2893 // end a sibling list item
2894 i = buf.insert(i, ")");
2895 iParagraphStart = skipChars(buf, i, " \t\r\n");
2896 }
2897 else if (iAfterSpaces >= buf.length || (buf[iAfterSpaces] != '\r' && buf[iAfterSpaces] != '\n'))
2898 {
2899 // end nested lists that are indented more than this content
2900 const indent = getMarkdownIndent(buf, i + 1, iAfterSpaces);
2901 while (nestedLists.length && nestedLists[$-1].contentIndent > indent)
2902 {
2903 i = buf.insert(i, ")\n)");
2904 --nestedLists.length;
2905 iParagraphStart = skipChars(buf, i, " \t\r\n");
2906
2907 if (nestedLists.length && nestedLists[$-1].isAtItemInThisList(buf, i + 1, iParagraphStart))
2908 {
2909 i = buf.insert(i, ")");
2910 ++iParagraphStart;
2911 break;
2912 }
2913 }
2914 }
2915 }
2916
2917 /****************************************************
2918 * Parse an unordered list item at the current position
2919 * Params:
2920 * buf = an OutBuffer containing the DDoc
2921 * iLineStart = the index within `buf` of the first character of the line
2922 * i = the index within `buf` of the list item
2923 * Returns: the parsed list item, or a list item with type `.init` if no list item is available
2924 */
2925 private static MarkdownList parseUnorderedListItem(ref OutBuffer buf, size_t iLineStart, size_t i) @safe
2926 {
2927 if (i+1 < buf.length &&
2928 (buf[i] == '-' ||
2929 buf[i] == '*' ||
2930 buf[i] == '+') &&
2931 (buf[i+1] == ' ' ||
2932 buf[i+1] == '\t' ||
2933 buf[i+1] == '\r' ||
2934 buf[i+1] == '\n'))
2935 {
2936 const iContentStart = skipChars(buf, i + 1, " \t");
2937 const delimiterIndent = getMarkdownIndent(buf, iLineStart, i);
2938 const contentIndent = getMarkdownIndent(buf, iLineStart, iContentStart);
2939 auto list = MarkdownList(null, iLineStart, iContentStart, delimiterIndent, contentIndent, 0, buf[i]);
2940 return list;
2941 }
2942 return MarkdownList();
2943 }
2944
2945 /****************************************************
2946 * Parse an ordered list item at the current position
2947 * Params:
2948 * buf = an OutBuffer containing the DDoc
2949 * iLineStart = the index within `buf` of the first character of the line
2950 * i = the index within `buf` of the list item
2951 * Returns: the parsed list item, or a list item with type `.init` if no list item is available
2952 */
2953 private static MarkdownList parseOrderedListItem(ref OutBuffer buf, size_t iLineStart, size_t i) @safe
2954 {
2955 size_t iAfterNumbers = skipChars(buf, i, "0123456789");
2956 if (iAfterNumbers - i > 0 &&
2957 iAfterNumbers - i <= 9 &&
2958 iAfterNumbers + 1 < buf.length &&
2959 buf[iAfterNumbers] == '.' &&
2960 (buf[iAfterNumbers+1] == ' ' ||
2961 buf[iAfterNumbers+1] == '\t' ||
2962 buf[iAfterNumbers+1] == '\r' ||
2963 buf[iAfterNumbers+1] == '\n'))
2964 {
2965 const iContentStart = skipChars(buf, iAfterNumbers + 1, " \t");
2966 const delimiterIndent = getMarkdownIndent(buf, iLineStart, i);
2967 const contentIndent = getMarkdownIndent(buf, iLineStart, iContentStart);
2968 size_t iNumberStart = skipChars(buf, i, "0");
2969 if (iNumberStart == iAfterNumbers)
2970 --iNumberStart;
2971 auto orderedStart = buf[][iNumberStart .. iAfterNumbers];
2972 if (orderedStart == "1")
2973 orderedStart = null;
2974 return MarkdownList(orderedStart.idup, iLineStart, iContentStart, delimiterIndent, contentIndent, 0, buf[iAfterNumbers]);
2975 }
2976 return MarkdownList();
2977 }
2978 }
2979
2980 /****************************************************
2981 * A Markdown link.
2982 */
2983 struct MarkdownLink
2984 {
2985 string href; /// the link destination
2986 string title; /// an optional title for the link
2987 string label; /// an optional label for the link
2988 Dsymbol symbol; /// an optional symbol to link to
2989
2990 /****************************************************
2991 * Replace a Markdown link or link definition in the form of:
2992 * - Inline link: `[foo](url/ 'optional title')`
2993 * - Reference link: `[foo][bar]`, `[foo][]` or `[foo]`
2994 * - Link reference definition: `[bar]: url/ 'optional title'`
2995 * Params:
2996 * buf = an OutBuffer containing the DDoc
2997 * i = the index within `buf` that points to the `]` character of the potential link.
2998 * If this function succeeds it will be adjusted to fit the inserted link macro.
2999 * inlineDelimiters = previously parsed Markdown delimiters, including emphasis and link/image starts
3000 * delimiterIndex = the index within `inlineDelimiters` of the nearest link/image starting delimiter
3001 * linkReferences = previously parsed link references. When this function returns it may contain
3002 * additional previously unparsed references.
3003 * Returns: whether a reference link was found and replaced at `i`
3004 */
3005 static bool replaceLink(ref OutBuffer buf, ref size_t i, ref MarkdownDelimiter[] inlineDelimiters, int delimiterIndex, ref MarkdownLinkReferences linkReferences)
3006 {
3007 const delimiter = inlineDelimiters[delimiterIndex];
3008 MarkdownLink link;
3009
3010 size_t iEnd = link.parseReferenceDefinition(buf, i, delimiter);
3011 if (iEnd > i)
3012 {
3013 i = delimiter.iStart;
3014 link.storeAndReplaceDefinition(buf, i, iEnd, linkReferences);
3015 inlineDelimiters.length = delimiterIndex;
3016 return true;
3017 }
3018
3019 iEnd = link.parseInlineLink(buf, i);
3020 if (iEnd == i)
3021 {
3022 iEnd = link.parseReferenceLink(buf, i, delimiter);
3023 if (iEnd > i)
3024 {
3025 const label = link.label;
3026 link = linkReferences.lookupReference(label, buf, i);
3027 // check rightFlanking to avoid replacing things like int[string]
3028 if (!link.href.length && !delimiter.rightFlanking)
3029 link = linkReferences.lookupSymbol(label);
3030 if (!link.href.length)
3031 return false;
3032 }
3033 }
3034
3035 if (iEnd == i)
3036 return false;
3037
3038 immutable delta = replaceMarkdownEmphasis(buf, inlineDelimiters, delimiterIndex);
3039 iEnd += delta;
3040 i += delta;
3041 link.replaceLink(buf, i, iEnd, delimiter);
3042 return true;
3043 }
3044
3045 /****************************************************
3046 * Replace a Markdown link definition in the form of `[bar]: url/ 'optional title'`
3047 * Params:
3048 * buf = an OutBuffer containing the DDoc
3049 * i = the index within `buf` that points to the `]` character of the potential link.
3050 * If this function succeeds it will be adjusted to fit the inserted link macro.
3051 * inlineDelimiters = previously parsed Markdown delimiters, including emphasis and link/image starts
3052 * delimiterIndex = the index within `inlineDelimiters` of the nearest link/image starting delimiter
3053 * linkReferences = previously parsed link references. When this function returns it may contain
3054 * additional previously unparsed references.
3055 * Returns: whether a reference link was found and replaced at `i`
3056 */
3057 static bool replaceReferenceDefinition(ref OutBuffer buf, ref size_t i, ref MarkdownDelimiter[] inlineDelimiters, int delimiterIndex, ref MarkdownLinkReferences linkReferences)
3058 {
3059 const delimiter = inlineDelimiters[delimiterIndex];
3060 MarkdownLink link;
3061 size_t iEnd = link.parseReferenceDefinition(buf, i, delimiter);
3062 if (iEnd == i)
3063 return false;
3064
3065 i = delimiter.iStart;
3066 link.storeAndReplaceDefinition(buf, i, iEnd, linkReferences);
3067 inlineDelimiters.length = delimiterIndex;
3068 return true;
3069 }
3070
3071 /****************************************************
3072 * Parse a Markdown inline link in the form of `[foo](url/ 'optional title')`
3073 * Params:
3074 * buf = an OutBuffer containing the DDoc
3075 * i = the index within `buf` that points to the `]` character of the inline link.
3076 * Returns: the index at the end of parsing the link, or `i` if parsing failed.
3077 */
3078 private size_t parseInlineLink(ref OutBuffer buf, size_t i)
3079 {
3080 size_t iEnd = i + 1;
3081 if (iEnd >= buf.length || buf[iEnd] != '(')
3082 return i;
3083 ++iEnd;
3084
3085 if (!parseHref(buf, iEnd))
3086 return i;
3087
3088 iEnd = skipChars(buf, iEnd, " \t\r\n");
3089 if (buf[iEnd] != ')')
3090 {
3091 if (parseTitle(buf, iEnd))
3092 iEnd = skipChars(buf, iEnd, " \t\r\n");
3093 }
3094
3095 if (buf[iEnd] != ')')
3096 return i;
3097
3098 return iEnd + 1;
3099 }
3100
3101 /****************************************************
3102 * Parse a Markdown reference link in the form of `[foo][bar]`, `[foo][]` or `[foo]`
3103 * Params:
3104 * buf = an OutBuffer containing the DDoc
3105 * i = the index within `buf` that points to the `]` character of the inline link.
3106 * delimiter = the delimiter that starts this link
3107 * Returns: the index at the end of parsing the link, or `i` if parsing failed.
3108 */
3109 private size_t parseReferenceLink(ref OutBuffer buf, size_t i, MarkdownDelimiter delimiter) @safe
3110 {
3111 size_t iStart = i + 1;
3112 size_t iEnd = iStart;
3113 if (iEnd >= buf.length || buf[iEnd] != '[' || (iEnd+1 < buf.length && buf[iEnd+1] == ']'))
3114 {
3115 // collapsed reference [foo][] or shortcut reference [foo]
3116 iStart = delimiter.iStart + delimiter.count - 1;
3117 if (buf[iEnd] == '[')
3118 iEnd += 2;
3119 }
3120
3121 parseLabel(buf, iStart);
3122 if (!label.length)
3123 return i;
3124
3125 if (iEnd < iStart)
3126 iEnd = iStart;
3127 return iEnd;
3128 }
3129
3130 /****************************************************
3131 * Parse a Markdown reference definition in the form of `[bar]: url/ 'optional title'`
3132 * Params:
3133 * buf = an OutBuffer containing the DDoc
3134 * i = the index within `buf` that points to the `]` character of the inline link.
3135 * delimiter = the delimiter that starts this link
3136 * Returns: the index at the end of parsing the link, or `i` if parsing failed.
3137 */
3138 private size_t parseReferenceDefinition(ref OutBuffer buf, size_t i, MarkdownDelimiter delimiter)
3139 {
3140 if (!delimiter.atParagraphStart || delimiter.type != '[' ||
3141 i+1 >= buf.length || buf[i+1] != ':')
3142 return i;
3143
3144 size_t iEnd = delimiter.iStart;
3145 parseLabel(buf, iEnd);
3146 if (label.length == 0 || iEnd != i + 1)
3147 return i;
3148
3149 ++iEnd;
3150 iEnd = skipChars(buf, iEnd, " \t");
3151 skipOneNewline(buf, iEnd);
3152
3153 if (!parseHref(buf, iEnd) || href.length == 0)
3154 return i;
3155
3156 iEnd = skipChars(buf, iEnd, " \t");
3157 const requireNewline = !skipOneNewline(buf, iEnd);
3158 const iBeforeTitle = iEnd;
3159
3160 if (parseTitle(buf, iEnd))
3161 {
3162 iEnd = skipChars(buf, iEnd, " \t");
3163 if (iEnd < buf.length && buf[iEnd] != '\r' && buf[iEnd] != '\n')
3164 {
3165 // the title must end with a newline
3166 title.length = 0;
3167 iEnd = iBeforeTitle;
3168 }
3169 }
3170
3171 iEnd = skipChars(buf, iEnd, " \t");
3172 if (requireNewline && iEnd < buf.length-1 && buf[iEnd] != '\r' && buf[iEnd] != '\n')
3173 return i;
3174
3175 return iEnd;
3176 }
3177
3178 /****************************************************
3179 * Parse and normalize a Markdown reference label
3180 * Params:
3181 * buf = an OutBuffer containing the DDoc
3182 * i = the index within `buf` that points to the `[` character at the start of the label.
3183 * If this function returns a non-empty label then `i` will point just after the ']' at the end of the label.
3184 * Returns: the parsed and normalized label, possibly empty
3185 */
3186 private bool parseLabel(ref OutBuffer buf, ref size_t i) @safe
3187 {
3188 if (buf[i] != '[')
3189 return false;
3190
3191 const slice = buf[];
3192 size_t j = i + 1;
3193
3194 // Some labels have already been en-symboled; handle that
3195 const inSymbol = j+15 < slice.length && slice[j..j+15] == "$(DDOC_PSYMBOL ";
3196 if (inSymbol)
3197 j += 15;
3198
3199 for (; j < slice.length; ++j)
3200 {
3201 const c = slice[j];
3202 switch (c)
3203 {
3204 case ' ':
3205 case '\t':
3206 case '\r':
3207 case '\n':
3208 if (label.length && label[$-1] != ' ')
3209 label ~= ' ';
3210 break;
3211 case ')':
3212 if (inSymbol && j+1 < slice.length && slice[j+1] == ']')
3213 {
3214 ++j;
3215 goto case ']';
3216 }
3217 goto default;
3218 case '[':
3219 if (slice[j-1] != '\\')
3220 {
3221 label.length = 0;
3222 return false;
3223 }
3224 break;
3225 case ']':
3226 if (label.length && label[$-1] == ' ')
3227 --label.length;
3228 if (label.length)
3229 {
3230 i = j + 1;
3231 return true;
3232 }
3233 return false;
3234 default:
3235 label ~= c;
3236 break;
3237 }
3238 }
3239 label.length = 0;
3240 return false;
3241 }
3242
3243 /****************************************************
3244 * Parse and store a Markdown link URL, optionally enclosed in `<>` brackets
3245 * Params:
3246 * buf = an OutBuffer containing the DDoc
3247 * i = the index within `buf` that points to the first character of the URL.
3248 * If this function succeeds `i` will point just after the end of the URL.
3249 * Returns: whether a URL was found and parsed
3250 */
3251 private bool parseHref(ref OutBuffer buf, ref size_t i)
3252 {
3253 size_t j = skipChars(buf, i, " \t");
3254
3255 size_t iHrefStart = j;
3256 size_t parenDepth = 1;
3257 bool inPointy = false;
3258 const slice = buf[];
3259 for (; j < slice.length; j++)
3260 {
3261 switch (slice[j])
3262 {
3263 case '<':
3264 if (!inPointy && j == iHrefStart)
3265 {
3266 inPointy = true;
3267 ++iHrefStart;
3268 }
3269 break;
3270 case '>':
3271 if (inPointy && slice[j-1] != '\\')
3272 goto LReturnHref;
3273 break;
3274 case '(':
3275 if (!inPointy && slice[j-1] != '\\')
3276 ++parenDepth;
3277 break;
3278 case ')':
3279 if (!inPointy && slice[j-1] != '\\')
3280 {
3281 --parenDepth;
3282 if (!parenDepth)
3283 goto LReturnHref;
3284 }
3285 break;
3286 case ' ':
3287 case '\t':
3288 case '\r':
3289 case '\n':
3290 if (inPointy)
3291 {
3292 // invalid link
3293 return false;
3294 }
3295 goto LReturnHref;
3296 default:
3297 break;
3298 }
3299 }
3300 if (inPointy)
3301 return false;
3302 LReturnHref:
3303 auto href = slice[iHrefStart .. j].dup;
3304 this.href = cast(string) percentEncode(removeEscapeBackslashes(href)).replaceChar(',', "$(COMMA)");
3305 i = j;
3306 if (inPointy)
3307 ++i;
3308 return true;
3309 }
3310
3311 /****************************************************
3312 * Parse and store a Markdown link title, enclosed in parentheses or `'` or `"` quotes
3313 * Params:
3314 * buf = an OutBuffer containing the DDoc
3315 * i = the index within `buf` that points to the first character of the title.
3316 * If this function succeeds `i` will point just after the end of the title.
3317 * Returns: whether a title was found and parsed
3318 */
3319 private bool parseTitle(ref OutBuffer buf, ref size_t i)
3320 {
3321 size_t j = skipChars(buf, i, " \t");
3322 if (j >= buf.length)
3323 return false;
3324
3325 char type = buf[j];
3326 if (type != '"' && type != '\'' && type != '(')
3327 return false;
3328 if (type == '(')
3329 type = ')';
3330
3331 const iTitleStart = j + 1;
3332 size_t iNewline = 0;
3333 const slice = buf[];
3334 for (j = iTitleStart; j < slice.length; j++)
3335 {
3336 const c = slice[j];
3337 switch (c)
3338 {
3339 case ')':
3340 case '"':
3341 case '\'':
3342 if (type == c && slice[j-1] != '\\')
3343 goto LEndTitle;
3344 iNewline = 0;
3345 break;
3346 case ' ':
3347 case '\t':
3348 case '\r':
3349 break;
3350 case '\n':
3351 if (iNewline)
3352 {
3353 // no blank lines in titles
3354 return false;
3355 }
3356 iNewline = j;
3357 break;
3358 default:
3359 iNewline = 0;
3360 break;
3361 }
3362 }
3363 return false;
3364 LEndTitle:
3365 auto title = slice[iTitleStart .. j].dup;
3366 this.title = cast(string) removeEscapeBackslashes(title).
3367 replaceChar(',', "$(COMMA)").
3368 replaceChar('"', "$(QUOTE)");
3369 i = j + 1;
3370 return true;
3371 }
3372
3373 /****************************************************
3374 * Replace a Markdown link or image with the appropriate macro
3375 * Params:
3376 * buf = an OutBuffer containing the DDoc
3377 * i = the index within `buf` that points to the `]` character of the inline link.
3378 * When this function returns it will be adjusted to the end of the inserted macro.
3379 * iLinkEnd = the index within `buf` that points just after the last character of the link
3380 * delimiter = the Markdown delimiter that started the link or image
3381 */
3382 private void replaceLink(ref OutBuffer buf, ref size_t i, size_t iLinkEnd, MarkdownDelimiter delimiter)
3383 {
3384 size_t iAfterLink = i - delimiter.count;
3385 string macroName;
3386 if (symbol)
3387 {
3388 macroName = "$(SYMBOL_LINK ";
3389 }
3390 else if (title.length)
3391 {
3392 if (delimiter.type == '[')
3393 macroName = "$(LINK_TITLE ";
3394 else
3395 macroName = "$(IMAGE_TITLE ";
3396 }
3397 else
3398 {
3399 if (delimiter.type == '[')
3400 macroName = "$(LINK2 ";
3401 else
3402 macroName = "$(IMAGE ";
3403 }
3404 buf.remove(delimiter.iStart, delimiter.count);
3405 buf.remove(i - delimiter.count, iLinkEnd - i);
3406 iLinkEnd = buf.insert(delimiter.iStart, macroName);
3407 iLinkEnd = buf.insert(iLinkEnd, href);
3408 iLinkEnd = buf.insert(iLinkEnd, ", ");
3409 iAfterLink += macroName.length + href.length + 2;
3410 if (title.length)
3411 {
3412 iLinkEnd = buf.insert(iLinkEnd, title);
3413 iLinkEnd = buf.insert(iLinkEnd, ", ");
3414 iAfterLink += title.length + 2;
3415
3416 // Link macros with titles require escaping commas
3417 for (size_t j = iLinkEnd; j < iAfterLink; ++j)
3418 if (buf[j] == ',')
3419 {
3420 buf.remove(j, 1);
3421 j = buf.insert(j, "$(COMMA)") - 1;
3422 iAfterLink += 7;
3423 }
3424 }
3425 // TODO: if image, remove internal macros, leaving only text
3426 buf.insert(iAfterLink, ")");
3427 i = iAfterLink;
3428 }
3429
3430 /****************************************************
3431 * Store the Markdown link definition and remove it from `buf`
3432 * Params:
3433 * buf = an OutBuffer containing the DDoc
3434 * i = the index within `buf` that points to the `[` character at the start of the link definition.
3435 * When this function returns it will be adjusted to exclude the link definition.
3436 * iEnd = the index within `buf` that points just after the end of the definition
3437 * linkReferences = previously parsed link references. When this function returns it may contain
3438 * an additional reference.
3439 */
3440 private void storeAndReplaceDefinition(ref OutBuffer buf, ref size_t i, size_t iEnd, ref MarkdownLinkReferences linkReferences)
3441 {
3442 // Remove the definition and trailing whitespace
3443 iEnd = skipChars(buf, iEnd, " \t\r\n");
3444 buf.remove(i, iEnd - i);
3445 i -= 2;
3446
3447 string lowercaseLabel = label.toLowercase();
3448 if (lowercaseLabel !in linkReferences.references)
3449 linkReferences.references[lowercaseLabel] = this;
3450 }
3451
3452 /****************************************************
3453 * Remove Markdown escaping backslashes from the given string
3454 * Params:
3455 * s = the string to remove escaping backslashes from
3456 * Returns: `s` without escaping backslashes in it
3457 */
3458 private static char[] removeEscapeBackslashes(char[] s) @safe
3459 {
3460 if (!s.length)
3461 return s;
3462
3463 // avoid doing anything if there isn't anything to escape
3464 size_t i;
3465 for (i = 0; i < s.length-1; ++i)
3466 if (s[i] == '\\' && ispunct(s[i+1]))
3467 break;
3468 if (i == s.length-1)
3469 return s;
3470
3471 // copy characters backwards, then truncate
3472 size_t j = i + 1;
3473 s[i] = s[j];
3474 for (++i, ++j; j < s.length; ++i, ++j)
3475 {
3476 if (j < s.length-1 && s[j] == '\\' && ispunct(s[j+1]))
3477 ++j;
3478 s[i] = s[j];
3479 }
3480 s.length -= (j - i);
3481 return s;
3482 }
3483
3484 ///
3485 unittest
3486 {
3487 assert(removeEscapeBackslashes("".dup) == "");
3488 assert(removeEscapeBackslashes(`\a`.dup) == `\a`);
3489 assert(removeEscapeBackslashes(`.\`.dup) == `.\`);
3490 assert(removeEscapeBackslashes(`\.\`.dup) == `.\`);
3491 assert(removeEscapeBackslashes(`\.`.dup) == `.`);
3492 assert(removeEscapeBackslashes(`\.\.`.dup) == `..`);
3493 assert(removeEscapeBackslashes(`a\.b\.c`.dup) == `a.b.c`);
3494 }
3495
3496 /****************************************************
3497 * Percent-encode (AKA URL-encode) the given string
3498 * Params:
3499 * s = the string to percent-encode
3500 * Returns: `s` with special characters percent-encoded
3501 */
3502 private static inout(char)[] percentEncode(inout(char)[] s) pure @safe
3503 {
3504 static bool shouldEncode(char c)
3505 {
3506 return ((c < '0' && c != '!' && c != '#' && c != '$' && c != '%' && c != '&' && c != '\'' && c != '(' &&
3507 c != ')' && c != '*' && c != '+' && c != ',' && c != '-' && c != '.' && c != '/')
3508 || (c > '9' && c < 'A' && c != ':' && c != ';' && c != '=' && c != '?' && c != '@')
3509 || (c > 'Z' && c < 'a' && c != '[' && c != ']' && c != '_')
3510 || (c > 'z' && c != '~'));
3511 }
3512
3513 for (size_t i = 0; i < s.length; ++i)
3514 {
3515 if (shouldEncode(s[i]))
3516 {
3517 immutable static hexDigits = "0123456789ABCDEF";
3518 immutable encoded1 = hexDigits[s[i] >> 4];
3519 immutable encoded2 = hexDigits[s[i] & 0x0F];
3520 s = s[0..i] ~ '%' ~ encoded1 ~ encoded2 ~ s[i+1..$];
3521 i += 2;
3522 }
3523 }
3524 return s;
3525 }
3526
3527 ///
3528 unittest
3529 {
3530 assert(percentEncode("") == "");
3531 assert(percentEncode("aB12-._~/?") == "aB12-._~/?");
3532 assert(percentEncode("<\n>") == "%3C%0A%3E");
3533 }
3534
3535 /**************************************************
3536 * Skip a single newline at `i`
3537 * Params:
3538 * buf = an OutBuffer containing the DDoc
3539 * i = the index within `buf` to start looking at.
3540 * If this function succeeds `i` will point after the newline.
3541 * Returns: whether a newline was skipped
3542 */
3543 private static bool skipOneNewline(ref OutBuffer buf, ref size_t i) pure @safe
3544 {
3545 if (i < buf.length && buf[i] == '\r')
3546 ++i;
3547 if (i < buf.length && buf[i] == '\n')
3548 {
3549 ++i;
3550 return true;
3551 }
3552 return false;
3553 }
3554 }
3555
3556 /**************************************************
3557 * A set of Markdown link references.
3558 */
3559 struct MarkdownLinkReferences
3560 {
3561 MarkdownLink[string] references; // link references keyed by normalized label
3562 MarkdownLink[string] symbols; // link symbols keyed by name
3563 Scope* _scope; // the current scope
3564 bool extractedAll; // the index into the buffer of the last-parsed reference
3565
3566 /**************************************************
3567 * Look up a reference by label, searching through the rest of the buffer if needed.
3568 * Symbols in the current scope are searched for if the DDoc doesn't define the reference.
3569 * Params:
3570 * label = the label to find the reference for
3571 * buf = an OutBuffer containing the DDoc
3572 * i = the index within `buf` to start searching for references at
3573 * Returns: a link. If the `href` member has a value then the reference is valid.
3574 */
3575 MarkdownLink lookupReference(string label, ref OutBuffer buf, size_t i)
3576 {
3577 const lowercaseLabel = label.toLowercase();
3578 if (lowercaseLabel !in references)
3579 extractReferences(buf, i);
3580
3581 if (lowercaseLabel in references)
3582 return references[lowercaseLabel];
3583
3584 return MarkdownLink();
3585 }
3586
3587 /**
3588 * Look up the link for the D symbol with the given name.
3589 * If found, the link is cached in the `symbols` member.
3590 * Params:
3591 * name = the name of the symbol
3592 * Returns: the link for the symbol or a link with a `null` href
3593 */
3594 MarkdownLink lookupSymbol(string name)
3595 {
3596 if (name in symbols)
3597 return symbols[name];
3598
3599 const ids = split(name, '.');
3600
3601 MarkdownLink link;
3602 auto id = Identifier.lookup(ids[0].ptr, ids[0].length);
3603 if (id)
3604 {
3605 auto loc = Loc.initial;
3606 Dsymbol pscopesym;
3607 auto symbol = _scope.search(loc, id, pscopesym, SearchOpt.ignoreErrors);
3608 for (size_t i = 1; symbol && i < ids.length; ++i)
3609 {
3610 id = Identifier.lookup(ids[i].ptr, ids[i].length);
3611 symbol = id !is null ? symbol.search(loc, id, SearchOpt.ignoreErrors) : null;
3612 }
3613 if (symbol)
3614 link = MarkdownLink(createHref(symbol), null, name, symbol);
3615 }
3616
3617 symbols[name] = link;
3618 return link;
3619 }
3620
3621 /**************************************************
3622 * Remove and store all link references from the document, in the form of
3623 * `[label]: href "optional title"`
3624 * Params:
3625 * buf = an OutBuffer containing the DDoc
3626 * i = the index within `buf` to start looking at
3627 * Returns: whether a reference was extracted
3628 */
3629 private void extractReferences(ref OutBuffer buf, size_t i)
3630 {
3631 static bool isFollowedBySpace(ref OutBuffer buf, size_t i)
3632 {
3633 return i+1 < buf.length && (buf[i+1] == ' ' || buf[i+1] == '\t');
3634 }
3635
3636 if (extractedAll)
3637 return;
3638
3639 bool leadingBlank = false;
3640 int inCode = false;
3641 bool newParagraph = true;
3642 MarkdownDelimiter[] delimiters;
3643 for (; i < buf.length; ++i)
3644 {
3645 const c = buf[i];
3646 switch (c)
3647 {
3648 case ' ':
3649 case '\t':
3650 break;
3651 case '\n':
3652 if (leadingBlank && !inCode)
3653 newParagraph = true;
3654 leadingBlank = true;
3655 break;
3656 case '\\':
3657 ++i;
3658 break;
3659 case '#':
3660 if (leadingBlank && !inCode)
3661 newParagraph = true;
3662 leadingBlank = false;
3663 break;
3664 case '>':
3665 if (leadingBlank && !inCode)
3666 newParagraph = true;
3667 break;
3668 case '+':
3669 if (leadingBlank && !inCode && isFollowedBySpace(buf, i))
3670 newParagraph = true;
3671 else
3672 leadingBlank = false;
3673 break;
3674 case '0':
3675 ..
3676 case '9':
3677 if (leadingBlank && !inCode)
3678 {
3679 i = skipChars(buf, i, "0123456789");
3680 if (i < buf.length &&
3681 (buf[i] == '.' || buf[i] == ')') &&
3682 isFollowedBySpace(buf, i))
3683 newParagraph = true;
3684 else
3685 leadingBlank = false;
3686 }
3687 break;
3688 case '*':
3689 if (leadingBlank && !inCode)
3690 {
3691 newParagraph = true;
3692 if (!isFollowedBySpace(buf, i))
3693 leadingBlank = false;
3694 }
3695 break;
3696 case '`':
3697 case '~':
3698 if (leadingBlank && i+2 < buf.length && buf[i+1] == c && buf[i+2] == c)
3699 {
3700 inCode = inCode == c ? false : c;
3701 i = skipChars(buf, i, [c]) - 1;
3702 newParagraph = true;
3703 }
3704 leadingBlank = false;
3705 break;
3706 case '-':
3707 if (leadingBlank && !inCode && isFollowedBySpace(buf, i))
3708 goto case '+';
3709 else
3710 goto case '`';
3711 case '[':
3712 if (leadingBlank && !inCode && newParagraph)
3713 delimiters ~= MarkdownDelimiter(i, 1, 0, false, false, true, c);
3714 break;
3715 case ']':
3716 if (delimiters.length && !inCode &&
3717 MarkdownLink.replaceReferenceDefinition(buf, i, delimiters, cast(int) delimiters.length - 1, this))
3718 --i;
3719 break;
3720 default:
3721 if (leadingBlank)
3722 newParagraph = false;
3723 leadingBlank = false;
3724 break;
3725 }
3726 }
3727 extractedAll = true;
3728 }
3729
3730 /**
3731 * Split a string by a delimiter, excluding the delimiter.
3732 * Params:
3733 * s = the string to split
3734 * delimiter = the character to split by
3735 * Returns: the resulting array of strings
3736 */
3737 private static string[] split(string s, char delimiter) pure @safe
3738 {
3739 string[] result;
3740 size_t iStart = 0;
3741 foreach (size_t i; 0..s.length)
3742 if (s[i] == delimiter)
3743 {
3744 result ~= s[iStart..i];
3745 iStart = i + 1;
3746 }
3747 result ~= s[iStart..$];
3748 return result;
3749 }
3750
3751 ///
3752 unittest
3753 {
3754 assert(split("", ',') == [""]);
3755 assert(split("ab", ',') == ["ab"]);
3756 assert(split("a,b", ',') == ["a", "b"]);
3757 assert(split("a,,b", ',') == ["a", "", "b"]);
3758 assert(split(",ab", ',') == ["", "ab"]);
3759 assert(split("ab,", ',') == ["ab", ""]);
3760 }
3761
3762 /**
3763 * Create a HREF for the given D symbol.
3764 * The HREF is relative to the current location if possible.
3765 * Params:
3766 * symbol = the symbol to create a HREF for.
3767 * Returns: the resulting href
3768 */
3769 private string createHref(Dsymbol symbol)
3770 {
3771 Dsymbol root = symbol;
3772
3773 const(char)[] lref;
3774 while (symbol && symbol.ident && !symbol.isModule())
3775 {
3776 if (lref.length)
3777 lref = '.' ~ lref;
3778 lref = symbol.ident.toString() ~ lref;
3779 symbol = symbol.parent;
3780 }
3781
3782 const(char)[] path;
3783 if (symbol && symbol.ident && symbol.isModule() != _scope._module)
3784 {
3785 do
3786 {
3787 root = symbol;
3788
3789 // If the module has a file name, we're done
3790 if (const m = symbol.isModule())
3791 if (m.docfile)
3792 {
3793 path = m.docfile.toString();
3794 break;
3795 }
3796
3797 if (path.length)
3798 path = '_' ~ path;
3799 path = symbol.ident.toString() ~ path;
3800 symbol = symbol.parent;
3801 } while (symbol && symbol.ident);
3802
3803 if (!symbol && path.length)
3804 path ~= "$(DOC_EXTENSION)";
3805 }
3806
3807 // Attempt an absolute URL if not in the same package
3808 while (root.parent)
3809 root = root.parent;
3810 Dsymbol scopeRoot = _scope._module;
3811 while (scopeRoot.parent)
3812 scopeRoot = scopeRoot.parent;
3813 if (scopeRoot != root)
3814 {
3815 path = "$(DOC_ROOT_" ~ root.ident.toString() ~ ')' ~ path;
3816 lref = '.' ~ lref; // remote URIs like Phobos and Mir use .prefixes
3817 }
3818
3819 return cast(string) (path ~ '#' ~ lref);
3820 }
3821 }
3822
3823 enum TableColumnAlignment
3824 {
3825 none,
3826 left,
3827 center,
3828 right
3829 }
3830
3831 /****************************************************
3832 * Parse a Markdown table delimiter row in the form of `| -- | :-- | :--: | --: |`
3833 * where the example text has four columns with the following alignments:
3834 * default, left, center, and right. The first and last pipes are optional. If a
3835 * delimiter row is found it will be removed from `buf`.
3836 *
3837 * Params:
3838 * buf = an OutBuffer containing the DDoc
3839 * iStart = the index within `buf` that the delimiter row starts at
3840 * inQuote = whether the table is inside a quote
3841 * columnAlignments = alignments to populate for each column
3842 * Returns: the index of the end of the parsed delimiter, or `0` if not found
3843 */
3844 size_t parseTableDelimiterRow(ref OutBuffer buf, const size_t iStart, bool inQuote, ref TableColumnAlignment[] columnAlignments) @safe
3845 {
3846 size_t i = skipChars(buf, iStart, inQuote ? ">| \t" : "| \t");
3847 while (i < buf.length && buf[i] != '\r' && buf[i] != '\n')
3848 {
3849 const leftColon = buf[i] == ':';
3850 if (leftColon)
3851 ++i;
3852
3853 if (i >= buf.length || buf[i] != '-')
3854 break;
3855 i = skipChars(buf, i, "-");
3856
3857 const rightColon = i < buf.length && buf[i] == ':';
3858 i = skipChars(buf, i, ": \t");
3859
3860 if (i >= buf.length || (buf[i] != '|' && buf[i] != '\r' && buf[i] != '\n'))
3861 break;
3862 i = skipChars(buf, i, "| \t");
3863
3864 columnAlignments ~= (leftColon && rightColon) ? TableColumnAlignment.center :
3865 leftColon ? TableColumnAlignment.left :
3866 rightColon ? TableColumnAlignment.right :
3867 TableColumnAlignment.none;
3868 }
3869
3870 if (i < buf.length && buf[i] != '\r' && buf[i] != '\n' && buf[i] != ')')
3871 {
3872 columnAlignments.length = 0;
3873 return 0;
3874 }
3875
3876 if (i < buf.length && buf[i] == '\r') ++i;
3877 if (i < buf.length && buf[i] == '\n') ++i;
3878 return i;
3879 }
3880
3881 /****************************************************
3882 * Look for a table delimiter row, and if found parse the previous row as a
3883 * table header row. If both exist with a matching number of columns, start a
3884 * table.
3885 *
3886 * Params:
3887 * buf = an OutBuffer containing the DDoc
3888 * iStart = the index within `buf` that the table header row starts at, inclusive
3889 * iEnd = the index within `buf` that the table header row ends at, exclusive
3890 * inQuote = whether the table is inside a quote
3891 * inlineDelimiters = delimiters containing columns separators and any inline emphasis
3892 * columnAlignments = the parsed alignments for each column
3893 * Returns: the number of characters added by starting the table, or `0` if unchanged
3894 */
3895 size_t startTable(ref OutBuffer buf, size_t iStart, size_t iEnd, bool inQuote, ref MarkdownDelimiter[] inlineDelimiters, out TableColumnAlignment[] columnAlignments)
3896 {
3897 const iDelimiterRowEnd = parseTableDelimiterRow(buf, iEnd + 1, inQuote, columnAlignments);
3898 if (iDelimiterRowEnd)
3899 {
3900 size_t delta;
3901 if (replaceTableRow(buf, iStart, iEnd, inlineDelimiters, columnAlignments, true, delta))
3902 {
3903 buf.remove(iEnd + delta, iDelimiterRowEnd - iEnd);
3904 buf.insert(iEnd + delta, "$(TBODY ");
3905 buf.insert(iStart, "$(TABLE ");
3906 return delta + 15;
3907 }
3908 }
3909
3910 columnAlignments.length = 0;
3911 return 0;
3912 }
3913
3914 /****************************************************
3915 * Replace a Markdown table row in the form of table cells delimited by pipes:
3916 * `| cell | cell | cell`. The first and last pipes are optional.
3917 *
3918 * Params:
3919 * buf = an OutBuffer containing the DDoc
3920 * iStart = the index within `buf` that the table row starts at, inclusive
3921 * iEnd = the index within `buf` that the table row ends at, exclusive
3922 * inlineDelimiters = delimiters containing columns separators and any inline emphasis
3923 * columnAlignments = alignments for each column
3924 * headerRow = if `true` then the number of columns will be enforced to match
3925 * `columnAlignments.length` and the row will be surrounded by a
3926 * `THEAD` macro
3927 * delta = the number of characters added by replacing the row, or `0` if unchanged
3928 * Returns: `true` if a table row was found and replaced
3929 */
3930 bool replaceTableRow(ref OutBuffer buf, size_t iStart, size_t iEnd, ref MarkdownDelimiter[] inlineDelimiters, TableColumnAlignment[] columnAlignments, bool headerRow, out size_t delta)
3931 {
3932 delta = 0;
3933
3934 if (!columnAlignments.length || iStart == iEnd)
3935 return false;
3936
3937 iStart = skipChars(buf, iStart, " \t");
3938 int cellCount = 0;
3939 foreach (delimiter; inlineDelimiters)
3940 if (delimiter.type == '|' && !delimiter.leftFlanking)
3941 ++cellCount;
3942 bool ignoreLast = inlineDelimiters.length > 0 && inlineDelimiters[$-1].type == '|';
3943 if (ignoreLast)
3944 {
3945 const iLast = skipChars(buf, inlineDelimiters[$-1].iStart + inlineDelimiters[$-1].count, " \t");
3946 ignoreLast = iLast >= iEnd;
3947 }
3948 if (!ignoreLast)
3949 ++cellCount;
3950
3951 if (headerRow && cellCount != columnAlignments.length)
3952 return false;
3953
3954 void replaceTableCell(size_t iCellStart, size_t iCellEnd, int cellIndex, int di)
3955 {
3956 const eDelta = replaceMarkdownEmphasis(buf, inlineDelimiters, di);
3957 delta += eDelta;
3958 iCellEnd += eDelta;
3959
3960 // strip trailing whitespace and delimiter
3961 size_t i = iCellEnd - 1;
3962 while (i > iCellStart && (buf[i] == '|' || buf[i] == ' ' || buf[i] == '\t'))
3963 --i;
3964 ++i;
3965 buf.remove(i, iCellEnd - i);
3966 delta -= iCellEnd - i;
3967 iCellEnd = i;
3968
3969 buf.insert(iCellEnd, ")");
3970 ++delta;
3971
3972 // strip initial whitespace and delimiter
3973 i = skipChars(buf, iCellStart, "| \t");
3974 buf.remove(iCellStart, i - iCellStart);
3975 delta -= i - iCellStart;
3976
3977 switch (columnAlignments[cellIndex])
3978 {
3979 case TableColumnAlignment.none:
3980 buf.insert(iCellStart, headerRow ? "$(TH " : "$(TD ");
3981 delta += 5;
3982 break;
3983 case TableColumnAlignment.left:
3984 buf.insert(iCellStart, "left, ");
3985 delta += 6;
3986 goto default;
3987 case TableColumnAlignment.center:
3988 buf.insert(iCellStart, "center, ");
3989 delta += 8;
3990 goto default;
3991 case TableColumnAlignment.right:
3992 buf.insert(iCellStart, "right, ");
3993 delta += 7;
3994 goto default;
3995 default:
3996 buf.insert(iCellStart, headerRow ? "$(TH_ALIGN " : "$(TD_ALIGN ");
3997 delta += 11;
3998 break;
3999 }
4000 }
4001
4002 int cellIndex = cellCount - 1;
4003 size_t iCellEnd = iEnd;
4004 foreach_reverse (di, delimiter; inlineDelimiters)
4005 {
4006 if (delimiter.type == '|')
4007 {
4008 if (ignoreLast && di == inlineDelimiters.length-1)
4009 {
4010 ignoreLast = false;
4011 continue;
4012 }
4013
4014 if (cellIndex >= columnAlignments.length)
4015 {
4016 // kill any extra cells
4017 buf.remove(delimiter.iStart, iEnd + delta - delimiter.iStart);
4018 delta -= iEnd + delta - delimiter.iStart;
4019 iCellEnd = iEnd + delta;
4020 --cellIndex;
4021 continue;
4022 }
4023
4024 replaceTableCell(delimiter.iStart, iCellEnd, cellIndex, cast(int) di);
4025 iCellEnd = delimiter.iStart;
4026 --cellIndex;
4027 }
4028 }
4029
4030 // if no starting pipe, replace from the start
4031 if (cellIndex >= 0)
4032 replaceTableCell(iStart, iCellEnd, cellIndex, 0);
4033
4034 buf.insert(iEnd + delta, ")");
4035 buf.insert(iStart, "$(TR ");
4036 delta += 6;
4037
4038 if (headerRow)
4039 {
4040 buf.insert(iEnd + delta, ")");
4041 buf.insert(iStart, "$(THEAD ");
4042 delta += 9;
4043 }
4044
4045 return true;
4046 }
4047
4048 /****************************************************
4049 * End a table, if in one.
4050 *
4051 * Params:
4052 * buf = an OutBuffer containing the DDoc
4053 * i = the index within `buf` to end the table at
4054 * columnAlignments = alignments for each column; upon return is set to length `0`
4055 * Returns: the number of characters added by ending the table, or `0` if unchanged
4056 */
4057 size_t endTable(ref OutBuffer buf, size_t i, ref TableColumnAlignment[] columnAlignments)
4058 {
4059 if (!columnAlignments.length)
4060 return 0;
4061
4062 buf.insert(i, "))");
4063 columnAlignments.length = 0;
4064 return 2;
4065 }
4066
4067 /****************************************************
4068 * End a table row and then the table itself.
4069 *
4070 * Params:
4071 * buf = an OutBuffer containing the DDoc
4072 * iStart = the index within `buf` that the table row starts at, inclusive
4073 * iEnd = the index within `buf` that the table row ends at, exclusive
4074 * inlineDelimiters = delimiters containing columns separators and any inline emphasis
4075 * columnAlignments = alignments for each column; upon return is set to length `0`
4076 * Returns: the number of characters added by replacing the row, or `0` if unchanged
4077 */
4078 size_t endRowAndTable(ref OutBuffer buf, size_t iStart, size_t iEnd, ref MarkdownDelimiter[] inlineDelimiters, ref TableColumnAlignment[] columnAlignments)
4079 {
4080 size_t delta;
4081 replaceTableRow(buf, iStart, iEnd, inlineDelimiters, columnAlignments, false, delta);
4082 delta += endTable(buf, iEnd + delta, columnAlignments);
4083 return delta;
4084 }
4085
4086 /**************************************************
4087 * Highlight text section.
4088 *
4089 * Params:
4090 * scope = the current parse scope
4091 * a = an array of D symbols at the current scope
4092 * 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.
4093 * buf = an OutBuffer containing the DDoc
4094 * offset = the index within buf to start highlighting
4095 */
4096 void highlightText(Scope* sc, Dsymbols* a, Loc loc, ref OutBuffer buf, size_t offset)
4097 {
4098 loc.nextLine();
4099
4100 //printf("highlightText()\n");
4101 bool leadingBlank = true;
4102 size_t iParagraphStart = offset;
4103 size_t iPrecedingBlankLine = 0;
4104 int headingLevel = 0;
4105 int headingMacroLevel = 0;
4106 int quoteLevel = 0;
4107 bool lineQuoted = false;
4108 int quoteMacroLevel = 0;
4109 MarkdownList[] nestedLists;
4110 MarkdownDelimiter[] inlineDelimiters;
4111 MarkdownLinkReferences linkReferences;
4112 TableColumnAlignment[] columnAlignments;
4113 bool tableRowDetected = false;
4114 int inCode = 0;
4115 int inBacktick = 0;
4116 int macroLevel = 0;
4117 int previousMacroLevel = 0;
4118 int parenLevel = 0;
4119 size_t iCodeStart = 0; // start of code section
4120 size_t codeFenceLength = 0;
4121 size_t codeIndent = 0;
4122 string codeLanguage;
4123 size_t iLineStart = offset;
4124 linkReferences._scope = sc;
4125 for (size_t i = offset; i < buf.length; i++)
4126 {
4127 char c = buf[i];
4128 Lcont:
4129 switch (c)
4130 {
4131 case ' ':
4132 case '\t':
4133 break;
4134 case '\n':
4135 if (inBacktick)
4136 {
4137 // `inline code` is only valid if contained on a single line
4138 // otherwise, the backticks should be output literally.
4139 //
4140 // This lets things like `output from the linker' display
4141 // unmolested while keeping the feature consistent with GitHub.
4142 inBacktick = false;
4143 inCode = false; // the backtick also assumes we're in code
4144 // Nothing else is necessary since the DDOC_BACKQUOTED macro is
4145 // inserted lazily at the close quote, meaning the rest of the
4146 // text is already OK.
4147 }
4148 if (headingLevel)
4149 {
4150 i += replaceMarkdownEmphasis(buf, inlineDelimiters);
4151 endMarkdownHeading(buf, iParagraphStart, i, headingLevel);
4152 removeBlankLineMacro(buf, iPrecedingBlankLine, i);
4153 ++i;
4154 iParagraphStart = skipChars(buf, i, " \t\r\n");
4155 }
4156
4157 if (tableRowDetected && !columnAlignments.length)
4158 i += startTable(buf, iLineStart, i, lineQuoted, inlineDelimiters, columnAlignments);
4159 else if (columnAlignments.length)
4160 {
4161 size_t delta;
4162 if (replaceTableRow(buf, iLineStart, i, inlineDelimiters, columnAlignments, false, delta))
4163 i += delta;
4164 else
4165 i += endTable(buf, i, columnAlignments);
4166 }
4167
4168 if (!inCode && nestedLists.length && !quoteLevel)
4169 MarkdownList.handleSiblingOrEndingList(buf, i, iParagraphStart, nestedLists);
4170
4171 iPrecedingBlankLine = 0;
4172 if (!inCode && i == iLineStart && i + 1 < buf.length) // if "\n\n"
4173 {
4174 i += endTable(buf, i, columnAlignments);
4175 if (!lineQuoted && quoteLevel)
4176 endAllListsAndQuotes(buf, i, nestedLists, quoteLevel, quoteMacroLevel);
4177 i += replaceMarkdownEmphasis(buf, inlineDelimiters);
4178
4179 // if we don't already know about this paragraph break then
4180 // insert a blank line and record the paragraph break
4181 if (iParagraphStart <= i)
4182 {
4183 iPrecedingBlankLine = i;
4184 i = buf.insert(i, "$(DDOC_BLANKLINE)");
4185 iParagraphStart = i + 1;
4186 }
4187 }
4188 else if (inCode &&
4189 i == iLineStart &&
4190 i + 1 < buf.length &&
4191 !lineQuoted &&
4192 quoteLevel) // if "\n\n" in quoted code
4193 {
4194 inCode = false;
4195 i = buf.insert(i, ")");
4196 i += endAllMarkdownQuotes(buf, i, quoteLevel);
4197 quoteMacroLevel = 0;
4198 }
4199 leadingBlank = true;
4200 lineQuoted = false;
4201 tableRowDetected = false;
4202 iLineStart = i + 1;
4203 loc.nextLine();
4204
4205 // update the paragraph start if we just entered a macro
4206 if (previousMacroLevel < macroLevel && iParagraphStart < iLineStart)
4207 iParagraphStart = iLineStart;
4208 previousMacroLevel = macroLevel;
4209 break;
4210
4211 case '<':
4212 {
4213 leadingBlank = false;
4214 if (inCode)
4215 break;
4216 const slice = buf[];
4217 auto p = &slice[i];
4218 const se = sc._module.escapetable.escapeChar('<');
4219 if (se == "&lt;")
4220 {
4221 // Generating HTML
4222 // Skip over comments
4223 if (p[1] == '!' && p[2] == '-' && p[3] == '-')
4224 {
4225 size_t j = i + 4;
4226 p += 4;
4227 while (1)
4228 {
4229 if (j == slice.length)
4230 goto L1;
4231 if (p[0] == '-' && p[1] == '-' && p[2] == '>')
4232 {
4233 i = j + 2; // place on closing '>'
4234 break;
4235 }
4236 j++;
4237 p++;
4238 }
4239 break;
4240 }
4241 // Skip over HTML tag
4242 if (isalpha(p[1]) || (p[1] == '/' && isalpha(p[2])))
4243 {
4244 size_t j = i + 2;
4245 p += 2;
4246 while (1)
4247 {
4248 if (j == slice.length)
4249 break;
4250 if (p[0] == '>')
4251 {
4252 i = j; // place on closing '>'
4253 break;
4254 }
4255 j++;
4256 p++;
4257 }
4258 break;
4259 }
4260 }
4261 L1:
4262 // Replace '<' with '&lt;' character entity
4263 if (se.length)
4264 {
4265 buf.remove(i, 1);
4266 i = buf.insert(i, se);
4267 i--; // point to ';'
4268 }
4269 break;
4270 }
4271
4272 case '>':
4273 {
4274 if (leadingBlank && (!inCode || quoteLevel))
4275 {
4276 lineQuoted = true;
4277 int lineQuoteLevel = 1;
4278 size_t iAfterDelimiters = i + 1;
4279 for (; iAfterDelimiters < buf.length; ++iAfterDelimiters)
4280 {
4281 const c0 = buf[iAfterDelimiters];
4282 if (c0 == '>')
4283 ++lineQuoteLevel;
4284 else if (c0 != ' ' && c0 != '\t')
4285 break;
4286 }
4287 if (!quoteMacroLevel)
4288 quoteMacroLevel = macroLevel;
4289 buf.remove(i, iAfterDelimiters - i);
4290
4291 if (quoteLevel < lineQuoteLevel)
4292 {
4293 i += endRowAndTable(buf, iLineStart, i, inlineDelimiters, columnAlignments);
4294 if (nestedLists.length)
4295 {
4296 const indent = getMarkdownIndent(buf, iLineStart, i);
4297 if (indent < nestedLists[$-1].contentIndent)
4298 i += MarkdownList.endAllNestedLists(buf, i, nestedLists);
4299 }
4300
4301 for (; quoteLevel < lineQuoteLevel; ++quoteLevel)
4302 {
4303 i = buf.insert(i, "$(BLOCKQUOTE\n");
4304 iLineStart = iParagraphStart = i;
4305 }
4306 --i;
4307 }
4308 else
4309 {
4310 --i;
4311 if (nestedLists.length)
4312 MarkdownList.handleSiblingOrEndingList(buf, i, iParagraphStart, nestedLists);
4313 }
4314 break;
4315 }
4316
4317 leadingBlank = false;
4318 if (inCode)
4319 break;
4320 // Replace '>' with '&gt;' character entity
4321 const se = sc._module.escapetable.escapeChar('>');
4322 if (se.length)
4323 {
4324 buf.remove(i, 1);
4325 i = buf.insert(i, se);
4326 i--; // point to ';'
4327 }
4328 break;
4329 }
4330
4331 case '&':
4332 {
4333 leadingBlank = false;
4334 if (inCode)
4335 break;
4336 char* p = cast(char*)&buf[].ptr[i];
4337 if (p[1] == '#' || isalpha(p[1]))
4338 break;
4339 // already a character entity
4340 // Replace '&' with '&amp;' character entity
4341 const se = sc._module.escapetable.escapeChar('&');
4342 if (se)
4343 {
4344 buf.remove(i, 1);
4345 i = buf.insert(i, se);
4346 i--; // point to ';'
4347 }
4348 break;
4349 }
4350
4351 case '`':
4352 {
4353 const iAfterDelimiter = skipChars(buf, i, "`");
4354 const count = iAfterDelimiter - i;
4355
4356 if (inBacktick == count)
4357 {
4358 inBacktick = 0;
4359 inCode = 0;
4360 OutBuffer codebuf;
4361 codebuf.write(buf[iCodeStart + count .. i]);
4362 // escape the contents, but do not perform highlighting except for DDOC_PSYMBOL
4363 highlightCode(sc, a, codebuf, 0);
4364 escapeStrayParenthesis(loc, codebuf, 0, false, sc.eSink);
4365 buf.remove(iCodeStart, i - iCodeStart + count); // also trimming off the current `
4366 immutable pre = "$(DDOC_BACKQUOTED ";
4367 i = buf.insert(iCodeStart, pre);
4368 i = buf.insert(i, codebuf[]);
4369 i = buf.insert(i, ")");
4370 i--; // point to the ending ) so when the for loop does i++, it will see the next character
4371 break;
4372 }
4373
4374 // Perhaps we're starting or ending a Markdown code block
4375 if (leadingBlank && count >= 3)
4376 {
4377 bool moreBackticks = false;
4378 for (size_t j = iAfterDelimiter; !moreBackticks && j < buf.length; ++j)
4379 if (buf[j] == '`')
4380 moreBackticks = true;
4381 else if (buf[j] == '\r' || buf[j] == '\n')
4382 break;
4383 if (!moreBackticks)
4384 goto case '-';
4385 }
4386
4387 if (inCode)
4388 {
4389 if (inBacktick)
4390 i = iAfterDelimiter - 1;
4391 break;
4392 }
4393 inCode = c;
4394 inBacktick = cast(int) count;
4395 codeIndent = 0; // inline code is not indented
4396 // All we do here is set the code flags and record
4397 // the location. The macro will be inserted lazily
4398 // so we can easily cancel the inBacktick if we come
4399 // across a newline character.
4400 iCodeStart = i;
4401 i = iAfterDelimiter - 1;
4402 break;
4403 }
4404
4405 case '#':
4406 {
4407 /* A line beginning with # indicates an ATX-style heading. */
4408 if (leadingBlank && !inCode)
4409 {
4410 leadingBlank = false;
4411
4412 headingLevel = detectAtxHeadingLevel(buf, i);
4413 if (!headingLevel)
4414 break;
4415
4416 i += endRowAndTable(buf, iLineStart, i, inlineDelimiters, columnAlignments);
4417 if (!lineQuoted && quoteLevel)
4418 i += endAllListsAndQuotes(buf, iLineStart, nestedLists, quoteLevel, quoteMacroLevel);
4419
4420 // remove the ### prefix, including whitespace
4421 i = skipChars(buf, i + headingLevel, " \t");
4422 buf.remove(iLineStart, i - iLineStart);
4423 i = iParagraphStart = iLineStart;
4424
4425 removeAnyAtxHeadingSuffix(buf, i);
4426 --i;
4427
4428 headingMacroLevel = macroLevel;
4429 }
4430 break;
4431 }
4432
4433 case '~':
4434 {
4435 if (leadingBlank)
4436 {
4437 // Perhaps we're starting or ending a Markdown code block
4438 const iAfterDelimiter = skipChars(buf, i, "~");
4439 if (iAfterDelimiter - i >= 3)
4440 goto case '-';
4441 }
4442 leadingBlank = false;
4443 break;
4444 }
4445
4446 case '-':
4447 /* A line beginning with --- delimits a code section.
4448 * inCode tells us if it is start or end of a code section.
4449 */
4450 if (leadingBlank)
4451 {
4452 if (!inCode && c == '-')
4453 {
4454 const list = MarkdownList.parseItem(buf, iLineStart, i);
4455 if (list.isValid)
4456 {
4457 if (replaceMarkdownThematicBreak(buf, i, iLineStart))
4458 {
4459 removeBlankLineMacro(buf, iPrecedingBlankLine, i);
4460 iParagraphStart = skipChars(buf, i+1, " \t\r\n");
4461 break;
4462 }
4463 else
4464 goto case '+';
4465 }
4466 }
4467
4468 size_t istart = i;
4469 size_t eollen = 0;
4470 leadingBlank = false;
4471 const c0 = c; // if we jumped here from case '`' or case '~'
4472 size_t iInfoString = 0;
4473 if (!inCode)
4474 codeLanguage.length = 0;
4475 while (1)
4476 {
4477 ++i;
4478 if (i >= buf.length)
4479 break;
4480 c = buf[i];
4481 if (c == '\n')
4482 {
4483 eollen = 1;
4484 break;
4485 }
4486 if (c == '\r')
4487 {
4488 eollen = 1;
4489 if (i + 1 >= buf.length)
4490 break;
4491 if (buf[i + 1] == '\n')
4492 {
4493 eollen = 2;
4494 break;
4495 }
4496 }
4497 // BUG: handle UTF PS and LS too
4498 if (c != c0 || iInfoString)
4499 {
4500 if (!iInfoString && !inCode && i - istart >= 3)
4501 {
4502 // Start a Markdown info string, like ```ruby
4503 codeFenceLength = i - istart;
4504 i = iInfoString = skipChars(buf, i, " \t");
4505 }
4506 else if (iInfoString && c != '`')
4507 {
4508 if (!codeLanguage.length && (c == ' ' || c == '\t'))
4509 codeLanguage = cast(string) buf[iInfoString..i].idup;
4510 }
4511 else
4512 {
4513 iInfoString = 0;
4514 goto Lcont;
4515 }
4516 }
4517 }
4518 if (i - istart < 3 || (inCode && (inCode != c0 || (inCode != '-' && i - istart < codeFenceLength))))
4519 goto Lcont;
4520 if (iInfoString)
4521 {
4522 if (!codeLanguage.length)
4523 codeLanguage = cast(string) buf[iInfoString..i].idup;
4524 }
4525 else
4526 codeFenceLength = i - istart;
4527
4528 // We have the start/end of a code section
4529 // Remove the entire --- line, including blanks and \n
4530 buf.remove(iLineStart, i - iLineStart + eollen);
4531 i = iLineStart;
4532 if (eollen)
4533 leadingBlank = true;
4534 if (inCode && (i <= iCodeStart))
4535 {
4536 // Empty code section, just remove it completely.
4537 inCode = 0;
4538 break;
4539 }
4540 if (inCode)
4541 {
4542 inCode = 0;
4543 // The code section is from iCodeStart to i
4544 OutBuffer codebuf;
4545 codebuf.write(buf[iCodeStart .. i]);
4546 codebuf.writeByte(0);
4547 // Remove leading indentations from all lines
4548 bool lineStart = true;
4549 char* endp = cast(char*)codebuf[].ptr + codebuf.length;
4550 for (char* p = cast(char*)codebuf[].ptr; p < endp;)
4551 {
4552 if (lineStart)
4553 {
4554 size_t j = codeIndent;
4555 char* q = p;
4556 while (j-- > 0 && q < endp && isIndentWS(q))
4557 ++q;
4558 codebuf.remove(p - cast(char*)codebuf[].ptr, q - p);
4559 assert(cast(char*)codebuf[].ptr <= p);
4560 assert(p < cast(char*)codebuf[].ptr + codebuf.length);
4561 lineStart = false;
4562 endp = cast(char*)codebuf[].ptr + codebuf.length; // update
4563 continue;
4564 }
4565 if (*p == '\n')
4566 lineStart = true;
4567 ++p;
4568 }
4569 if (!codeLanguage.length || codeLanguage == "dlang" || codeLanguage == "d")
4570 highlightCode2(sc, a, codebuf, 0);
4571 else
4572 codebuf.remove(codebuf.length-1, 1); // remove the trailing 0 byte
4573 escapeStrayParenthesis(loc, codebuf, 0, false, sc.eSink);
4574 buf.remove(iCodeStart, i - iCodeStart);
4575 i = buf.insert(iCodeStart, codebuf[]);
4576 i = buf.insert(i, ")\n");
4577 i -= 2; // in next loop, c should be '\n'
4578 }
4579 else
4580 {
4581 i += endRowAndTable(buf, iLineStart, i, inlineDelimiters, columnAlignments);
4582 if (!lineQuoted && quoteLevel)
4583 {
4584 const delta = endAllListsAndQuotes(buf, iLineStart, nestedLists, quoteLevel, quoteMacroLevel);
4585 i += delta;
4586 istart += delta;
4587 }
4588
4589 inCode = c0;
4590 codeIndent = istart - iLineStart; // save indent count
4591 if (codeLanguage.length && codeLanguage != "dlang" && codeLanguage != "d")
4592 {
4593 // backslash-escape
4594 for (size_t j; j < codeLanguage.length - 1; ++j)
4595 if (codeLanguage[j] == '\\' && ispunct(codeLanguage[j + 1]))
4596 codeLanguage = codeLanguage[0..j] ~ codeLanguage[j + 1..$];
4597
4598 i = buf.insert(i, "$(OTHER_CODE ");
4599 i = buf.insert(i, codeLanguage);
4600 i = buf.insert(i, ",");
4601 }
4602 else
4603 i = buf.insert(i, "$(D_CODE ");
4604 iCodeStart = i;
4605 i--; // place i on >
4606 leadingBlank = true;
4607 }
4608 }
4609 break;
4610
4611 case '_':
4612 {
4613 if (leadingBlank && !inCode && replaceMarkdownThematicBreak(buf, i, iLineStart))
4614 {
4615 i += endRowAndTable(buf, iLineStart, i, inlineDelimiters, columnAlignments);
4616 if (!lineQuoted && quoteLevel)
4617 i += endAllListsAndQuotes(buf, iLineStart, nestedLists, quoteLevel, quoteMacroLevel);
4618 removeBlankLineMacro(buf, iPrecedingBlankLine, i);
4619 iParagraphStart = skipChars(buf, i+1, " \t\r\n");
4620 break;
4621 }
4622 goto default;
4623 }
4624
4625 case '+':
4626 case '0':
4627 ..
4628 case '9':
4629 {
4630 if (leadingBlank && !inCode)
4631 {
4632 MarkdownList list = MarkdownList.parseItem(buf, iLineStart, i);
4633 if (list.isValid)
4634 {
4635 // Avoid starting a numbered list in the middle of a paragraph
4636 if (!nestedLists.length && list.orderedStart.length &&
4637 iParagraphStart < iLineStart)
4638 {
4639 i += list.orderedStart.length - 1;
4640 break;
4641 }
4642
4643 i += endRowAndTable(buf, iLineStart, i, inlineDelimiters, columnAlignments);
4644 if (!lineQuoted && quoteLevel)
4645 {
4646 const delta = endAllListsAndQuotes(buf, iLineStart, nestedLists, quoteLevel, quoteMacroLevel);
4647 i += delta;
4648 list.iStart += delta;
4649 list.iContentStart += delta;
4650 }
4651
4652 list.macroLevel = macroLevel;
4653 list.startItem(buf, iLineStart, i, iPrecedingBlankLine, nestedLists);
4654 break;
4655 }
4656 }
4657 leadingBlank = false;
4658 break;
4659 }
4660
4661 case '*':
4662 {
4663 if (inCode || inBacktick)
4664 {
4665 leadingBlank = false;
4666 break;
4667 }
4668
4669 if (leadingBlank)
4670 {
4671 // Check for a thematic break
4672 if (replaceMarkdownThematicBreak(buf, i, iLineStart))
4673 {
4674 i += endRowAndTable(buf, iLineStart, i, inlineDelimiters, columnAlignments);
4675 if (!lineQuoted && quoteLevel)
4676 i += endAllListsAndQuotes(buf, iLineStart, nestedLists, quoteLevel, quoteMacroLevel);
4677 removeBlankLineMacro(buf, iPrecedingBlankLine, i);
4678 iParagraphStart = skipChars(buf, i+1, " \t\r\n");
4679 break;
4680 }
4681
4682 // An initial * indicates a Markdown list item
4683 const list = MarkdownList.parseItem(buf, iLineStart, i);
4684 if (list.isValid)
4685 goto case '+';
4686 }
4687
4688 // Markdown emphasis
4689 const leftC = i > offset ? buf[i-1] : '\0';
4690 size_t iAfterEmphasis = skipChars(buf, i+1, "*");
4691 const rightC = iAfterEmphasis < buf.length ? buf[iAfterEmphasis] : '\0';
4692 int count = cast(int) (iAfterEmphasis - i);
4693 const leftFlanking = (rightC != '\0' && !isspace(rightC)) && (!ispunct(rightC) || leftC == '\0' || isspace(leftC) || ispunct(leftC));
4694 const rightFlanking = (leftC != '\0' && !isspace(leftC)) && (!ispunct(leftC) || rightC == '\0' || isspace(rightC) || ispunct(rightC));
4695 auto emphasis = MarkdownDelimiter(i, count, macroLevel, leftFlanking, rightFlanking, false, c);
4696
4697 if (!emphasis.leftFlanking && !emphasis.rightFlanking)
4698 {
4699 i = iAfterEmphasis - 1;
4700 break;
4701 }
4702
4703 inlineDelimiters ~= emphasis;
4704 i += emphasis.count;
4705 --i;
4706 break;
4707 }
4708
4709 case '!':
4710 {
4711 leadingBlank = false;
4712
4713 if (inCode)
4714 break;
4715
4716 if (i < buf.length-1 && buf[i+1] == '[')
4717 {
4718 const imageStart = MarkdownDelimiter(i, 2, macroLevel, false, false, false, c);
4719 inlineDelimiters ~= imageStart;
4720 ++i;
4721 }
4722 break;
4723 }
4724 case '[':
4725 {
4726 if (inCode)
4727 {
4728 leadingBlank = false;
4729 break;
4730 }
4731
4732 const leftC = i > offset ? buf[i-1] : '\0';
4733 const rightFlanking = leftC != '\0' && !isspace(leftC) && !ispunct(leftC);
4734 const atParagraphStart = leadingBlank && iParagraphStart >= iLineStart;
4735 const linkStart = MarkdownDelimiter(i, 1, macroLevel, false, rightFlanking, atParagraphStart, c);
4736 inlineDelimiters ~= linkStart;
4737 leadingBlank = false;
4738 break;
4739 }
4740 case ']':
4741 {
4742 leadingBlank = false;
4743
4744 if (inCode)
4745 break;
4746
4747 for (int d = cast(int) inlineDelimiters.length - 1; d >= 0; --d)
4748 {
4749 const delimiter = inlineDelimiters[d];
4750 if (delimiter.type == '[' || delimiter.type == '!')
4751 {
4752 if (delimiter.isValid &&
4753 MarkdownLink.replaceLink(buf, i, inlineDelimiters, d, linkReferences))
4754 {
4755 // if we removed a reference link then we're at line start
4756 if (i <= delimiter.iStart)
4757 leadingBlank = true;
4758
4759 // don't nest links
4760 if (delimiter.type == '[')
4761 for (--d; d >= 0; --d)
4762 if (inlineDelimiters[d].type == '[')
4763 inlineDelimiters[d].invalidate();
4764 }
4765 else
4766 {
4767 // nothing found, so kill the delimiter
4768 inlineDelimiters = inlineDelimiters[0..d] ~ inlineDelimiters[d+1..$];
4769 }
4770 break;
4771 }
4772 }
4773 break;
4774 }
4775
4776 case '|':
4777 {
4778 if (inCode)
4779 {
4780 leadingBlank = false;
4781 break;
4782 }
4783
4784 tableRowDetected = true;
4785 inlineDelimiters ~= MarkdownDelimiter(i, 1, macroLevel, leadingBlank, false, false, c);
4786 leadingBlank = false;
4787 break;
4788 }
4789
4790 case '\\':
4791 {
4792 leadingBlank = false;
4793 if (inCode || i+1 >= buf.length)
4794 break;
4795
4796 /* Escape Markdown special characters */
4797 char c1 = buf[i+1];
4798 if (ispunct(c1))
4799 {
4800 buf.remove(i, 1);
4801
4802 auto se = sc._module.escapetable.escapeChar(c1);
4803 if (!se)
4804 se = c1 == '$' ? "$(DOLLAR)" : c1 == ',' ? "$(COMMA)" : null;
4805 if (se)
4806 {
4807 buf.remove(i, 1);
4808 i = buf.insert(i, se);
4809 i--; // point to escaped char
4810 }
4811 }
4812 break;
4813 }
4814
4815 case '$':
4816 {
4817 /* Look for the start of a macro, '$(Identifier'
4818 */
4819 leadingBlank = false;
4820 if (inCode || inBacktick)
4821 break;
4822 const slice = buf[];
4823 auto p = &slice[i];
4824 if (p[1] == '(' && isIdStart(&p[2]))
4825 ++macroLevel;
4826 break;
4827 }
4828
4829 case '(':
4830 {
4831 if (!inCode && i > offset && buf[i-1] != '$')
4832 ++parenLevel;
4833 break;
4834 }
4835
4836 case ')':
4837 { /* End of macro
4838 */
4839 leadingBlank = false;
4840 if (inCode || inBacktick)
4841 break;
4842 if (parenLevel > 0)
4843 --parenLevel;
4844 else if (macroLevel)
4845 {
4846 int downToLevel = cast(int) inlineDelimiters.length;
4847 while (downToLevel > 0 && inlineDelimiters[downToLevel - 1].macroLevel >= macroLevel)
4848 --downToLevel;
4849 if (headingLevel && headingMacroLevel >= macroLevel)
4850 {
4851 endMarkdownHeading(buf, iParagraphStart, i, headingLevel);
4852 removeBlankLineMacro(buf, iPrecedingBlankLine, i);
4853 }
4854 i += endRowAndTable(buf, iLineStart, i, inlineDelimiters, columnAlignments);
4855 while (nestedLists.length && nestedLists[$-1].macroLevel >= macroLevel)
4856 {
4857 i = buf.insert(i, ")\n)");
4858 --nestedLists.length;
4859 }
4860 if (quoteLevel && quoteMacroLevel >= macroLevel)
4861 i += endAllMarkdownQuotes(buf, i, quoteLevel);
4862 i += replaceMarkdownEmphasis(buf, inlineDelimiters, downToLevel);
4863
4864 --macroLevel;
4865 quoteMacroLevel = 0;
4866 }
4867 break;
4868 }
4869
4870 default:
4871 leadingBlank = false;
4872 if (sc._module.filetype == FileType.ddoc || inCode)
4873 break;
4874 const start = cast(char*)buf[].ptr + i;
4875 if (isIdStart(start))
4876 {
4877 size_t j = skippastident(buf, i);
4878 if (i < j)
4879 {
4880 size_t k = skippastURL(buf, i);
4881 if (i < k)
4882 {
4883 /* The URL is buf[i..k]
4884 */
4885 if (macroLevel)
4886 /* Leave alone if already in a macro
4887 */
4888 i = k - 1;
4889 else
4890 {
4891 /* Replace URL with '$(DDOC_LINK_AUTODETECT URL)'
4892 */
4893 i = buf.bracket(i, "$(DDOC_LINK_AUTODETECT ", k, ")") - 1;
4894 }
4895 break;
4896 }
4897 }
4898 else
4899 break;
4900 size_t len = j - i;
4901 // leading '_' means no highlight unless it's a reserved symbol name
4902 if (c == '_' && (i == 0 || !isdigit(*(start - 1))) && (i == buf.length - 1 || !isReservedName(start[0 .. len])))
4903 {
4904 buf.remove(i, 1);
4905 i = buf.bracket(i, "$(DDOC_AUTO_PSYMBOL_SUPPRESS ", j - 1, ")") - 1;
4906 break;
4907 }
4908 if (isIdentifier(a, start[0 .. len]))
4909 {
4910 i = buf.bracket(i, "$(DDOC_AUTO_PSYMBOL ", j, ")") - 1;
4911 break;
4912 }
4913 if (isKeyword(start[0 .. len]))
4914 {
4915 i = buf.bracket(i, "$(DDOC_AUTO_KEYWORD ", j, ")") - 1;
4916 break;
4917 }
4918 if (isFunctionParameter(a, start[0 .. len]))
4919 {
4920 //printf("highlighting arg '%s', i = %d, j = %d\n", arg.ident.toChars(), i, j);
4921 i = buf.bracket(i, "$(DDOC_AUTO_PARAM ", j, ")") - 1;
4922 break;
4923 }
4924 i = j - 1;
4925 }
4926 break;
4927 }
4928 }
4929
4930 if (inCode == '-')
4931 sc.eSink.error(loc, "unmatched `---` in DDoc comment");
4932 else if (inCode)
4933 buf.insert(buf.length, ")");
4934
4935 size_t i = buf.length;
4936 if (headingLevel)
4937 {
4938 endMarkdownHeading(buf, iParagraphStart, i, headingLevel);
4939 removeBlankLineMacro(buf, iPrecedingBlankLine, i);
4940 }
4941 i += endRowAndTable(buf, iLineStart, i, inlineDelimiters, columnAlignments);
4942 i += replaceMarkdownEmphasis(buf, inlineDelimiters);
4943 endAllListsAndQuotes(buf, i, nestedLists, quoteLevel, quoteMacroLevel);
4944 }
4945
4946 /**************************************************
4947 * Highlight code for DDOC section.
4948 */
4949 void highlightCode(Scope* sc, Dsymbol s, ref OutBuffer buf, size_t offset)
4950 {
4951 auto imp = s.isImport();
4952 if (imp && imp.aliases.length > 0)
4953 {
4954 // For example: `public import core.stdc.string : memcpy, memcmp;`
4955 for(int i = 0; i < imp.aliases.length; i++)
4956 {
4957 // Need to distinguish between
4958 // `public import core.stdc.string : memcpy, memcmp;` and
4959 // `public import core.stdc.string : copy = memcpy, compare = memcmp;`
4960 auto a = imp.aliases[i];
4961 auto id = a ? a : imp.names[i];
4962 auto loc = Loc.init;
4963 Dsymbol pscopesym;
4964 if (auto symFromId = sc.search(loc, id, pscopesym))
4965 {
4966 highlightCode(sc, symFromId, buf, offset);
4967 }
4968 }
4969 }
4970 else
4971 {
4972 OutBuffer ancbuf;
4973 emitAnchor(ancbuf, s, sc);
4974 buf.insert(offset, ancbuf[]);
4975 offset += ancbuf.length;
4976
4977 Dsymbols a;
4978 a.push(s);
4979 highlightCode(sc, &a, buf, offset);
4980 }
4981 }
4982
4983 /****************************************************
4984 */
4985 void highlightCode(Scope* sc, Dsymbols* a, ref OutBuffer buf, size_t offset)
4986 {
4987 //printf("highlightCode(a = '%s')\n", a.toChars());
4988 bool resolvedTemplateParameters = false;
4989
4990 for (size_t i = offset; i < buf.length; i++)
4991 {
4992 char c = buf[i];
4993 const se = sc._module.escapetable.escapeChar(c);
4994 if (se.length)
4995 {
4996 buf.remove(i, 1);
4997 i = buf.insert(i, se);
4998 i--; // point to ';'
4999 continue;
5000 }
5001 char* start = cast(char*)buf[].ptr + i;
5002 if (isIdStart(start))
5003 {
5004 size_t j = skipPastIdentWithDots(buf, i);
5005 if (i < j)
5006 {
5007 size_t len = j - i;
5008 if (isIdentifier(a, start[0 .. len]))
5009 {
5010 i = buf.bracket(i, "$(DDOC_PSYMBOL ", j, ")") - 1;
5011 continue;
5012 }
5013 }
5014
5015 j = skippastident(buf, i);
5016 if (i < j)
5017 {
5018 size_t len = j - i;
5019 if (isIdentifier(a, start[0 .. len]))
5020 {
5021 i = buf.bracket(i, "$(DDOC_PSYMBOL ", j, ")") - 1;
5022 continue;
5023 }
5024 if (isFunctionParameter(a, start[0 .. len]))
5025 {
5026 //printf("highlighting arg '%s', i = %d, j = %d\n", arg.ident.toChars(), i, j);
5027 i = buf.bracket(i, "$(DDOC_PARAM ", j, ")") - 1;
5028 continue;
5029 }
5030 i = j - 1;
5031 }
5032 }
5033 else if (!resolvedTemplateParameters)
5034 {
5035 size_t previ = i;
5036
5037 // hunt for template declarations:
5038 foreach (symi; 0 .. a.length)
5039 {
5040 FuncDeclaration fd = (*a)[symi].isFuncDeclaration();
5041
5042 if (!fd || !fd.parent || !fd.parent.isTemplateDeclaration())
5043 {
5044 continue;
5045 }
5046
5047 TemplateDeclaration td = fd.parent.isTemplateDeclaration();
5048
5049 // build the template parameters
5050 Array!(size_t) paramLens;
5051 paramLens.reserve(td.parameters.length);
5052
5053 OutBuffer parametersBuf;
5054 HdrGenState hgs;
5055
5056 parametersBuf.writeByte('(');
5057
5058 foreach (parami; 0 .. td.parameters.length)
5059 {
5060 TemplateParameter tp = (*td.parameters)[parami];
5061
5062 if (parami)
5063 parametersBuf.writestring(", ");
5064
5065 size_t lastOffset = parametersBuf.length;
5066
5067 toCBuffer(tp, parametersBuf, hgs);
5068
5069 paramLens[parami] = parametersBuf.length - lastOffset;
5070 }
5071 parametersBuf.writeByte(')');
5072
5073 const templateParams = parametersBuf[];
5074
5075 //printf("templateDecl: %s\ntemplateParams: %s\nstart: %s\n", td.toChars(), templateParams, start);
5076 if (start[0 .. templateParams.length] == templateParams)
5077 {
5078 immutable templateParamListMacro = "$(DDOC_TEMPLATE_PARAM_LIST ";
5079 buf.bracket(i, templateParamListMacro.ptr, i + templateParams.length, ")");
5080
5081 // We have the parameter list. While we're here we might
5082 // as well wrap the parameters themselves as well
5083
5084 // + 1 here to take into account the opening paren of the
5085 // template param list
5086 i += templateParamListMacro.length + 1;
5087
5088 foreach (const len; paramLens)
5089 {
5090 i = buf.bracket(i, "$(DDOC_TEMPLATE_PARAM ", i + len, ")");
5091 // increment two here for space + comma
5092 i += 2;
5093 }
5094
5095 resolvedTemplateParameters = true;
5096 // reset i to be positioned back before we found the template
5097 // param list this assures that anything within the template
5098 // param list that needs to be escaped or otherwise altered
5099 // has an opportunity for that to happen outside of this context
5100 i = previ;
5101
5102 continue;
5103 }
5104 }
5105 }
5106 }
5107 }
5108
5109 /****************************************
5110 */
5111 void highlightCode3(Scope* sc, ref OutBuffer buf, const(char)* p, const(char)* pend)
5112 {
5113 for (; p < pend; p++)
5114 {
5115 const se = sc._module.escapetable.escapeChar(*p);
5116 if (se.length)
5117 buf.writestring(se);
5118 else
5119 buf.writeByte(*p);
5120 }
5121 }
5122
5123 /**************************************************
5124 * Highlight code for CODE section.
5125 */
5126 void highlightCode2(Scope* sc, Dsymbols* a, ref OutBuffer buf, size_t offset)
5127 {
5128 scope eSinkNull = new ErrorSinkNull();
5129
5130 scope Lexer lex = new Lexer(null, cast(char*)buf[].ptr, 0, buf.length - 1, 0, 1,
5131 eSinkNull, // ignore errors
5132 &global.compileEnv);
5133 OutBuffer res;
5134 const(char)* lastp = cast(char*)buf[].ptr;
5135 //printf("highlightCode2('%.*s')\n", cast(int)(buf.length - 1), buf[].ptr);
5136 res.reserve(buf.length);
5137 while (1)
5138 {
5139 Token tok;
5140 lex.scan(&tok);
5141 highlightCode3(sc, res, lastp, tok.ptr);
5142 string highlight = null;
5143 switch (tok.value)
5144 {
5145 case TOK.identifier:
5146 {
5147 if (!sc)
5148 break;
5149 size_t len = lex.p - tok.ptr;
5150 if (isIdentifier(a, tok.ptr[0 .. len]))
5151 {
5152 highlight = "$(D_PSYMBOL ";
5153 break;
5154 }
5155 if (isFunctionParameter(a, tok.ptr[0 .. len]))
5156 {
5157 //printf("highlighting arg '%s', i = %d, j = %d\n", arg.ident.toChars(), i, j);
5158 highlight = "$(D_PARAM ";
5159 break;
5160 }
5161 break;
5162 }
5163 case TOK.comment:
5164 highlight = "$(D_COMMENT ";
5165 break;
5166 case TOK.string_:
5167 case TOK.interpolated:
5168 highlight = "$(D_STRING ";
5169 break;
5170 default:
5171 if (tok.isKeyword())
5172 highlight = "$(D_KEYWORD ";
5173 break;
5174 }
5175 if (highlight)
5176 {
5177 res.writestring(highlight);
5178 size_t o = res.length;
5179 highlightCode3(sc, res, tok.ptr, lex.p);
5180 if (tok.value == TOK.comment || tok.value == TOK.string_ || tok.value == TOK.interpolated)
5181 /* https://issues.dlang.org/show_bug.cgi?id=7656
5182 * https://issues.dlang.org/show_bug.cgi?id=7715
5183 * https://issues.dlang.org/show_bug.cgi?id=10519
5184 */
5185 escapeDdocString(res, o);
5186 res.writeByte(')');
5187 }
5188 else
5189 highlightCode3(sc, res, tok.ptr, lex.p);
5190 if (tok.value == TOK.endOfFile)
5191 break;
5192 lastp = lex.p;
5193 }
5194 buf.setsize(offset);
5195 buf.write(&res);
5196 }
5197
5198 /****************************************
5199 * Determine if p points to the start of a "..." parameter identifier.
5200 */
5201 bool isCVariadicArg(const(char)[] p) @nogc nothrow pure @safe
5202 {
5203 return p.length >= 3 && p[0 .. 3] == "...";
5204 }
5205
5206 /****************************************
5207 * Determine if p points to the start of an identifier.
5208 */
5209 @trusted
5210 bool isIdStart(const(char)* p) @nogc nothrow pure
5211 {
5212 import dmd.common.charactertables;
5213
5214 dchar c = *p;
5215 if (isalpha(c) || c == '_')
5216 return true;
5217 if (c >= 0x80)
5218 {
5219 size_t i = 0;
5220 if (utf_decodeChar(p[0 .. 4], i, c))
5221 return false; // ignore errors
5222 if (isAnyStart(c))
5223 return true;
5224 }
5225 return false;
5226 }
5227
5228 /****************************************
5229 * Determine if p points to the rest of an identifier.
5230 */
5231 @trusted
5232 bool isIdTail(const(char)* p) @nogc nothrow pure
5233 {
5234 import dmd.common.charactertables;
5235
5236 dchar c = *p;
5237 if (isalnum(c) || c == '_')
5238 return true;
5239 if (c >= 0x80)
5240 {
5241 size_t i = 0;
5242 if (utf_decodeChar(p[0 .. 4], i, c))
5243 return false; // ignore errors
5244 if (isAnyContinue(c))
5245 return true;
5246 }
5247 return false;
5248 }
5249
5250 /****************************************
5251 * Determine if p points to the indentation space.
5252 */
5253 bool isIndentWS(const(char)* p) @nogc nothrow pure @safe
5254 {
5255 return (*p == ' ') || (*p == '\t');
5256 }
5257
5258 /*****************************************
5259 * Return number of bytes in UTF character.
5260 */
5261 int utfStride(const(char)* p) @nogc nothrow pure
5262 {
5263 dchar c = *p;
5264 if (c < 0x80)
5265 return 1;
5266 size_t i = 0;
5267 utf_decodeChar(p[0 .. 4], i, c); // ignore errors, but still consume input
5268 return cast(int)i;
5269 }
5270
5271 inout(char)* stripLeadingNewlines(inout(char)* s) @nogc nothrow pure
5272 {
5273 while (s && *s == '\n' || *s == '\r')
5274 s++;
5275
5276 return s;
5277 }