Debian Codegraph @

gcc/d/dmd/lexer.d

raw
1 /**
2 * Implements the lexical analyzer, which converts source code into lexical tokens.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/lex.html, Lexical)
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/lexer.d, _lexer.d)
10 * Documentation: https://dlang.org/phobos/dmd_lexer.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/lexer.d
12 */
13
14 module dmd.lexer;
15
16 import core.stdc.ctype;
17 import core.stdc.stdio;
18 import core.stdc.string;
19
20 import dmd.entity;
21 import dmd.errorsink;
22 import dmd.id;
23 import dmd.identifier;
24 import dmd.location;
25 import dmd.common.smallbuffer;
26 import dmd.common.outbuffer;
27 import dmd.common.charactertables;
28 import dmd.root.array;
29 import dmd.root.ctfloat;
30 import dmd.root.port;
31 import dmd.root.rmem;
32 import dmd.root.utf;
33 import dmd.tokens;
34
35 nothrow:
36
37 /***********************************************************
38 * Values to use for various magic identifiers
39 */
40 struct CompileEnv
41 {
42 import dmd.common.charactertables;
43
44 uint versionNumber; /// __VERSION__
45 const(char)[] date; /// __DATE__
46 const(char)[] time; /// __TIME__
47 const(char)[] vendor; /// __VENDOR__
48 const(char)[] timestamp; /// __TIMESTAMP__
49
50 bool previewIn; /// `in` means `[ref] scope const`, accepts rvalues
51 bool transitionIn; /// `-transition=in` is active, `in` parameters are listed
52 bool ddocOutput; /// collect embedded documentation comments
53 bool masm; /// use MASM inline asm syntax
54
55 // these need a default otherwise tests won't work.
56 IdentifierCharLookup cCharLookupTable; /// C identifier table (set to the lexer by the C parser)
57 IdentifierCharLookup dCharLookupTable; /// D identifier table
58 }
59
60 /***********************************************************
61 */
62 class Lexer
63 {
64 private __gshared OutBuffer stringbuffer;
65
66 BaseLoc* baseLoc; // Used to generate `scanloc`, which is just an index into this data structure
67 Loc scanloc; // for error messages
68 Loc prevloc; // location of token before current
69 int linnum; // current line number
70
71 const(char)* p; // current character
72
73 Token token;
74
75 IdentifierCharLookup charLookup; /// Character table for identifiers
76
77 // For ImportC
78 bool Ccompile; /// true if compiling ImportC
79
80 // The following are valid only if (Ccompile == true)
81 ubyte boolsize; /// size of a C _Bool, default 1
82 ubyte shortsize; /// size of a C short, default 2
83 ubyte intsize; /// size of a C int, default 4
84 ubyte longsize; /// size of C long, 4 or 8
85 ubyte long_longsize; /// size of a C long long, default 8
86 ubyte long_doublesize; /// size of C long double, 8 or D real.sizeof
87 ubyte wchar_tsize; /// size of C wchar_t, 2 or 4
88
89 ErrorSink eSink; /// send error messages through this interface
90 CompileEnv compileEnv; /// environment
91
92 private
93 {
94 const(char)* base; // pointer to start of buffer
95 const(char)* end; // pointer to last element of buffer
96 const(char)* line; // start of current line
97
98 bool doDocComment; // collect doc comment information
99 bool anyToken; // seen at least one token
100 bool commentToken; // comments are TOK.comment's
101 bool tokenizeNewlines; // newlines are turned into TOK.endOfLine's
102
103 bool whitespaceToken; // tokenize whitespaces (only for DMDLIB)
104
105 int inTokenStringConstant; // can be larger than 1 when in nested q{} strings
106 int lastDocLine; // last line of previous doc comment
107
108 Token* tokenFreelist;
109 }
110
111 nothrow:
112
113 /*********************
114 * Creates a Lexer for the source code base[begoffset..endoffset+1].
115 * The last character, base[endoffset], must be null (0) or EOF (0x1A).
116 *
117 * Params:
118 * filename = used for error messages
119 * base = source code, must be terminated by a null (0) or EOF (0x1A) character
120 * begoffset = starting offset into base[]
121 * endoffset = the last offset to read into base[]
122 * doDocComment = handle documentation comments
123 * commentToken = comments become TOK.comment's
124 * errorSink = where error messages go, must not be null
125 * compileEnv = version, vendor, date, time, etc.
126 */
127 this(const(char)* filename, const(char)* base, size_t begoffset,
128 size_t endoffset, bool doDocComment, bool commentToken,
129 ErrorSink errorSink,
130 const CompileEnv* compileEnv) scope
131 {
132 // debug printf("Lexer::Lexer(%p)\n", base);
133 // debug printf("lexer.filename = %s\n", filename);
134 token = Token.init;
135 this.baseLoc = newBaseLoc(filename, base[0 .. endoffset]);
136 this.linnum = 1;
137 this.base = base;
138 this.end = base + endoffset;
139 p = base + begoffset;
140 line = p;
141 this.doDocComment = doDocComment;
142 this.commentToken = commentToken;
143 this.tokenizeNewlines = false;
144 this.inTokenStringConstant = 0;
145 this.lastDocLine = 0;
146 this.eSink = errorSink;
147 assert(errorSink);
148 if (compileEnv)
149 this.compileEnv = *compileEnv;
150 else
151 {
152 this.compileEnv.versionNumber = 1;
153 this.compileEnv.vendor = "DLF";
154 this.compileEnv.cCharLookupTable = IdentifierCharLookup.forTable(IdentifierTable.LR);
155 this.compileEnv.dCharLookupTable = IdentifierCharLookup.forTable(IdentifierTable.LR);
156 }
157 //initKeywords();
158 /* If first line starts with '#!', ignore the line
159 */
160 if (p && p[0] == '#' && p[1] == '!')
161 {
162 p += 2;
163 for (;;p++)
164 {
165 char c = *p;
166 switch (c)
167 {
168 case '\n':
169 p++;
170 goto case;
171 case 0:
172 case 0x1A:
173 break;
174
175 default:
176 // Note: We do allow malformed UTF-8 on shebang line.
177 // It could have a meaning if the native system
178 // encoding is not Unicode. See test compilable/test13512.d
179 // for example encoded in KOI-8.
180 // We also allow bidirectional control characters.
181 // We do not execute the shebang line, so it can't be used
182 // to conceal code. It is up to the shell to sanitize it.
183 continue;
184 }
185 break;
186 }
187 endOfLine();
188 }
189
190 // setup the identifier table lookup functions
191 // C tables are setup in its parser constructor
192 // Due to us not knowing if we're in C at this point in time.
193 charLookup = this.compileEnv.dCharLookupTable;
194 }
195
196 /***********************
197 * Alternative entry point for DMDLIB, adds `whitespaceToken`
198 */
199 this(const(char)* filename, const(char)* base, size_t begoffset, size_t endoffset,
200 bool doDocComment, bool commentToken, bool whitespaceToken,
201 ErrorSink errorSink, const CompileEnv* compileEnv = null
202 )
203 {
204 this(filename, base, begoffset, endoffset, doDocComment, commentToken, errorSink, compileEnv);
205 this.whitespaceToken = whitespaceToken;
206 }
207
208 /******************
209 * Used for unittests for a mock Lexer
210 */
211 this(ErrorSink errorSink) scope @safe { assert(errorSink); this.eSink = errorSink; }
212
213 /**************************************
214 * Reset lexer to lex #define's
215 */
216 final void resetDefineLines(const(char)[] slice)
217 {
218 base = slice.ptr;
219 end = base + slice.length;
220 assert(*end == 0);
221 p = base;
222 line = p;
223 tokenizeNewlines = true;
224 inTokenStringConstant = 0;
225 lastDocLine = 0;
226
227 baseLoc = newBaseLoc("#defines", slice);
228 scanloc = baseLoc.getLoc(0);
229 }
230
231 /**********************************
232 * Set up for next #define line.
233 * p should be at start of next line.
234 */
235 final void nextDefineLine()
236 {
237 tokenizeNewlines = true;
238 }
239
240 /***************
241 * Range interface
242 */
243
244 final bool empty() const pure @property @nogc @safe
245 {
246 return front() == TOK.endOfFile;
247 }
248
249 final TOK front() const pure @property @nogc @safe
250 {
251 return token.value;
252 }
253
254 final void popFront()
255 {
256 nextToken();
257 }
258
259 /// Returns: a newly allocated `Token`.
260 Token* allocateToken() pure nothrow @safe
261 {
262 if (tokenFreelist)
263 {
264 Token* t = tokenFreelist;
265 tokenFreelist = t.next;
266 t.next = null;
267 return t;
268 }
269 return new Token();
270 }
271
272 /// Frees the given token by returning it to the freelist.
273 private void releaseToken(Token* token) pure nothrow @nogc @safe
274 {
275 if (mem.isGCEnabled)
276 *token = Token.init;
277 token.next = tokenFreelist;
278 tokenFreelist = token;
279 }
280
281 final TOK nextToken()
282 {
283 prevloc = token.loc;
284 if (token.next)
285 {
286 Token* t = token.next;
287 memcpy(&token, t, Token.sizeof);
288 releaseToken(t);
289 }
290 else
291 {
292 scan(&token);
293 }
294 //printf(token.toChars());
295 return token.value;
296 }
297
298 /***********************
299 * Look ahead at next token's value.
300 */
301 final TOK peekNext()
302 {
303 return peek(&token).value;
304 }
305
306 /***********************
307 * Look 2 tokens ahead at value.
308 */
309 final TOK peekNext2()
310 {
311 Token* t = peek(&token);
312 return peek(t).value;
313 }
314
315 /****************************
316 * Turn next token in buffer into a token.
317 * Params:
318 * t = the token to set the resulting Token to
319 */
320 final void scan(Token* t)
321 {
322 const lastLine = linnum;
323 Loc startLoc;
324 t.blockComment = null;
325 t.lineComment = null;
326
327 size_t universalCharacterName4, universalCharacterName8;
328
329 while (1)
330 {
331 t.ptr = p;
332 //printf("p = %p, *p = '%c'\n",p,*p);
333 t.loc = loc();
334 switch (*p)
335 {
336 case 0:
337 case 0x1A:
338 t.value = TOK.endOfFile; // end of file
339 // Intentionally not advancing `p`, such that subsequent calls keep returning TOK.endOfFile.
340 return;
341 case ' ':
342 // Skip 4 spaces at a time after aligning 'p' to a 4-byte boundary.
343 while ((cast(size_t)p) % uint.sizeof)
344 {
345 if (*p != ' ')
346 goto LendSkipFourSpaces;
347 p++;
348 }
349 while (*(cast(uint*)p) == 0x20202020) // ' ' == 0x20
350 p += 4;
351 // Skip over any remaining space on the line.
352 while (*p == ' ')
353 p++;
354 LendSkipFourSpaces:
355 version (DMDLIB)
356 {
357 if (whitespaceToken)
358 {
359 t.value = TOK.whitespace;
360 return;
361 }
362 }
363 continue; // skip white space
364 case '\t':
365 case '\v':
366 case '\f':
367 p++;
368 version (DMDLIB)
369 {
370 if (whitespaceToken)
371 {
372 t.value = TOK.whitespace;
373 return;
374 }
375 }
376 continue; // skip white space
377 case '\r':
378 p++;
379 if (*p != '\n') // if CR stands by itself
380 {
381 endOfLine();
382 if (tokenizeNewlines)
383 {
384 t.value = TOK.endOfLine;
385 tokenizeNewlines = false;
386 return;
387 }
388 }
389 version (DMDLIB)
390 {
391 if (whitespaceToken)
392 {
393 t.value = TOK.whitespace;
394 return;
395 }
396 }
397 continue; // skip white space
398 case '\n':
399 p++;
400 endOfLine();
401 if (tokenizeNewlines)
402 {
403 t.value = TOK.endOfLine;
404 tokenizeNewlines = false;
405 return;
406 }
407 version (DMDLIB)
408 {
409 if (whitespaceToken)
410 {
411 t.value = TOK.whitespace;
412 return;
413 }
414 }
415 continue; // skip white space
416
417 case '\\':
418 if (Ccompile)
419 {
420 if (p[1] == '\r' || p[1] == '\n')
421 {
422 ++p; // ignore \ followed by new line, like VC does
423 continue;
424 }
425 else if (p[1] == 'u')
426 {
427 // Universal Character Name (C) 2 byte
428 // \uXXXX
429 // let the main case handling for identifiers process this
430
431 // case_indent will always increment, so subtract to prevent branching on the fast path
432 p--;
433
434 goto case_ident;
435 }
436 else if (p[1] == 'U')
437 {
438 // Universal Character Name (C) 4 byte
439 // \UXXXXXXXX
440 // let the main case handling for identifiers process this
441
442 // case_indent will always increment, so subtract to prevent branching on the fast path
443 p--;
444
445 goto case_ident;
446 }
447 }
448 goto default;
449
450 case '0':
451 if (!isZeroSecond(p[1])) // if numeric literal does not continue
452 {
453 ++p;
454 t.unsvalue = 0;
455 t.value = TOK.int32Literal;
456 return;
457 }
458 goto Lnumber;
459
460 case '1': .. case '9':
461 if (!isDigitSecond(p[1])) // if numeric literal does not continue
462 {
463 t.unsvalue = *p - '0';
464 ++p;
465 t.value = TOK.int32Literal;
466 return;
467 }
468 Lnumber:
469 t.value = number(t);
470 return;
471
472 case '\'':
473 if (issinglechar(p[1]) && p[2] == '\'')
474 {
475 t.unsvalue = p[1]; // simple one character literal
476 t.value = TOK.charLiteral;
477 p += 3;
478 }
479 else if (Ccompile)
480 {
481 clexerCharConstant(*t, 0);
482 }
483 else
484 {
485 t.value = charConstant(t);
486 }
487 return;
488
489 case 'u':
490 case 'U':
491 case 'L':
492 if (!Ccompile)
493 goto case_ident;
494 if (p[1] == '\'') // C wide character constant
495 {
496 char c = *p;
497 if (c == 'L') // convert L to u or U
498 c = (wchar_tsize == 4) ? 'u' : 'U';
499 ++p;
500 clexerCharConstant(*t, c);
501 return;
502 }
503 if (p[1] == '\"') // C wide string literal
504 {
505 const c = *p;
506 ++p;
507 escapeStringConstant(t);
508 t.postfix = c == 'L' ? (wchar_tsize == 2 ? 'w' : 'd') :
509 c == 'u' ? 'w' :
510 'd';
511 return;
512 }
513 if (p[1] == '8' && p[2] == '\"') // C UTF-8 string literal
514 {
515 p += 2;
516 escapeStringConstant(t);
517 return;
518 }
519 goto case_ident;
520
521 case 'r':
522 if (Ccompile || p[1] != '"')
523 goto case_ident;
524 p++;
525 goto case '`';
526 case '`':
527 if (Ccompile)
528 goto default;
529 wysiwygStringConstant(t);
530 return;
531 case 'x':
532 if (p[1] != '"')
533 goto case_ident;
534 p++;
535 t.value = hexStringConstant(t);
536 return;
537 case 'q':
538 if (Ccompile)
539 goto case_ident;
540 if (p[1] == '"')
541 {
542 p++;
543 delimitedStringConstant(t);
544 return;
545 }
546 if (p[1] == '{')
547 {
548 p++;
549 tokenStringConstant(t);
550 return;
551 }
552 goto case_ident;
553 case 'i':
554 if (Ccompile)
555 goto case_ident;
556 if (p[1] == '"')
557 {
558 p++; // skip the i
559 escapeStringConstant(t, true);
560 return;
561 }
562 if (p[1] == '`')
563 {
564 p++; // skip the i
565 wysiwygStringConstant(t, true);
566 return;
567 }
568 if (p[1] == 'q' && p[2] == '{')
569 {
570 p += 2; // skip the i and q
571 tokenStringConstant(t, true);
572 return;
573 }
574 goto case_ident;
575 case '"':
576 escapeStringConstant(t);
577 return;
578 case 'a':
579 case 'b':
580 case 'c':
581 case 'd':
582 case 'e':
583 case 'f':
584 case 'g':
585 case 'h':
586 /*case 'i':*/
587 case 'j':
588 case 'k':
589 case 'l':
590 case 'm':
591 case 'n':
592 case 'o':
593 case 'p':
594 /*case 'q': case 'r':*/
595 case 's':
596 case 't':
597 //case 'u':
598 case 'v':
599 case 'w':
600 /*case 'x':*/
601 case 'y':
602 case 'z':
603 case 'A':
604 case 'B':
605 case 'C':
606 case 'D':
607 case 'E':
608 case 'F':
609 case 'G':
610 case 'H':
611 case 'I':
612 case 'J':
613 case 'K':
614 //case 'L':
615 case 'M':
616 case 'N':
617 case 'O':
618 case 'P':
619 case 'Q':
620 case 'R':
621 case 'S':
622 case 'T':
623 //case 'U':
624 case 'V':
625 case 'W':
626 case 'X':
627 case 'Y':
628 case 'Z':
629 case '_':
630 case_ident:
631 {
632 IdentLoop: while (1)
633 {
634 // If this is changed, change the decrement in C's universal character name code above
635 // For syntax \uXXXX and \UXXXXXXXX
636 const c = *++p;
637
638 // Is this the first character of the identifier
639 // For the universal character name this will line up,
640 // for the main switch it won't since it wasn't the first,
641 // for the default it won't either because a decode increments.
642 const isStartCharacter = t.ptr is p;
643
644 if (isidchar(c))
645 continue;
646 if (c & 0x80)
647 {
648 const s = p;
649 const u = decodeUTF();
650
651 if (isStartCharacter)
652 {
653 if (charLookup.isStart(u))
654 continue;
655 error(t.loc, "character 0x%04x is not allowed as a start character in an identifier", u);
656 }
657 else
658 {
659 if (charLookup.isContinue(u))
660 continue;
661 error(t.loc, "character 0x%04x is not allowed as a continue character in an identifier", u);
662 }
663
664 p = s;
665 }
666 else if (Ccompile && c == '\\')
667 {
668 uint times;
669 const s = p;
670 p++;
671
672 if (*p == 'u')
673 {
674 // Universal Character Name (C) 2 byte
675 // \uXXXX
676 p++;
677 times = 4;
678 }
679 else if (*p == 'U')
680 {
681 // Universal Character Name (C) 4 byte
682 // \UXXXXXXXX
683 p++;
684 times = 8;
685 }
686 else
687 {
688 error(t.loc, "char 0x%x is not allowed to follow '\\' expecting a C universal character name in format \\uXXXX or \\UXXXXXXXX with hex digits instead of X with invalid u/U", *p);
689 p = s;
690 break;
691 }
692
693 foreach(_; 0 .. times)
694 {
695 const hc = *p;
696 p++;
697
698 if ((hc >= '0' && hc <= '9') || (hc >= 'a' && hc <= 'f') || (hc >= 'A' && hc <= 'F'))
699 continue;
700
701 error(t.loc, "char 0x%x is not allowed to follow '\\' expecting a C universal character name in format \\uXXXX or \\UXXXXXXXX with hex digits instead of X with invalid hex digit", hc);
702 p = s;
703 break IdentLoop;
704 }
705
706 continue;
707 }
708 break;
709 }
710
711 Identifier id;
712
713 if (universalCharacterName4 > 0 || universalCharacterName8 > 0)
714 {
715 auto priorValidation = t.ptr[0 .. p - t.ptr];
716 const(char)* priorVPtr = priorValidation.ptr;
717 const possibleLength = (
718 priorValidation.length - (
719 (universalCharacterName4 * 6) +
720 (universalCharacterName8 * 10)
721 )) + (
722 (universalCharacterName4 * 3) +
723 (universalCharacterName8 * 4)
724 );
725
726 char[64] buffer = void;
727 SmallBuffer!char sb = SmallBuffer!char(possibleLength, buffer[]);
728
729 char[] storage = sb.extent;
730 size_t offset;
731
732 while(priorVPtr < &priorValidation[$-1] + 1)
733 {
734 if (*priorVPtr == '\\')
735 {
736 dchar tempDchar = 0;
737 uint times;
738
739 // universal character name (C)
740 if (priorVPtr[1] == 'u')
741 times = 4;
742 else if (priorVPtr[1] == 'U')
743 times = 8;
744 else
745 assert(0, "ICE: Universal character name is 2 or 4 bytes only");
746 priorVPtr += 2;
747
748 foreach(_; 0 .. times)
749 {
750 char c = *++priorVPtr;
751 if (c >= '0' && c <= '9')
752 c -= '0';
753 else if (c >= 'a' && c <= 'f')
754 c -= 'a' - 10;
755 else if (c >= 'A' && c <= 'F')
756 c -= 'A' - 10;
757
758 tempDchar <<= 4;
759 tempDchar |= c;
760 }
761
762 utf_encodeChar(&storage[offset], tempDchar);
763 offset += utf_codeLengthChar(tempDchar);
764
765 // Could be an error instead of a warning,
766 // but hey it was written specifically so why worry?
767 if (priorVPtr is priorValidation.ptr)
768 {
769 if (!charLookup.isStart(tempDchar))
770 warning(t.loc, "char 0x%x is not allowed start character for an identifier", tempDchar);
771 }
772 else
773 {
774 if (!charLookup.isContinue(tempDchar))
775 warning(t.loc, "char 0x%x is not allowed continue character for an identifier", tempDchar);
776 }
777 }
778 else
779 storage[offset++] = *++priorVPtr;
780 }
781
782 id = Identifier.idPool(storage[0 .. offset], false);
783 }
784 else
785 id = Identifier.idPool((cast(char*)t.ptr)[0 .. p - t.ptr], false);
786
787 t.ident = id;
788 t.value = cast(TOK)id.getValue();
789
790 anyToken = 1;
791
792 /* Different keywords for C and D
793 */
794 if (Ccompile)
795 {
796 if (t.value != TOK.identifier)
797 {
798 t.value = Ckeywords[t.value]; // filter out D keywords
799 }
800 }
801 else if (t.value >= FirstCKeyword)
802 t.value = TOK.identifier; // filter out C keywords
803
804 else if (*t.ptr == '_') // if special identifier token
805 {
806 void toToken(const(char)[] s)
807 {
808 t.value = TOK.string_;
809 t.ustring = s.ptr;
810 t.len = cast(uint)s.length;
811 t.postfix = 0;
812 }
813
814 if (id == Id.DATE)
815 toToken(compileEnv.date);
816 else if (id == Id.TIME)
817 toToken(compileEnv.time);
818 else if (id == Id.VENDOR)
819 toToken(compileEnv.vendor);
820 else if (id == Id.TIMESTAMP)
821 toToken(compileEnv.timestamp);
822 else if (id == Id.VERSIONX)
823 {
824 t.value = TOK.int64Literal;
825 t.unsvalue = compileEnv.versionNumber;
826 }
827 else if (id == Id.EOFX)
828 {
829 t.value = TOK.endOfFile;
830 // Advance scanner to end of file
831 while (!(*p == 0 || *p == 0x1A))
832 p++;
833 }
834 }
835 //printf("t.value = %d\n",t.value);
836 return;
837 }
838 case '/':
839 p++;
840 switch (*p)
841 {
842 case '=':
843 p++;
844 t.value = TOK.divAssign;
845 return;
846 case '*':
847 p++;
848 startLoc = loc();
849 while (1)
850 {
851 while (1)
852 {
853 const c = *p;
854 switch (c)
855 {
856 case '/':
857 break;
858 case '\n':
859 endOfLine();
860 p++;
861 continue;
862 case '\r':
863 p++;
864 if (*p != '\n')
865 endOfLine();
866 continue;
867 case 0:
868 case 0x1A:
869 error(t.loc, "unterminated /* */ comment");
870 //p = end;
871 t.loc = loc();
872 t.value = TOK.endOfFile;
873 return;
874 default:
875 if (c & 0x80)
876 {
877 const u = decodeUTF();
878 if (u == PS || u == LS)
879 endOfLine();
880 }
881 p++;
882 continue;
883 }
884 break;
885 }
886 p++;
887 if (p[-2] == '*' && p - 3 != t.ptr)
888 break;
889 }
890 if (commentToken)
891 {
892 t.loc = startLoc;
893 t.value = TOK.comment;
894 return;
895 }
896 if (doDocComment && t.ptr[2] == '*' && p - 4 != t.ptr)
897 {
898 // if /** but not /**/
899 getDocComment(t, lastLine == startLoc.linnum, startLoc.linnum - lastDocLine > 1);
900 lastDocLine = linnum;
901 }
902 continue;
903 case '/': // do // style comments
904 startLoc = loc();
905 while (1)
906 {
907 const c = *++p;
908 switch (c)
909 {
910 case '\n':
911 break;
912 case '\r':
913 if (p[1] == '\n')
914 p++;
915 break;
916 case 0:
917 case 0x1A:
918 if (commentToken)
919 {
920 p = end;
921 t.loc = startLoc;
922 t.value = TOK.comment;
923 return;
924 }
925 if (doDocComment && t.ptr[2] == '/')
926 {
927 getDocComment(t, lastLine == startLoc.linnum, startLoc.linnum - lastDocLine > 1);
928 lastDocLine = linnum;
929 }
930 //p = end;
931 t.loc = loc();
932 t.value = TOK.endOfFile;
933 return;
934 default:
935 if (c & 0x80)
936 {
937 const u = decodeUTF();
938 if (u == PS || u == LS)
939 break;
940 }
941 continue;
942 }
943 break;
944 }
945 if (commentToken)
946 {
947 version (DMDLIB) {}
948 else
949 {
950 p++;
951 endOfLine();
952 }
953 t.loc = startLoc;
954 t.value = TOK.comment;
955 return;
956 }
957 if (doDocComment && t.ptr[2] == '/')
958 {
959 getDocComment(t, lastLine == startLoc.linnum, startLoc.linnum - lastDocLine > 1);
960 lastDocLine = linnum;
961 }
962 p++;
963 endOfLine();
964 continue;
965 case '+':
966 if (!Ccompile)
967 {
968 int nest;
969 startLoc = loc();
970 p++;
971 nest = 1;
972 while (1)
973 {
974 char c = *p;
975 switch (c)
976 {
977 case '/':
978 p++;
979 if (*p == '+')
980 {
981 p++;
982 nest++;
983 }
984 continue;
985 case '+':
986 p++;
987 if (*p == '/')
988 {
989 p++;
990 if (--nest == 0)
991 break;
992 }
993 continue;
994 case '\r':
995 p++;
996 if (*p != '\n')
997 endOfLine();
998 continue;
999 case '\n':
1000 endOfLine();
1001 p++;
1002 continue;
1003 case 0:
1004 case 0x1A:
1005 error(t.loc, "unterminated /+ +/ comment");
1006 //p = end;
1007 t.loc = loc();
1008 t.value = TOK.endOfFile;
1009 return;
1010 default:
1011 if (c & 0x80)
1012 {
1013 uint u = decodeUTF();
1014 if (u == PS || u == LS)
1015 endOfLine();
1016 }
1017 p++;
1018 continue;
1019 }
1020 break;
1021 }
1022 if (commentToken)
1023 {
1024 t.loc = startLoc;
1025 t.value = TOK.comment;
1026 return;
1027 }
1028 if (doDocComment && t.ptr[2] == '+' && p - 4 != t.ptr)
1029 {
1030 // if /++ but not /++/
1031 getDocComment(t, lastLine == startLoc.linnum, startLoc.linnum - lastDocLine > 1);
1032 lastDocLine = linnum;
1033 }
1034 continue;
1035 }
1036 break;
1037 default:
1038 break;
1039 }
1040 t.value = TOK.div;
1041 return;
1042 case '.':
1043 p++;
1044 if (isdigit(*p))
1045 {
1046 /* Note that we don't allow ._1 and ._ as being
1047 * valid floating point numbers.
1048 */
1049 p--;
1050 t.value = inreal(t);
1051 }
1052 else if (p[0] == '.')
1053 {
1054 if (p[1] == '.')
1055 {
1056 p += 2;
1057 t.value = TOK.dotDotDot;
1058 }
1059 else
1060 {
1061 p++;
1062 t.value = TOK.slice;
1063 }
1064 }
1065 else
1066 t.value = TOK.dot;
1067 return;
1068 case '&':
1069 p++;
1070 if (*p == '=')
1071 {
1072 p++;
1073 t.value = TOK.andAssign;
1074 }
1075 else if (*p == '&')
1076 {
1077 p++;
1078 t.value = TOK.andAnd;
1079 }
1080 else
1081 t.value = TOK.and;
1082 return;
1083 case '|':
1084 p++;
1085 if (*p == '=')
1086 {
1087 p++;
1088 t.value = TOK.orAssign;
1089 }
1090 else if (*p == '|')
1091 {
1092 p++;
1093 t.value = TOK.orOr;
1094 }
1095 else
1096 t.value = TOK.or;
1097 return;
1098 case '-':
1099 p++;
1100 if (*p == '=')
1101 {
1102 p++;
1103 t.value = TOK.minAssign;
1104 }
1105 else if (*p == '-')
1106 {
1107 p++;
1108 t.value = TOK.minusMinus;
1109 }
1110 else if (*p == '>')
1111 {
1112 ++p;
1113 t.value = TOK.arrow;
1114 }
1115 else
1116 t.value = TOK.min;
1117 return;
1118 case '+':
1119 p++;
1120 if (*p == '=')
1121 {
1122 p++;
1123 t.value = TOK.addAssign;
1124 }
1125 else if (*p == '+')
1126 {
1127 p++;
1128 t.value = TOK.plusPlus;
1129 }
1130 else
1131 t.value = TOK.add;
1132 return;
1133 case '<':
1134 p++;
1135 if (*p == '=')
1136 {
1137 p++;
1138 t.value = TOK.lessOrEqual; // <=
1139 }
1140 else if (*p == '<')
1141 {
1142 p++;
1143 if (*p == '=')
1144 {
1145 p++;
1146 t.value = TOK.leftShiftAssign; // <<=
1147 }
1148 else
1149 t.value = TOK.leftShift; // <<
1150 }
1151 else if (*p == ':' && Ccompile)
1152 {
1153 ++p;
1154 t.value = TOK.leftBracket; // <:
1155 }
1156 else if (*p == '%' && Ccompile)
1157 {
1158 ++p;
1159 t.value = TOK.leftCurly; // <%
1160 }
1161 else
1162 t.value = TOK.lessThan; // <
1163 return;
1164 case '>':
1165 p++;
1166 if (*p == '=')
1167 {
1168 p++;
1169 t.value = TOK.greaterOrEqual; // >=
1170 }
1171 else if (*p == '>')
1172 {
1173 p++;
1174 if (*p == '=')
1175 {
1176 p++;
1177 t.value = TOK.rightShiftAssign; // >>=
1178 }
1179 else if (*p == '>')
1180 {
1181 p++;
1182 if (*p == '=')
1183 {
1184 p++;
1185 t.value = TOK.unsignedRightShiftAssign; // >>>=
1186 }
1187 else
1188 t.value = TOK.unsignedRightShift; // >>>
1189 }
1190 else
1191 t.value = TOK.rightShift; // >>
1192 }
1193 else
1194 t.value = TOK.greaterThan; // >
1195 return;
1196 case '!':
1197 p++;
1198 if (*p == '=')
1199 {
1200 p++;
1201 t.value = TOK.notEqual; // !=
1202 }
1203 else
1204 t.value = TOK.not; // !
1205 return;
1206 case '=':
1207 p++;
1208 if (*p == '=')
1209 {
1210 p++;
1211 t.value = TOK.equal; // ==
1212 }
1213 else if (*p == '>')
1214 {
1215 p++;
1216 t.value = TOK.goesTo; // =>
1217 }
1218 else
1219 t.value = TOK.assign; // =
1220 return;
1221 case '~':
1222 p++;
1223 if (*p == '=')
1224 {
1225 p++;
1226 t.value = TOK.concatenateAssign; // ~=
1227 }
1228 else
1229 t.value = TOK.tilde; // ~
1230 return;
1231 case '^':
1232 p++;
1233 if (*p == '^')
1234 {
1235 p++;
1236 if (*p == '=')
1237 {
1238 p++;
1239 t.value = TOK.powAssign; // ^^=
1240 }
1241 else
1242 t.value = TOK.pow; // ^^
1243 }
1244 else if (*p == '=')
1245 {
1246 p++;
1247 t.value = TOK.xorAssign; // ^=
1248 }
1249 else
1250 t.value = TOK.xor; // ^
1251 return;
1252 case '(':
1253 p++;
1254 t.value = TOK.leftParenthesis;
1255 return;
1256 case ')':
1257 p++;
1258 t.value = TOK.rightParenthesis;
1259 return;
1260 case '[':
1261 p++;
1262 t.value = TOK.leftBracket;
1263 return;
1264 case ']':
1265 p++;
1266 t.value = TOK.rightBracket;
1267 return;
1268 case '{':
1269 p++;
1270 t.value = TOK.leftCurly;
1271 return;
1272 case '}':
1273 p++;
1274 t.value = TOK.rightCurly;
1275 return;
1276 case '?':
1277 p++;
1278 t.value = TOK.question;
1279 return;
1280 case ',':
1281 p++;
1282 t.value = TOK.comma;
1283 return;
1284 case ';':
1285 p++;
1286 t.value = TOK.semicolon;
1287 return;
1288 case ':':
1289 p++;
1290 if (*p == ':')
1291 {
1292 ++p;
1293 t.value = TOK.colonColon;
1294 }
1295 else if (*p == '>' && Ccompile)
1296 {
1297 ++p;
1298 t.value = TOK.rightBracket;
1299 }
1300 else
1301 t.value = TOK.colon;
1302 return;
1303 case '$':
1304 p++;
1305 t.value = TOK.dollar;
1306 return;
1307 case '@':
1308 p++;
1309 t.value = TOK.at;
1310 return;
1311 case '*':
1312 p++;
1313 if (*p == '=')
1314 {
1315 p++;
1316 t.value = TOK.mulAssign;
1317 }
1318 else
1319 t.value = TOK.mul;
1320 return;
1321 case '%':
1322 p++;
1323 if (*p == '=')
1324 {
1325 p++;
1326 t.value = TOK.modAssign;
1327 }
1328 else if (*p == '>' && Ccompile)
1329 {
1330 ++p;
1331 t.value = TOK.rightCurly;
1332 }
1333 else if (*p == ':' && Ccompile)
1334 {
1335 goto case '#'; // %: means #
1336 }
1337 else
1338 t.value = TOK.mod;
1339 return;
1340 case '#':
1341 {
1342 // https://issues.dlang.org/show_bug.cgi?id=22825
1343 // Special token sequences are terminated by newlines,
1344 // and should not be skipped over.
1345 this.tokenizeNewlines = true;
1346 p++;
1347 if (parseSpecialTokenSequence())
1348 continue;
1349 t.value = TOK.pound;
1350 return;
1351 }
1352 default:
1353 {
1354 dchar c = *p;
1355 if (c & 0x80)
1356 {
1357 c = decodeUTF();
1358
1359 // Check for start of an identifier
1360 if (charLookup.isStart(c))
1361 goto case_ident;
1362
1363 if (c == PS || c == LS)
1364 {
1365 endOfLine();
1366 p++;
1367 if (tokenizeNewlines)
1368 {
1369 t.value = TOK.endOfLine;
1370 tokenizeNewlines = false;
1371 return;
1372 }
1373 continue;
1374 }
1375 }
1376 if (c < 0x80 && isprint(c))
1377 error(t.loc, "character '%c' is not a valid token", c);
1378 else
1379 error(t.loc, "character 0x%02x is not a valid token", c);
1380 p++;
1381 continue;
1382 // assert(0);
1383 }
1384 }
1385 }
1386 }
1387
1388 final Token* peek(Token* ct)
1389 {
1390 Token* t;
1391 if (ct.next)
1392 t = ct.next;
1393 else
1394 {
1395 t = allocateToken();
1396 scan(t);
1397 ct.next = t;
1398 }
1399 return t;
1400 }
1401
1402 /*********************************
1403 * tk is on the opening (.
1404 * Look ahead and return token that is past the closing ).
1405 */
1406 final Token* peekPastParen(Token* tk)
1407 {
1408 //printf("peekPastParen()\n");
1409 int parens = 1;
1410 int curlynest = 0;
1411 while (1)
1412 {
1413 tk = peek(tk);
1414 //tk.print();
1415 switch (tk.value)
1416 {
1417 case TOK.leftParenthesis:
1418 parens++;
1419 continue;
1420 case TOK.rightParenthesis:
1421 --parens;
1422 if (parens)
1423 continue;
1424 tk = peek(tk);
1425 break;
1426 case TOK.leftCurly:
1427 curlynest++;
1428 continue;
1429 case TOK.rightCurly:
1430 if (--curlynest >= 0)
1431 continue;
1432 break;
1433 case TOK.semicolon:
1434 if (curlynest)
1435 continue;
1436 break;
1437 case TOK.endOfFile:
1438 break;
1439 default:
1440 continue;
1441 }
1442 return tk;
1443 }
1444 }
1445
1446 /*******************************************
1447 * Parse escape sequence.
1448 */
1449 private uint escapeSequence(out dchar c2)
1450 {
1451 return Lexer.escapeSequence(token.loc, p, Ccompile, c2);
1452 }
1453
1454 /********
1455 * Parse the given string literal escape sequence into a single character.
1456 * D https://dlang.org/spec/lex.html#escape_sequences
1457 * C11 6.4.4.4
1458 * Params:
1459 * loc = location to use for error messages
1460 * sequence = pointer to string with escape sequence to parse. Updated to
1461 * point past the end of the escape sequence
1462 * Ccompile = true for compile C11 escape sequences
1463 * c2 = returns second `dchar` of html entity with 2 code units, otherwise stays `dchar.init`
1464 * Returns:
1465 * the escape sequence as a single character
1466 */
1467 private dchar escapeSequence(Loc loc, ref const(char)* sequence, bool Ccompile, out dchar c2)
1468 {
1469 const(char)* p = sequence; // cache sequence reference on stack
1470 scope(exit) sequence = p;
1471
1472 uint c = *p;
1473 int ndigits;
1474 switch (c)
1475 {
1476 case '\'':
1477 case '"':
1478 case '?':
1479 case '\\':
1480 Lconsume:
1481 p++;
1482 break;
1483 case 'a':
1484 c = 7;
1485 goto Lconsume;
1486 case 'b':
1487 c = 8;
1488 goto Lconsume;
1489 case 'f':
1490 c = 12;
1491 goto Lconsume;
1492 case 'n':
1493 c = 10;
1494 goto Lconsume;
1495 case 'r':
1496 c = 13;
1497 goto Lconsume;
1498 case 't':
1499 c = 9;
1500 goto Lconsume;
1501 case 'v':
1502 c = 11;
1503 goto Lconsume;
1504 case 'u':
1505 ndigits = 4;
1506 goto Lhex;
1507 case 'U':
1508 ndigits = 8;
1509 goto Lhex;
1510 case 'x':
1511 ndigits = 2;
1512 Lhex:
1513 p++;
1514 c = *p;
1515 if (ishex(cast(char)c))
1516 {
1517 uint v = 0;
1518 int n = 0;
1519 if (Ccompile && ndigits == 2)
1520 {
1521 /* C11 6.4.4.4-7 one to infinity hex digits
1522 */
1523 do
1524 {
1525 if (isdigit(cast(char)c))
1526 c -= '0';
1527 else if (islower(c))
1528 c -= 'a' - 10;
1529 else
1530 c -= 'A' - 10;
1531 v = v * 16 + c;
1532 c = *++p;
1533 } while (ishex(cast(char)c));
1534 }
1535 else
1536 {
1537 while (1)
1538 {
1539 if (isdigit(cast(char)c))
1540 c -= '0';
1541 else if (islower(c))
1542 c -= 'a' - 10;
1543 else
1544 c -= 'A' - 10;
1545 v = v * 16 + c;
1546 c = *++p;
1547 if (++n == ndigits)
1548 break;
1549 if (!ishex(cast(char)c))
1550 {
1551 error(loc, "escape hex sequence has %d hex digits instead of %d", n, ndigits);
1552 break;
1553 }
1554 }
1555 if (ndigits != 2 && !utf_isValidDchar(v))
1556 {
1557 error(loc, "invalid UTF character \\U%08x", v);
1558 if (v >= 0xD800 && v <= 0xDFFF)
1559 errorSupplemental("The code unit is a UTF-16 surrogate, is the escape UTF-16 not a Unicode code point?");
1560 v = '?'; // recover with valid UTF character
1561 }
1562 }
1563 c = v;
1564 }
1565 else
1566 {
1567 error(loc, "undefined escape hex sequence \\%c%c", sequence[0], c);
1568 p++;
1569 }
1570 break;
1571 case '&':
1572 if (Ccompile)
1573 goto default;
1574
1575 // named character entity
1576 for (const idstart = ++p; 1; p++)
1577 {
1578 switch (*p)
1579 {
1580 case ';':
1581 auto entity = HtmlNamedEntity(idstart[0 .. p - idstart]);
1582 c = entity[0];
1583 if (entity == entity.init)
1584 {
1585 error(loc, "unnamed character entity &%.*s;", cast(int)(p - idstart), idstart);
1586 c = '?';
1587 }
1588 if (entity[1] != entity.init[1])
1589 c2 = entity[1];
1590
1591 p++;
1592 break;
1593 default:
1594 if (isalpha(*p) || (p != idstart && isdigit(*p)))
1595 continue;
1596 error(loc, "unterminated named entity &%.*s;", cast(int)(p - idstart + 1), idstart);
1597 c = '?';
1598 break;
1599 }
1600 break;
1601 }
1602 break;
1603 case 0:
1604 case 0x1A:
1605 // end of file
1606 c = '\\';
1607 break;
1608 default:
1609 if (isoctal(cast(char)c))
1610 {
1611 uint v = 0;
1612 int n = 0;
1613 do
1614 {
1615 v = v * 8 + (c - '0');
1616 c = *++p;
1617 }
1618 while (++n < 3 && isoctal(cast(char)c));
1619 c = v;
1620 if (c > 0xFF)
1621 error(loc, "escape octal sequence \\%03o is larger than \\377", c);
1622 }
1623 else
1624 {
1625 error(loc, "undefined escape sequence \\%c", c);
1626 p++;
1627 }
1628 break;
1629 }
1630 return c;
1631 }
1632
1633 /**
1634 Lex a wysiwyg string. `p` must be pointing to the first character before the
1635 contents of the string literal. The character pointed to by `p` will be used as
1636 the terminating character (i.e. backtick or double-quote).
1637 Params:
1638 result = pointer to the token that accepts the result
1639 */
1640 private void wysiwygStringConstant(Token* result, bool supportInterpolation = false)
1641 {
1642 if (supportInterpolation)
1643 {
1644 result.value = TOK.interpolated;
1645 result.interpolatedSet = null;
1646 }
1647 else
1648 {
1649 result.value = TOK.string_;
1650 }
1651
1652 Loc start = loc();
1653 auto terminator = p[0];
1654 p++;
1655 stringbuffer.setsize(0);
1656 while (1)
1657 {
1658 dchar c = p[0];
1659 p++;
1660 switch (c)
1661 {
1662 case '\n':
1663 endOfLine();
1664 break;
1665 case '\r':
1666 if (p[0] == '\n')
1667 continue; // ignore
1668 c = '\n'; // treat EndOfLine as \n character
1669 endOfLine();
1670 break;
1671 case '$':
1672 if (!supportInterpolation)
1673 goto default;
1674
1675 if (!handleInterpolatedSegment(result, start))
1676 goto default;
1677
1678 continue;
1679 case 0:
1680 case 0x1A:
1681 error("unterminated string constant starting at %s", start.toChars());
1682 result.setString();
1683 // rewind `p` so it points to the EOF character
1684 p--;
1685 return;
1686 default:
1687 if (c == terminator)
1688 {
1689 if (supportInterpolation)
1690 result.appendInterpolatedPart(stringbuffer);
1691 else
1692 result.setString(stringbuffer);
1693
1694 stringPostfix(result);
1695 return;
1696 }
1697 else if (c & 0x80)
1698 {
1699 p--;
1700 const u = decodeUTF();
1701 p++;
1702 if (u == PS || u == LS)
1703 endOfLine();
1704 stringbuffer.writeUTF8(u);
1705 continue;
1706 }
1707 break;
1708 }
1709 stringbuffer.writeByte(c);
1710 }
1711 }
1712
1713 /**************************************
1714 * Lex hex strings:
1715 * x"0A ae 34FE BD"
1716 */
1717 final TOK hexStringConstant(Token* t)
1718 {
1719 Loc start = loc();
1720 uint n = 0;
1721 uint v = ~0; // dead assignment, needed to suppress warning
1722 p++;
1723 stringbuffer.setsize(0);
1724 while (1)
1725 {
1726 dchar c = *p++;
1727 switch (c)
1728 {
1729 case ' ':
1730 case '\t':
1731 case '\v':
1732 case '\f':
1733 continue; // skip white space
1734 case '\r':
1735 if (*p == '\n')
1736 continue; // ignore '\r' if followed by '\n'
1737 // Treat isolated '\r' as if it were a '\n'
1738 goto case '\n';
1739 case '\n':
1740 endOfLine();
1741 continue;
1742 case 0:
1743 case 0x1A:
1744 error("unterminated string constant starting at %s", start.toChars());
1745 t.setString();
1746 // decrement `p`, because it needs to point to the next token (the 0 or 0x1A character is the TOK.endOfFile token).
1747 p--;
1748 return TOK.hexadecimalString;
1749 case '"':
1750 if (n & 1)
1751 {
1752 error("odd number (%d) of hex characters in hex string", n);
1753 stringbuffer.writeByte(v);
1754 }
1755 t.setString(stringbuffer);
1756 stringPostfix(t);
1757 return TOK.hexadecimalString;
1758 default:
1759 if (c >= '0' && c <= '9')
1760 c -= '0';
1761 else if (c >= 'a' && c <= 'f')
1762 c -= 'a' - 10;
1763 else if (c >= 'A' && c <= 'F')
1764 c -= 'A' - 10;
1765 else if (c & 0x80)
1766 {
1767 p--;
1768 const u = decodeUTF();
1769 p++;
1770 if (u == PS || u == LS)
1771 endOfLine();
1772 else
1773 error("non-hex character \\u%04x in hex string", u);
1774 }
1775 else
1776 error("non-hex character '%c' in hex string", c);
1777 if (n & 1)
1778 {
1779 v = (v << 4) | c;
1780 stringbuffer.writeByte(v);
1781 }
1782 else
1783 v = c;
1784 n++;
1785 break;
1786 }
1787 }
1788 assert(0); // see bug 15731
1789 }
1790
1791 /**
1792 Lex a delimited string. Some examples of delimited strings are:
1793 ---
1794 q"(foo(xxx))" // "foo(xxx)"
1795 q"[foo$(LPAREN)]" // "foo$(LPAREN)"
1796 q"/foo]/" // "foo]"
1797 q"HERE
1798 foo
1799 HERE" // "foo\n"
1800 ---
1801 It is assumed that `p` points to the opening double-quote '"'.
1802 Params:
1803 result = pointer to the token that accepts the result
1804 */
1805 private void delimitedStringConstant(Token* result)
1806 {
1807 result.value = TOK.string_;
1808 Loc start = loc();
1809 dchar delimleft = 0;
1810 dchar delimright = 0;
1811 uint nest = 1;
1812 uint nestcount = ~0; // dead assignment, needed to suppress warning
1813 Identifier hereid = null;
1814 uint blankrol = 0;
1815 uint startline = 0;
1816 p++;
1817 stringbuffer.setsize(0);
1818 while (1)
1819 {
1820 const s = p;
1821 dchar c = *p++;
1822 //printf("c = '%c'\n", c);
1823 switch (c)
1824 {
1825 case '\n':
1826 Lnextline:
1827 endOfLine();
1828 startline = 1;
1829 if (blankrol)
1830 {
1831 blankrol = 0;
1832 continue;
1833 }
1834 if (hereid)
1835 {
1836 stringbuffer.writeUTF8(c);
1837 continue;
1838 }
1839 break;
1840 case '\r':
1841 if (*p == '\n')
1842 continue; // ignore
1843 c = '\n'; // treat EndOfLine as \n character
1844 goto Lnextline;
1845 case 0:
1846 case 0x1A:
1847 error("unterminated delimited string constant starting at %s", start.toChars());
1848 result.setString();
1849 // decrement `p`, because it needs to point to the next token (the 0 or 0x1A character is the TOK.endOfFile token).
1850 p--;
1851 return;
1852 default:
1853 if (c & 0x80)
1854 {
1855 p--;
1856 c = decodeUTF();
1857 p++;
1858 if (c == PS || c == LS)
1859 goto Lnextline;
1860 }
1861 break;
1862 }
1863 if (delimleft == 0)
1864 {
1865 delimleft = c;
1866 nest = 1;
1867 nestcount = 1;
1868 if (c == '(')
1869 delimright = ')';
1870 else if (c == '{')
1871 delimright = '}';
1872 else if (c == '[')
1873 delimright = ']';
1874 else if (c == '<')
1875 delimright = '>';
1876 else if (isalpha(c) || c == '_' || (c >= 0x80 && charLookup.isStart(c)))
1877 {
1878 // Start of identifier; must be a heredoc
1879 Token tok;
1880 p = s;
1881 scan(&tok); // read in heredoc identifier
1882 if (tok.value != TOK.identifier)
1883 {
1884 error("identifier expected for heredoc, not %s", tok.toChars());
1885 delimright = c;
1886 }
1887 else
1888 {
1889 hereid = tok.ident;
1890 //printf("hereid = '%s'\n", hereid.toChars());
1891 blankrol = 1;
1892 }
1893 nest = 0;
1894 }
1895 else
1896 {
1897 delimright = c;
1898 nest = 0;
1899 if (isspace(c))
1900 error("delimiter cannot be whitespace");
1901 }
1902 }
1903 else
1904 {
1905 if (blankrol)
1906 {
1907 error("heredoc rest of line should be blank");
1908 blankrol = 0;
1909 continue;
1910 }
1911 if (nest == 1)
1912 {
1913 if (c == delimleft)
1914 nestcount++;
1915 else if (c == delimright)
1916 {
1917 nestcount--;
1918 if (nestcount == 0)
1919 goto Ldone;
1920 }
1921 }
1922 else if (c == delimright)
1923 goto Ldone;
1924
1925 // we're looking for a new identifier token
1926 if (startline && (isalpha(c) || c == '_' || (c >= 0x80 && charLookup.isStart(c))) && hereid)
1927 {
1928 Token tok;
1929 auto psave = p;
1930 p = s;
1931 scan(&tok); // read in possible heredoc identifier
1932 //printf("endid = '%s'\n", tok.ident.toChars());
1933 if (tok.value == TOK.identifier && tok.ident is hereid)
1934 {
1935 /* should check that rest of line is blank
1936 */
1937 goto Ldone;
1938 }
1939 p = psave;
1940 }
1941 stringbuffer.writeUTF8(c);
1942 startline = 0;
1943 }
1944 }
1945 Ldone:
1946 if (*p == '"')
1947 p++;
1948 else if (hereid)
1949 error("delimited string must end in `%s\"`", hereid.toChars());
1950 else if (isspace(delimright))
1951 error("delimited string must end in `\"`");
1952 else
1953 error(token.loc, "delimited string must end in `%c\"`", delimright);
1954 result.setString(stringbuffer);
1955 stringPostfix(result);
1956 }
1957
1958 /**
1959 Lex a token string. Some examples of token strings are:
1960 ---
1961 q{ foo(xxx) } // " foo(xxx) "
1962 q{foo$(LPAREN)} // "foo$(LPAREN)"
1963 q{{foo}"}"} // "{foo}"}""
1964 ---
1965 It is assumed that `p` points to the opening curly-brace.
1966 Params:
1967 result = pointer to the token that accepts the result
1968 */
1969 private void tokenStringConstant(Token* result, bool supportInterpolation = false)
1970 {
1971 if (supportInterpolation)
1972 {
1973 result.value = TOK.interpolated;
1974 result.interpolatedSet = null;
1975 }
1976 else
1977 {
1978 result.value = TOK.string_;
1979 }
1980
1981 uint nest = 1;
1982 const start = loc();
1983 auto pstart = ++p;
1984 inTokenStringConstant++;
1985 scope(exit) inTokenStringConstant--;
1986 while (1)
1987 {
1988 Token tok;
1989 scan(&tok);
1990 switch (tok.value)
1991 {
1992 case TOK.leftCurly:
1993 nest++;
1994 continue;
1995 case TOK.rightCurly:
1996 if (--nest == 0)
1997 {
1998 if (supportInterpolation)
1999 result.appendInterpolatedPart(pstart, p - 1 - pstart);
2000 else
2001 result.setString(pstart, p - 1 - pstart);
2002
2003 stringPostfix(result);
2004 return;
2005 }
2006 continue;
2007 case TOK.dollar:
2008 if (!supportInterpolation)
2009 goto default;
2010
2011 stringbuffer.setsize(0);
2012 stringbuffer.write(pstart, p - 1 - pstart);
2013 if (!handleInterpolatedSegment(result, start))
2014 goto default;
2015
2016 stringbuffer.setsize(0);
2017
2018 pstart = p;
2019
2020 continue;
2021 case TOK.endOfFile:
2022 error("unterminated token string constant starting at %s", start.toChars());
2023 result.setString();
2024 return;
2025 default:
2026 continue;
2027 }
2028 }
2029 }
2030
2031 // returns true if it got special treatment as an interpolated segment
2032 // otherwise returns false, indicating to treat it as just part of a normal string
2033 private bool handleInterpolatedSegment(Token* token, Loc start)
2034 {
2035 switch(*p)
2036 {
2037 case '(':
2038 // expression, at this level we need to scan until the closing ')'
2039
2040 // always put the string part in first
2041 token.appendInterpolatedPart(stringbuffer);
2042 stringbuffer.setsize(0);
2043
2044 int openParenCount = 1;
2045 p++; // skip the first open paren
2046 auto pstart = p;
2047 while (openParenCount > 0)
2048 {
2049 // need to scan with the lexer to support embedded strings and other complex cases
2050 Token tok;
2051 scan(&tok);
2052 if (tok.value == TOK.leftParenthesis)
2053 openParenCount++;
2054 if (tok.value == TOK.rightParenthesis)
2055 openParenCount--;
2056 if (tok.value == TOK.endOfFile)
2057 {
2058 // FIXME: make this error better, it spams a lot
2059 error("unterminated interpolated string constant starting at %s", start.toChars());
2060 return false;
2061 }
2062 }
2063
2064 // then put the interpolated string segment
2065 token.appendInterpolatedPart(pstart[0 .. p - 1 - pstart]);
2066
2067 stringbuffer.setsize(0); // make sure this is reset from the last token scan
2068 // otherwise something like i"$(func("thing")) stuff" can still include it
2069
2070 return true;
2071 default:
2072 // nothing special
2073 return false;
2074 }
2075 }
2076
2077 /**
2078 Scan a quoted string while building the processed string value by
2079 handling escape sequences. The result is returned in the given `t` token.
2080 This function assumes that `p` currently points to the opening quote
2081 of the string.
2082 Params:
2083 t = the token to set the resulting string to
2084 * References:
2085 * D https://dlang.org/spec/lex.html#double_quoted_strings
2086 * ImportC C11 6.4.5
2087 */
2088 private void escapeStringConstant(Token* t, bool supportInterpolation = false)
2089 {
2090 if (supportInterpolation)
2091 {
2092 t.value = TOK.interpolated;
2093 t.interpolatedSet = null;
2094 }
2095 else
2096 {
2097 t.value = TOK.string_;
2098 }
2099
2100 const start = loc();
2101 const tc = *p++; // opening quote
2102 stringbuffer.setsize(0);
2103 while (1)
2104 {
2105 dchar c = *p++;
2106 dchar c2;
2107 switch (c)
2108 {
2109 case '\\':
2110 switch (*p)
2111 {
2112 case '&':
2113 if (Ccompile)
2114 goto default;
2115
2116 c = escapeSequence(c2);
2117 stringbuffer.writeUTF8(c);
2118 if (c2 != dchar.init)
2119 stringbuffer.writeUTF8(c2);
2120 continue;
2121 case 'u':
2122 case 'U':
2123 c = escapeSequence(c2);
2124 stringbuffer.writeUTF8(c);
2125 continue;
2126 case '$':
2127 if (supportInterpolation)
2128 {
2129 p++; // skip escaped $
2130 stringbuffer.writeByte('$');
2131 continue;
2132 }
2133 else
2134 goto default;
2135 default:
2136 c = escapeSequence(c2);
2137 break;
2138 }
2139 break;
2140 case '$':
2141 if (!supportInterpolation)
2142 goto default;
2143
2144 if (!handleInterpolatedSegment(t, start))
2145 goto default;
2146
2147 continue;
2148 case '\n':
2149 endOfLine();
2150 if (Ccompile)
2151 goto Lunterminated;
2152 break;
2153 case '\r':
2154 if (*p == '\n')
2155 continue; // ignore
2156 c = '\n'; // treat EndOfLine as \n character
2157 endOfLine();
2158 if (Ccompile)
2159 goto Lunterminated;
2160 break;
2161 case '\'':
2162 case '"':
2163 if (c != tc)
2164 goto default;
2165 if (supportInterpolation)
2166 t.appendInterpolatedPart(stringbuffer);
2167 else
2168 t.setString(stringbuffer);
2169 if (!Ccompile)
2170 stringPostfix(t);
2171 return;
2172 case 0:
2173 case 0x1A:
2174 // decrement `p`, because it needs to point to the next token (the 0 or 0x1A character is the TOK.endOfFile token).
2175 p--;
2176 Lunterminated:
2177 error("unterminated string constant starting at %s", start.toChars());
2178 t.setString();
2179 return;
2180 default:
2181 if (c & 0x80)
2182 {
2183 p--;
2184 c = decodeUTF();
2185 if (c == LS || c == PS)
2186 {
2187 c = '\n';
2188 endOfLine();
2189 if (Ccompile)
2190 goto Lunterminated;
2191 }
2192 p++;
2193 stringbuffer.writeUTF8(c);
2194 continue;
2195 }
2196 break;
2197 }
2198 stringbuffer.writeByte(c);
2199 }
2200 }
2201
2202 /**************************************
2203 * Reference:
2204 * https://dlang.org/spec/lex.html#characterliteral
2205 */
2206 private TOK charConstant(Token* t)
2207 {
2208 TOK tk = TOK.charLiteral;
2209 //printf("Lexer::charConstant\n");
2210 p++;
2211 dchar c = *p++;
2212 dchar c2;
2213 switch (c)
2214 {
2215 case '\\':
2216 switch (*p)
2217 {
2218 case 'u':
2219 tk = TOK.wcharLiteral;
2220 goto default;
2221 case 'U':
2222 case '&':
2223 tk = TOK.dcharLiteral;
2224 goto default;
2225 default:
2226 t.unsvalue = escapeSequence(c2);
2227 if (c2 != c2.init)
2228 {
2229 error("html entity requires 2 code units, use a string instead of a character");
2230 t.unsvalue = '?';
2231 }
2232 break;
2233 }
2234 break;
2235 case '\n':
2236 L1:
2237 endOfLine();
2238 goto case;
2239 case '\r':
2240 goto case '\'';
2241 case 0:
2242 case 0x1A:
2243 // decrement `p`, because it needs to point to the next token (the 0 or 0x1A character is the TOK.endOfFile token).
2244 p--;
2245 goto case;
2246 case '\'':
2247 error("unterminated character constant");
2248 t.unsvalue = '?';
2249 return tk;
2250 default:
2251 if (c & 0x80)
2252 {
2253 p--;
2254 c = decodeUTF();
2255 p++;
2256 if (c == LS || c == PS)
2257 goto L1;
2258 if (c < 0xD800 || (c >= 0xE000 && c < 0xFFFE))
2259 tk = TOK.wcharLiteral;
2260 else
2261 tk = TOK.dcharLiteral;
2262 }
2263 t.unsvalue = c;
2264 break;
2265 }
2266 if (*p != '\'')
2267 {
2268 while (*p != '\'' && *p != 0x1A && *p != 0 && *p != '\n' &&
2269 *p != '\r' && *p != ';' && *p != ')' && *p != ']' && *p != '}')
2270 {
2271 if (*p & 0x80)
2272 {
2273 const s = p;
2274 c = decodeUTF();
2275 if (c == LS || c == PS)
2276 {
2277 p = s;
2278 break;
2279 }
2280 }
2281 p++;
2282 }
2283
2284 if (*p == '\'')
2285 {
2286 error("character constant has multiple characters");
2287 p++;
2288 }
2289 else
2290 error("unterminated character constant");
2291 t.unsvalue = '?';
2292 return tk;
2293 }
2294 p++;
2295 return tk;
2296 }
2297
2298 /***************************************
2299 * Lex C character constant.
2300 * Parser is on the opening quote.
2301 * Params:
2302 * t = token to fill in
2303 * prefix = one of `u`, `U` or 0.
2304 * Reference:
2305 * C11 6.4.4.4
2306 */
2307 private void clexerCharConstant(ref Token t, char prefix)
2308 {
2309 escapeStringConstant(&t);
2310 const(char)[] str = t.ustring[0 .. t.len];
2311 const n = str.length;
2312 const loc = t.loc;
2313 if (n == 0)
2314 {
2315 error(loc, "empty character constant");
2316 t.value = TOK.semicolon;
2317 return;
2318 }
2319
2320 uint u;
2321 switch (prefix)
2322 {
2323 case 0:
2324 if (n == 1) // fast case
2325 {
2326 u = str[0];
2327 }
2328 else if (n > 4)
2329 error(loc, "max number of chars in character literal is 4, had %d",
2330 cast(int)n);
2331 else
2332 {
2333 foreach (i, c; str)
2334 (cast(char*)&u)[n - 1 - i] = c;
2335 }
2336 break;
2337
2338 case 'u':
2339 dchar d1;
2340 size_t idx;
2341 while (idx < n)
2342 {
2343 string msg = utf_decodeChar(str, idx, d1);
2344 if (msg)
2345 error(loc, "%.*s", cast(int)msg.length, msg.ptr);
2346 }
2347 if (d1 >= 0x1_0000)
2348 error(loc, "x%x does not fit in 16 bits", d1);
2349 t.unsvalue = d1;
2350 t.value = TOK.wcharLiteral; // C11 6.4.4.4-9
2351 return;
2352
2353 case 'U':
2354 dchar d;
2355 size_t idx;
2356 auto msg = utf_decodeChar(str, idx, d);
2357 if (msg)
2358 error(loc, "%.*s", cast(int)msg.length, msg.ptr);
2359 else if (idx < n)
2360 error(loc, "max number of chars in 32 bit character literal is 1, had %d",
2361 cast(int)((n + 3) >> 2));
2362 t.unsvalue = d;
2363 t.value = TOK.dcharLiteral; // C11 6.4.4.4-9
2364 return;
2365
2366 default:
2367 assert(0);
2368 }
2369 t.value = n == 1 ? TOK.charLiteral : TOK.int32Literal;
2370 t.unsvalue = u;
2371 }
2372
2373 /***************************************
2374 * Get postfix of string literal.
2375 */
2376 private void stringPostfix(Token* t) pure @nogc
2377 {
2378 switch (*p)
2379 {
2380 case 'c':
2381 case 'w':
2382 case 'd':
2383 t.postfix = *p;
2384 p++;
2385 break;
2386 default:
2387 t.postfix = 0;
2388 break;
2389 }
2390 }
2391
2392 /**************************************
2393 * Read in a number.
2394 * If it's an integer, store it in tok.TKutok.Vlong.
2395 * integers can be decimal, octal or hex
2396 * Handle the suffixes U, UL, LU, L, etc.
2397 * If it's double, store it in tok.TKutok.Vdouble.
2398 * Returns:
2399 * TKnum
2400 * TKdouble,...
2401 */
2402 private TOK number(Token* t)
2403 {
2404 int base = 10;
2405 const start = p;
2406 ulong n = 0; // unsigned >=64 bit integer type
2407 int d;
2408 bool err = false;
2409 bool overflow = false;
2410 bool anyBinaryDigitsNoSingleUS = false;
2411 bool anyHexDigitsNoSingleUS = false;
2412 char errorDigit = 0;
2413 dchar c = *p;
2414 if (c == '0')
2415 {
2416 ++p;
2417 c = *p;
2418 switch (c)
2419 {
2420 case '0':
2421 case '1':
2422 case '2':
2423 case '3':
2424 case '4':
2425 case '5':
2426 case '6':
2427 case '7':
2428 base = 8;
2429 break;
2430
2431 case '8':
2432 case '9':
2433 errorDigit = cast(char) c;
2434 base = 8;
2435 break;
2436 case 'x':
2437 case 'X':
2438 ++p;
2439 base = 16;
2440 break;
2441 case 'b':
2442 case 'B':
2443 ++p;
2444 base = 2;
2445 break;
2446 case '.':
2447 if (p[1] == '.')
2448 goto Ldone; // if ".."
2449 if (isalpha(p[1]) || p[1] == '_' || p[1] & 0x80)
2450 {
2451 if (Ccompile && (p[1] == 'f' || p[1] == 'F' || p[1] == 'l' || p[1] == 'L'))
2452 goto Lreal; // if `0.f` or `0.L`
2453 goto Ldone; // if ".identifier" or ".unicode"
2454 }
2455 goto Lreal; // '.' is part of current token
2456 case 'i':
2457 case 'f':
2458 case 'F':
2459 goto Lreal;
2460 case '_':
2461 if (Ccompile)
2462 error("embedded `_` not allowed");
2463 ++p;
2464 base = 8;
2465 break;
2466 case 'L':
2467 if (p[1] == 'i')
2468 goto Lreal;
2469 break;
2470 default:
2471 break;
2472 }
2473 }
2474 while (1)
2475 {
2476 c = *p;
2477 switch (c)
2478 {
2479 case '0':
2480 case '1':
2481 case '2':
2482 case '3':
2483 case '4':
2484 case '5':
2485 case '6':
2486 case '7':
2487 case '8':
2488 case '9':
2489 ++p;
2490 d = c - '0';
2491 break;
2492 case 'a':
2493 case 'b':
2494 case 'c':
2495 case 'd':
2496 case 'e':
2497 case 'f':
2498 case 'A':
2499 case 'B':
2500 case 'C':
2501 case 'D':
2502 case 'E':
2503 case 'F':
2504 ++p;
2505 if (base != 16)
2506 {
2507 if (c == 'e' || c == 'E' || c == 'f' || c == 'F')
2508 goto Lreal;
2509 }
2510 if (c >= 'a')
2511 d = c + 10 - 'a';
2512 else
2513 d = c + 10 - 'A';
2514 break;
2515 case 'L':
2516 if (p[1] == 'i')
2517 goto Lreal;
2518 goto Ldone;
2519 case '.':
2520 if (p[1] == '.')
2521 goto Ldone; // if ".."
2522 if (base <= 10 && n > 0 && (isalpha(p[1]) || p[1] == '_' || p[1] & 0x80))
2523 {
2524 if (Ccompile && base == 10 &&
2525 (p[1] == 'e' || p[1] == 'E' || p[1] == 'f' || p[1] == 'F' || p[1] == 'l' || p[1] == 'L'))
2526 goto Lreal; // if `1.e6` or `1.f` or `1.L`
2527 goto Ldone; // if ".identifier" or ".unicode"
2528 }
2529 if (base == 16 && (!ishex(p[1]) || p[1] == '_' || p[1] & 0x80))
2530 goto Ldone; // if ".identifier" or ".unicode"
2531 if (base == 2)
2532 goto Ldone; // if ".identifier" or ".unicode"
2533 goto Lreal; // otherwise as part of a floating point literal
2534
2535 case 'i':
2536 if (Ccompile)
2537 goto Ldone;
2538 goto Lreal;
2539
2540 case 'p':
2541 case 'P':
2542 Lreal:
2543 p = start;
2544 return inreal(t);
2545 case '_':
2546 if (Ccompile)
2547 goto default;
2548 ++p;
2549 continue;
2550 default:
2551 goto Ldone;
2552 }
2553 // got a digit here, set any necessary flags, check for errors
2554 anyHexDigitsNoSingleUS = true;
2555 anyBinaryDigitsNoSingleUS = true;
2556 if (!errorDigit && d >= base)
2557 {
2558 errorDigit = cast(char) c;
2559 }
2560 // Avoid expensive overflow check if we aren't at risk of overflow
2561 if (n <= 0x0FFF_FFFF_FFFF_FFFFUL)
2562 n = n * base + d;
2563 else
2564 {
2565 import core.checkedint : mulu, addu;
2566
2567 n = mulu(n, base, overflow);
2568 n = addu(n, d, overflow);
2569 }
2570 }
2571 Ldone:
2572 if (errorDigit)
2573 {
2574 error(scanloc, "%s digit expected, not `%c`", base == 2 ? "binary".ptr :
2575 base == 8 ? "octal".ptr :
2576 "decimal".ptr, errorDigit);
2577 err = true;
2578 }
2579 if (overflow && !err)
2580 {
2581 error(scanloc, "integer overflow");
2582 err = true;
2583 }
2584 if ((base == 2 && !anyBinaryDigitsNoSingleUS) ||
2585 (base == 16 && !anyHexDigitsNoSingleUS))
2586 error(scanloc, "`%.*s` isn't a valid integer literal, use `%.*s0` instead", cast(int)(p - start), start, 2, start);
2587
2588 t.unsvalue = n;
2589
2590 if (Ccompile)
2591 return cnumber(base, n);
2592
2593 enum FLAGS : int
2594 {
2595 none = 0,
2596 decimal = 1, // decimal
2597 unsigned = 2, // u or U suffix
2598 long_ = 4, // L suffix
2599 }
2600
2601 FLAGS flags = (base == 10) ? FLAGS.decimal : FLAGS.none;
2602 // Parse trailing 'u', 'U', 'l' or 'L' in any combination
2603 const psuffix = p;
2604 while (1)
2605 {
2606 FLAGS f;
2607 switch (*p)
2608 {
2609 case 'U':
2610 case 'u':
2611 f = FLAGS.unsigned;
2612 goto L1;
2613 case 'l':
2614 f = FLAGS.long_;
2615 error(scanloc, "lower case integer suffix 'l' is not allowed. Please use 'L' instead");
2616 goto L1;
2617 case 'L':
2618 f = FLAGS.long_;
2619 L1:
2620 p++;
2621 if ((flags & f) && !err)
2622 {
2623 error(scanloc, "repeated integer suffix `%c`", p[-1]);
2624 err = true;
2625 }
2626 flags = cast(FLAGS)(flags | f);
2627 continue;
2628 default:
2629 break;
2630 }
2631 break;
2632 }
2633 if (base == 8 && n >= 8)
2634 {
2635 if (err)
2636 // can't translate invalid octal value, just show a generic message
2637 error(scanloc, "octal literals larger than 7 are no longer supported");
2638 else
2639 error(scanloc, "octal literals `0%llo%.*s` are no longer supported, use `std.conv.octal!\"%llo%.*s\"` instead",
2640 n, cast(int)(p - psuffix), psuffix, n, cast(int)(p - psuffix), psuffix);
2641 }
2642 TOK result;
2643 switch (flags)
2644 {
2645 case FLAGS.none:
2646 /* Octal or Hexadecimal constant.
2647 * First that fits: int, uint, long, ulong
2648 */
2649 if (n & 0x8000000000000000L)
2650 result = TOK.uns64Literal;
2651 else if (n & 0xFFFFFFFF00000000L)
2652 result = TOK.int64Literal;
2653 else if (n & 0x80000000)
2654 result = TOK.uns32Literal;
2655 else
2656 result = TOK.int32Literal;
2657 break;
2658 case FLAGS.decimal:
2659 /* First that fits: int, long, long long
2660 */
2661 if (n & 0x8000000000000000L)
2662 {
2663 result = TOK.uns64Literal;
2664 }
2665 else if (n & 0xFFFFFFFF80000000L)
2666 result = TOK.int64Literal;
2667 else
2668 result = TOK.int32Literal;
2669 break;
2670 case FLAGS.unsigned:
2671 case FLAGS.decimal | FLAGS.unsigned:
2672 /* First that fits: uint, ulong
2673 */
2674 if (n & 0xFFFFFFFF00000000L)
2675 result = TOK.uns64Literal;
2676 else
2677 result = TOK.uns32Literal;
2678 break;
2679 case FLAGS.decimal | FLAGS.long_:
2680 if (n & 0x8000000000000000L)
2681 {
2682 if (!err)
2683 {
2684 error("signed integer overflow");
2685 err = true;
2686 }
2687 result = TOK.uns64Literal;
2688 }
2689 else
2690 result = TOK.int64Literal;
2691 break;
2692 case FLAGS.long_:
2693 if (n & 0x8000000000000000L)
2694 result = TOK.uns64Literal;
2695 else
2696 result = TOK.int64Literal;
2697 break;
2698 case FLAGS.unsigned | FLAGS.long_:
2699 case FLAGS.decimal | FLAGS.unsigned | FLAGS.long_:
2700 result = TOK.uns64Literal;
2701 break;
2702 default:
2703 debug
2704 {
2705 printf("%x\n", flags);
2706 }
2707 assert(0);
2708 }
2709 return result;
2710 }
2711
2712 /**************************************
2713 * Lex C integer-suffix
2714 * Params:
2715 * base = number base
2716 * n = raw integer value
2717 * Returns:
2718 * token value
2719 */
2720 private TOK cnumber(int base, ulong n)
2721 {
2722 /* C11 6.4.4.1
2723 * Parse trailing suffixes:
2724 * u or U
2725 * l or L
2726 * ll or LL
2727 */
2728 enum FLAGS : uint
2729 {
2730 octalhex = 1, // octal or hexadecimal
2731 decimal = 2, // decimal
2732 unsigned = 4, // u or U suffix
2733 long_ = 8, // l or L suffix
2734 llong = 0x10, // ll or LL
2735
2736 // Microsoft extensions
2737 i8 = 0x20,
2738 i16 = 0x40,
2739 i32 = 0x80,
2740 i64 = 0x100,
2741 }
2742 FLAGS flags = (base == 10) ? FLAGS.decimal : FLAGS.octalhex;
2743 bool err;
2744 Lsuffixes:
2745 while (1)
2746 {
2747 FLAGS f;
2748 const cs = *p;
2749 switch (cs)
2750 {
2751 case 'U':
2752 case 'u':
2753 f = FLAGS.unsigned;
2754 break;
2755
2756 case 'l':
2757 case 'L':
2758 f = FLAGS.long_;
2759 if (cs == p[1])
2760 {
2761 f = FLAGS.long_ | FLAGS.llong;
2762 ++p;
2763 }
2764 break;
2765
2766 case 'i':
2767 case 'I':
2768 if (p[1] == '8')
2769 {
2770 f = FLAGS.i8;
2771 ++p;
2772 }
2773 else if (p[1] == '1' && p[2] == '6')
2774 {
2775 f = FLAGS.i16;
2776 p += 2;
2777 }
2778 else if (p[1] == '3' && p[2] == '2')
2779 {
2780 f = FLAGS.i32;
2781 p += 2;
2782 }
2783 else if (p[1] == '6' && p[2] == '4')
2784 {
2785 f = FLAGS.i64;
2786 p += 2;
2787 }
2788 else
2789 break Lsuffixes;
2790 if (p[1] >= '0' && p[1] <= '9' && !err)
2791 {
2792 error("invalid integer suffix");
2793 err = true;
2794 }
2795 break;
2796
2797 default:
2798 break Lsuffixes;
2799 }
2800 ++p;
2801 if ((flags & f) && !err)
2802 {
2803 error("duplicate integer suffixes");
2804 err = true;
2805 }
2806 flags = cast(FLAGS)(flags | f);
2807 }
2808
2809 TOK result = TOK.int32Literal; // default
2810 switch (flags)
2811 {
2812 /* Since D doesn't have a variable sized `long` or `unsigned long` type,
2813 * this code deviates from C by picking D int, uint, long, or ulong instead
2814 */
2815
2816 case FLAGS.octalhex:
2817 /* Octal or Hexadecimal constant.
2818 * First that fits: int, unsigned, long, unsigned long,
2819 * long long, unsigned long long
2820 */
2821 if (n & 0x8000000000000000L)
2822 result = TOK.uns64Literal; // unsigned long
2823 else if (n & 0xFFFFFFFF00000000L)
2824 result = TOK.int64Literal; // long
2825 else if (n & 0x80000000)
2826 result = TOK.uns32Literal;
2827 else
2828 result = TOK.int32Literal;
2829 break;
2830
2831 case FLAGS.decimal:
2832 /* First that fits: int, long, long long
2833 */
2834 if (n & 0x8000000000000000L)
2835 result = TOK.uns64Literal; // unsigned long
2836 else if (n & 0xFFFFFFFF80000000L)
2837 result = TOK.int64Literal; // long
2838 else
2839 result = TOK.int32Literal;
2840 break;
2841
2842 case FLAGS.octalhex | FLAGS.unsigned:
2843 case FLAGS.decimal | FLAGS.unsigned:
2844 /* First that fits: unsigned, unsigned long, unsigned long long
2845 */
2846 if (n & 0xFFFFFFFF00000000L)
2847 result = TOK.uns64Literal; // unsigned long
2848 else
2849 result = TOK.uns32Literal;
2850 break;
2851
2852 case FLAGS.decimal | FLAGS.long_:
2853 /* First that fits: long, long long
2854 */
2855 if (longsize == 4 || long_longsize == 4)
2856 {
2857 if (n & 0xFFFFFFFF_80000000L)
2858 result = TOK.int64Literal;
2859 else
2860 result = TOK.int32Literal; // long
2861 }
2862 else
2863 {
2864 result = TOK.int64Literal; // long
2865 }
2866 break;
2867
2868 case FLAGS.octalhex | FLAGS.long_:
2869 /* First that fits: long, unsigned long, long long,
2870 * unsigned long long
2871 */
2872 if (longsize == 4 || long_longsize == 4)
2873 {
2874 if (n & 0x8000000000000000L)
2875 result = TOK.uns64Literal;
2876 else if (n & 0xFFFFFFFF00000000L)
2877 result = TOK.int64Literal;
2878 else if (n & 0x80000000)
2879 result = TOK.uns32Literal; // unsigned long
2880 else
2881 result = TOK.int32Literal; // long
2882 }
2883 else
2884 {
2885 if (n & 0x80000000_00000000L)
2886 result = TOK.uns64Literal; // unsigned long
2887 else
2888 result = TOK.int64Literal; // long
2889 }
2890 break;
2891
2892 case FLAGS.octalhex | FLAGS.unsigned | FLAGS.long_:
2893 case FLAGS.decimal | FLAGS.unsigned | FLAGS.long_:
2894 /* First that fits: unsigned long, unsigned long long
2895 */
2896 if (longsize == 4 || long_longsize == 4)
2897 {
2898 if (n & 0xFFFFFFFF00000000L)
2899 result = TOK.uns64Literal;
2900 else
2901 result = TOK.uns32Literal; // unsigned long
2902 }
2903 else
2904 {
2905 result = TOK.uns64Literal; // unsigned long
2906 }
2907 break;
2908
2909 case FLAGS.octalhex | FLAGS.long_ | FLAGS.llong:
2910 /* First that fits: long long, unsigned long long
2911 */
2912 if (n & 0x8000000000000000L)
2913 result = TOK.uns64Literal;
2914 else
2915 result = TOK.int64Literal;
2916 break;
2917
2918 case FLAGS.decimal | FLAGS.long_ | FLAGS.llong:
2919 /* long long
2920 */
2921 result = TOK.int64Literal;
2922 break;
2923
2924 case FLAGS.octalhex | FLAGS.long_ | FLAGS.unsigned | FLAGS.llong:
2925 case FLAGS.decimal | FLAGS.long_ | FLAGS.unsigned | FLAGS.llong:
2926 result = TOK.uns64Literal;
2927 break;
2928
2929 case FLAGS.octalhex | FLAGS.i8:
2930 case FLAGS.octalhex | FLAGS.i16:
2931 case FLAGS.octalhex | FLAGS.i32:
2932 case FLAGS.octalhex | FLAGS.unsigned | FLAGS.i8:
2933 case FLAGS.octalhex | FLAGS.unsigned | FLAGS.i16:
2934 case FLAGS.octalhex | FLAGS.unsigned | FLAGS.i32:
2935 case FLAGS.decimal | FLAGS.unsigned | FLAGS.i8:
2936 case FLAGS.decimal | FLAGS.unsigned | FLAGS.i16:
2937 case FLAGS.decimal | FLAGS.unsigned | FLAGS.i32:
2938 result = TOK.uns32Literal;
2939 break;
2940
2941 case FLAGS.decimal | FLAGS.i8:
2942 case FLAGS.decimal | FLAGS.i16:
2943 case FLAGS.decimal | FLAGS.i32:
2944 result = TOK.int32Literal;
2945 break;
2946
2947 case FLAGS.octalhex | FLAGS.i64:
2948 case FLAGS.octalhex | FLAGS.unsigned | FLAGS.i64:
2949 case FLAGS.decimal | FLAGS.unsigned | FLAGS.i64:
2950 result = TOK.uns64Literal;
2951 break;
2952
2953 case FLAGS.decimal | FLAGS.i64:
2954 result = TOK.int64Literal;
2955 break;
2956
2957 default:
2958 debug printf("%x\n",flags);
2959 assert(0);
2960 }
2961 return result;
2962 }
2963
2964 /**************************************
2965 * Read in characters, converting them to real.
2966 * Bugs:
2967 * Exponent overflow not detected.
2968 * Too much requested precision is not detected.
2969 */
2970 private TOK inreal(Token* t)
2971 {
2972 //printf("Lexer::inreal()\n");
2973 debug
2974 {
2975 assert(*p == '.' || isdigit(*p));
2976 }
2977 bool isWellformedString = true;
2978 stringbuffer.setsize(0);
2979 auto pstart = p;
2980 bool hex = false;
2981 dchar c = *p++;
2982 // Leading '0x'
2983 if (c == '0')
2984 {
2985 c = *p++;
2986 if (c == 'x' || c == 'X')
2987 {
2988 hex = true;
2989 c = *p++;
2990 }
2991 }
2992 // Digits to left of '.'
2993 while (1)
2994 {
2995 if (c == '.')
2996 {
2997 c = *p++;
2998 break;
2999 }
3000 if (isdigit(c) || (hex && isxdigit(c)) || c == '_')
3001 {
3002 c = *p++;
3003 continue;
3004 }
3005 break;
3006 }
3007 // Digits to right of '.'
3008 while (1)
3009 {
3010 if (isdigit(c) || (hex && isxdigit(c)) || c == '_')
3011 {
3012 c = *p++;
3013 continue;
3014 }
3015 break;
3016 }
3017 if (c == 'e' || c == 'E' || (hex && (c == 'p' || c == 'P')))
3018 {
3019 c = *p++;
3020 if (c == '-' || c == '+')
3021 {
3022 c = *p++;
3023 }
3024 bool anyexp = false;
3025 while (1)
3026 {
3027 if (isdigit(c))
3028 {
3029 anyexp = true;
3030 c = *p++;
3031 continue;
3032 }
3033 if (c == '_')
3034 {
3035 if (Ccompile)
3036 error("embedded `_` in numeric literals not allowed");
3037 c = *p++;
3038 continue;
3039 }
3040 if (!anyexp)
3041 {
3042 error("missing exponent");
3043 isWellformedString = false;
3044 }
3045 break;
3046 }
3047 }
3048 else if (hex)
3049 {
3050 error("exponent required for hex float");
3051 isWellformedString = false;
3052 }
3053 --p;
3054 while (pstart < p)
3055 {
3056 if (*pstart != '_')
3057 stringbuffer.writeByte(*pstart);
3058 ++pstart;
3059 }
3060 stringbuffer.writeByte(0);
3061 auto sbufptr = cast(const(char)*)stringbuffer[].ptr;
3062 TOK result;
3063 bool isOutOfRange = false;
3064 t.floatvalue = (isWellformedString ? CTFloat.parse(sbufptr, isOutOfRange) : CTFloat.zero);
3065
3066 bool imaginary = false;
3067 if (*p == 'i' && Ccompile)
3068 {
3069 ++p;
3070 imaginary = true;
3071 }
3072
3073 switch (*p)
3074 {
3075 case 'F':
3076 case 'f':
3077 if (isWellformedString && !isOutOfRange)
3078 isOutOfRange = Port.isFloat32LiteralOutOfRange(sbufptr);
3079 result = TOK.float32Literal;
3080 p++;
3081 break;
3082 default:
3083 if (isWellformedString && !isOutOfRange)
3084 isOutOfRange = Port.isFloat64LiteralOutOfRange(sbufptr);
3085 result = TOK.float64Literal;
3086 break;
3087 case 'l':
3088 if (!Ccompile)
3089 error("use 'L' suffix instead of 'l'");
3090 goto case 'L';
3091 case 'L':
3092 ++p;
3093 if (Ccompile && long_doublesize == 8)
3094 goto default;
3095 result = TOK.float80Literal;
3096 break;
3097 }
3098
3099 if ((*p == 'i' || *p == 'I') && !Ccompile)
3100 {
3101 if (*p == 'I')
3102 error("use 'i' suffix instead of 'I'");
3103 p++;
3104 imaginary = true;
3105 }
3106
3107 if (imaginary)
3108 {
3109 switch (result)
3110 {
3111 case TOK.float32Literal:
3112 result = TOK.imaginary32Literal;
3113 break;
3114 case TOK.float64Literal:
3115 result = TOK.imaginary64Literal;
3116 break;
3117 case TOK.float80Literal:
3118 result = TOK.imaginary80Literal;
3119 break;
3120 default:
3121 break;
3122 }
3123 }
3124 const isLong = (result == TOK.float80Literal || result == TOK.imaginary80Literal);
3125 if (isOutOfRange && !isLong && (!Ccompile || hex))
3126 {
3127 /* C11 6.4.4.2 doesn't actually care if it is not representable if it is not hex
3128 */
3129 const char* suffix = result == TOK.float32Literal ? "f" : result == TOK.float80Literal ? "L" : "";
3130 const char* type = [TOK.float32Literal: "`float`".ptr,
3131 TOK.float64Literal: "`double`".ptr,
3132 TOK.float80Literal: "`real` for the current target".ptr][result];
3133 error(scanloc, "number `%s%s` is not representable as a %s", sbufptr, suffix, type);
3134 const char* extra = result == TOK.float64Literal ? "`real` literals can be written using the `L` suffix. " : "";
3135 eSink.errorSupplemental(scanloc, "%shttps://dlang.org/spec/lex.html#floatliteral", extra);
3136 }
3137 debug
3138 {
3139 switch (result)
3140 {
3141 case TOK.float32Literal:
3142 case TOK.float64Literal:
3143 case TOK.float80Literal:
3144 case TOK.imaginary32Literal:
3145 case TOK.imaginary64Literal:
3146 case TOK.imaginary80Literal:
3147 break;
3148 default:
3149 assert(0);
3150 }
3151 }
3152 return result;
3153 }
3154
3155 final Loc loc() @nogc
3156 {
3157 scanloc = baseLoc.getLoc(cast(uint) (p - base));
3158 return scanloc;
3159 }
3160
3161 void error(T...)(const(char)* format, T args)
3162 {
3163 eSink.error(token.loc, format, args);
3164 }
3165
3166 void error(T...)(Loc loc, const(char)* format, T args)
3167 {
3168 eSink.error(loc, format, args);
3169 }
3170
3171 void errorSupplemental(T...)(const(char)* format, T args)
3172 {
3173 eSink.errorSupplemental(token.loc, format, args);
3174 }
3175
3176 void deprecation(T...)(Loc loc, const(char)* format, T args)
3177 {
3178 eSink.deprecation(loc, format, args);
3179 }
3180
3181 void warning(T...)(Loc loc, const(char)* format, T args)
3182 {
3183 eSink.warning(loc, format, args);
3184 }
3185
3186 void deprecation(T...)(const(char)* format, T args)
3187 {
3188 eSink.deprecation(token.loc, format, args);
3189 }
3190
3191 void deprecationSupplemental(T...)(const(char)* format, T args)
3192 {
3193 eSink.deprecationSupplemental(token.loc, format, args);
3194 }
3195
3196 /***************************************
3197 * Parse special token sequence:
3198 * Returns:
3199 * true if the special token sequence was handled
3200 * References:
3201 * https://dlang.org/spec/lex.html#special-token-sequence
3202 */
3203 bool parseSpecialTokenSequence()
3204 {
3205 Token n;
3206 scan(&n);
3207 if (n.value == TOK.identifier)
3208 {
3209 if (n.ident == Id.line)
3210 {
3211 poundLine(n, false);
3212 return true;
3213 }
3214 else
3215 {
3216 const locx = loc();
3217 // @@@DEPRECATED_2.103@@@
3218 // Turn into an error in 2.113
3219 if (inTokenStringConstant)
3220 deprecation(locx, "token string requires valid D tokens, not `#%s`", n.ident.toChars());
3221 else
3222 error(locx, "C preprocessor directive `#%s` is not supported", n.ident.toChars());
3223 }
3224 }
3225 else if (n.value == TOK.if_)
3226 {
3227 const locx = loc();
3228 if (inTokenStringConstant)
3229 error(locx, "token string requires valid D tokens, not `#if`");
3230 else
3231 error(locx, "C preprocessor directive `#if` is not supported, use `version` or `static if`");
3232 }
3233 return false;
3234 }
3235
3236 /*********************************************
3237 * Parse line/file preprocessor directive:
3238 * #line linnum [filespec]
3239 * Allow __LINE__ for linnum, and __FILE__ for filespec.
3240 * Accept linemarker format:
3241 * # linnum [filespec] {flags}
3242 * There can be zero or more flags, which are one of the digits 1..4, and
3243 * must be in ascending order. The flags are ignored.
3244 * Params:
3245 * tok = token we're on, which is linnum of linemarker
3246 * linemarker = true if line marker format and lexer is on linnum
3247 * References:
3248 * linemarker https://gcc.gnu.org/onlinedocs/gcc-11.1.0/cpp/Preprocessor-Output.html
3249 */
3250 final void poundLine(ref Token tok, bool linemarker)
3251 {
3252 const(char)* filespec = null;
3253 bool flags;
3254
3255 if (!linemarker)
3256 scan(&tok);
3257 if (tok.value == TOK.int32Literal || tok.value == TOK.int64Literal)
3258 {
3259 const lin = cast(int)(tok.unsvalue);
3260 if (lin != tok.unsvalue)
3261 {
3262 error(tok.loc, "line number `%lld` out of range", cast(ulong)tok.unsvalue);
3263 skipToNextLine();
3264 return;
3265 }
3266 else
3267 linnum = lin;
3268 }
3269 else if (tok.value == TOK.line) // #line __LINE__
3270 {
3271 }
3272 else
3273 {
3274 error(tok.loc, "positive integer argument expected following `#line`");
3275 if (tok.value != TOK.endOfLine)
3276 skipToNextLine();
3277 return;
3278 }
3279 while (1)
3280 {
3281 scan(&tok);
3282 switch (tok.value)
3283 {
3284 case TOK.endOfFile:
3285 case TOK.endOfLine:
3286 if (!inTokenStringConstant)
3287 {
3288 baseLoc.addSubstitution(cast(uint) (p - base), filespec, linnum);
3289 }
3290 return;
3291 case TOK.file:
3292 if (filespec || flags)
3293 goto Lerr;
3294 filespec = mem.xstrdup(scanloc.filename);
3295 continue;
3296 case TOK.string_:
3297 if (filespec || flags)
3298 goto Lerr;
3299 if (tok.ptr[0] != '"' || tok.postfix != 0)
3300 goto Lerr;
3301 filespec = tok.ustring;
3302 continue;
3303 case TOK.int32Literal:
3304 if (!filespec)
3305 goto Lerr;
3306 if (linemarker && tok.unsvalue >= 1 && tok.unsvalue <= 4)
3307 {
3308 flags = true; // linemarker flags seen
3309 continue;
3310 }
3311 goto Lerr;
3312 default:
3313 goto Lerr;
3314 }
3315 }
3316 Lerr:
3317 if (filespec is null)
3318 error(tok.loc, "invalid filename for `#line` directive");
3319 else if (linemarker)
3320 error(tok.loc, "invalid flag for line marker directive");
3321 else if (!Ccompile)
3322 error(tok.loc, "found `%s` when expecting new line following `#line` directive", tok.toChars());
3323 if (tok.value != TOK.endOfLine)
3324 skipToNextLine();
3325 }
3326
3327 /***************************************
3328 * Scan forward to start of next line.
3329 * Params:
3330 * defines = send characters to `defines`
3331 */
3332 final void skipToNextLine(OutBuffer* defines = null)
3333 {
3334 while (1)
3335 {
3336 switch (*p)
3337 {
3338 case 0:
3339 case 0x1A:
3340 return; // do not advance p
3341
3342 case '\n':
3343 ++p;
3344 break;
3345
3346 case '\r':
3347 ++p;
3348 if (p[0] == '\n')
3349 ++p;
3350 break;
3351
3352 default:
3353 if (defines)
3354 defines.writeByte(*p); // don't care about Unicode line endings for C
3355 else if (*p & 0x80)
3356 {
3357 const u = decodeUTF();
3358 if (u == PS || u == LS)
3359 {
3360 ++p;
3361 break;
3362 }
3363 }
3364 ++p;
3365 continue;
3366 }
3367 break;
3368 }
3369 endOfLine();
3370 tokenizeNewlines = false;
3371 }
3372
3373 /********************************************
3374 * Decode UTF character.
3375 * Issue error messages for invalid sequences.
3376 * Return decoded character, advance p to last character in UTF sequence.
3377 */
3378 private uint decodeUTF()
3379 {
3380 string msg;
3381 auto result = decodeUTFpure(msg);
3382
3383 if (msg)
3384 error(token.loc, "%.*s", cast(int)msg.length, msg.ptr);
3385 return result;
3386 }
3387
3388 /********************************************
3389 * Same as above, but the potential error message is stored to the
3390 * msg parameter instead of being issued.
3391 */
3392 private pure uint decodeUTFpure(out string msg)
3393 {
3394 const s = p;
3395 assert(*s & 0x80);
3396 // Check length of remaining string up to 4 UTF-8 characters
3397 size_t len;
3398 for (len = 1; len < 4 && s[len]; len++)
3399 {
3400 }
3401 size_t idx = 0;
3402 dchar u;
3403 msg = utf_decodeChar(s[0 .. len], idx, u);
3404 p += idx - 1;
3405 if (!msg && isBidiControl(u))
3406 msg = "Bidirectional control characters are disallowed for security reasons.";
3407 return u;
3408 }
3409
3410 /***************************************************
3411 * Parse doc comment embedded between t.ptr and p.
3412 * Remove trailing blanks and tabs from lines.
3413 * Replace all newlines with \n.
3414 * Remove leading comment character from each line.
3415 * Decide if it's a lineComment or a blockComment.
3416 * Append to previous one for this token.
3417 *
3418 * If newParagraph is true, an extra newline will be
3419 * added between adjoining doc comments.
3420 */
3421 private void getDocComment(Token* t, uint lineComment, bool newParagraph) pure
3422 {
3423 /* ct tells us which kind of comment it is: '/', '*', or '+'
3424 */
3425 const ct = t.ptr[2];
3426 /* Start of comment text skips over / * *, / + +, or / / /
3427 */
3428 const(char)* q = t.ptr + 3; // start of comment text
3429 const(char)* qend = p;
3430 if (ct == '*' || ct == '+')
3431 qend -= 2;
3432 /* Scan over initial row of ****'s or ++++'s or ////'s
3433 */
3434 for (; q < qend; q++)
3435 {
3436 if (*q != ct)
3437 break;
3438 }
3439 /* Remove leading line feed or space
3440 */
3441 int linestart = 0;
3442 if (ct == '/')
3443 {
3444 if (q < qend && *q == ' ')
3445 ++q;
3446 }
3447 else if (q < qend)
3448 {
3449 if (*q == '\r')
3450 {
3451 ++q;
3452 if (q < qend && *q == '\n')
3453 ++q;
3454 linestart = 1;
3455 }
3456 else if (*q == '\n')
3457 {
3458 ++q;
3459 linestart = 1;
3460 }
3461 }
3462 /* Remove trailing row of ****'s or ++++'s
3463 */
3464 if (ct != '/')
3465 {
3466 for (; q < qend; qend--)
3467 {
3468 if (qend[-1] != ct)
3469 break;
3470 }
3471 }
3472 /* Comment is now [q .. qend].
3473 * Canonicalize it into buf[].
3474 */
3475 OutBuffer buf;
3476
3477 void trimTrailingWhitespace()
3478 {
3479 const s = buf[];
3480 auto len = s.length;
3481 while (len && (s[len - 1] == ' ' || s[len - 1] == '\t'))
3482 --len;
3483 buf.setsize(len);
3484 }
3485
3486 for (; q < qend; q++)
3487 {
3488 char c = *q;
3489 switch (c)
3490 {
3491 case '*':
3492 case '+':
3493 if (linestart && c == ct)
3494 {
3495 linestart = 0;
3496 /* Trim preceding whitespace up to preceding \n
3497 */
3498 trimTrailingWhitespace();
3499 continue;
3500 }
3501 break;
3502 case ' ':
3503 case '\t':
3504 break;
3505 case '\r':
3506 if (q[1] == '\n')
3507 continue; // skip the \r
3508 goto Lnewline;
3509 default:
3510 if (c == 226)
3511 {
3512 // If LS or PS
3513 if (q[1] == 128 && (q[2] == 168 || q[2] == 169))
3514 {
3515 q += 2;
3516 goto Lnewline;
3517 }
3518 }
3519 linestart = 0;
3520 break;
3521 Lnewline:
3522 c = '\n'; // replace all newlines with \n
3523 goto case;
3524 case '\n':
3525 linestart = 1;
3526 /* Trim trailing whitespace
3527 */
3528 trimTrailingWhitespace();
3529 break;
3530 }
3531 buf.writeByte(c);
3532 }
3533 /* Trim trailing whitespace (if the last line does not have newline)
3534 */
3535 trimTrailingWhitespace();
3536
3537 // Always end with a newline
3538 const s = buf[];
3539 if (s.length == 0 || s[$ - 1] != '\n')
3540 buf.writeByte('\n');
3541
3542 // It's a line comment if the start of the doc comment comes
3543 // after other non-whitespace on the same line.
3544 auto dc = (lineComment && anyToken) ? &t.lineComment : &t.blockComment;
3545 // Combine with previous doc comment, if any
3546 if (*dc)
3547 {
3548 auto p = combineComments(*dc, buf[], newParagraph);
3549 *dc = p ? p[0 .. strlen(p)] : null;
3550 }
3551 else
3552 *dc = buf.extractSlice(true);
3553 }
3554
3555 /********************************************
3556 * Combine two document comments into one,
3557 * separated by an extra newline if newParagraph is true.
3558 */
3559 static const(char)* combineComments(const(char)[] c1, const(char)[] c2, bool newParagraph) pure
3560 {
3561 //debug printf("Lexer::combineComments('%*.s', '%*.s', '%i')\n", cast(int) c1.length, c1.ptr, cast(int) c2.length, c2.ptr, newParagraph);
3562 const(int) newParagraphSize = newParagraph ? 1 : 0; // Size of the combining '\n'
3563 if (!c1)
3564 return c2.ptr;
3565 if (!c2)
3566 return c1.ptr;
3567
3568 int insertNewLine = 0;
3569 if (c1.length && c1[$ - 1] != '\n')
3570 insertNewLine = 1;
3571 const retSize = c1.length + insertNewLine + newParagraphSize + c2.length;
3572 auto p = cast(char*)mem.xmalloc_noscan(retSize + 1);
3573 p[0 .. c1.length] = c1[];
3574 if (insertNewLine)
3575 p[c1.length] = '\n';
3576 if (newParagraph)
3577 p[c1.length + insertNewLine] = '\n';
3578 p[retSize - c2.length .. retSize] = c2[];
3579 p[retSize] = 0;
3580 return p;
3581 }
3582
3583 /**************************
3584 * `p` should be at start of next line
3585 */
3586 private void endOfLine() @safe
3587 {
3588 linnum += 1;
3589 line = p;
3590 baseLoc.newLine(cast(uint)(p - base));
3591 }
3592
3593 /****************************
3594 * Print the tokens from the current `token` to the end,
3595 * while not advancing the parser forward.
3596 * Useful for debugging.
3597 */
3598 void printRestOfTokens()
3599 {
3600 auto tk = &token;
3601 while (1)
3602 {
3603 printf("%s ", (*tk).toChars());
3604 if (tk.value == TOK.endOfFile || tk.value == TOK.endOfLine)
3605 break;
3606 tk = peek(tk);
3607 }
3608 printf("\n");
3609 }
3610 }
3611
3612 /******************************* Unittest *****************************************/
3613
3614 unittest
3615 {
3616 fprintf(stderr, "Lexer.unittest %d\n", __LINE__);
3617
3618 ErrorSink errorSink = new ErrorSinkStderr;
3619
3620 void test(T)(string sequence, T expected, bool Ccompile = false)
3621 {
3622 auto p = cast(const(char)*)sequence.ptr;
3623 dchar c2;
3624 Lexer lexer = new Lexer(errorSink);
3625 assert(expected == lexer.escapeSequence(Loc.initial, p, Ccompile, c2));
3626 assert(p == sequence.ptr + sequence.length);
3627 }
3628
3629 test(`'`, '\'');
3630 test(`"`, '"');
3631 test(`?`, '?');
3632 test(`\`, '\\');
3633 test(`0`, '\0');
3634 test(`a`, '\a');
3635 test(`b`, '\b');
3636 test(`f`, '\f');
3637 test(`n`, '\n');
3638 test(`r`, '\r');
3639 test(`t`, '\t');
3640 test(`v`, '\v');
3641
3642 test(`x00`, 0x00);
3643 test(`xff`, 0xff);
3644 test(`xFF`, 0xff);
3645 test(`xa7`, 0xa7);
3646 test(`x3c`, 0x3c);
3647 test(`xe2`, 0xe2);
3648
3649 test(`1`, '\1');
3650 test(`42`, '\42');
3651 test(`357`, '\357');
3652
3653 test(`u1234`, '\u1234');
3654 test(`uf0e4`, '\uf0e4');
3655
3656 test(`U0001f603`, '\U0001f603');
3657
3658 test(`&quot;`, '"');
3659 test(`&lt;`, '<');
3660 test(`&gt;`, '>');
3661 }
3662
3663 unittest
3664 {
3665 fprintf(stderr, "Lexer.unittest %d\n", __LINE__);
3666
3667 static class ErrorSinkTest : ErrorSinkNull
3668 {
3669 nothrow:
3670 extern (C++):
3671 override:
3672
3673 import core.stdc.stdio;
3674 import core.stdc.stdarg;
3675
3676 string expected;
3677 string expectedSupplemental;
3678 bool gotError;
3679
3680 void verror(Loc loc, const(char)* format, va_list ap)
3681 {
3682 gotError = true;
3683 char[100] buffer = void;
3684 auto actual = buffer[0 .. vsnprintf(buffer.ptr, buffer.length, format, ap)];
3685 assert(expected == actual);
3686 }
3687
3688 void errorSupplemental(Loc loc, const(char)* format, ...)
3689 {
3690 gotError = true;
3691 char[128] buffer = void;
3692 va_list ap;
3693 va_start(ap, format);
3694 auto actual = buffer[0 .. vsnprintf(buffer.ptr, buffer.length, format, ap)];
3695 va_end(ap);
3696 assert(expectedSupplemental == actual);
3697 }
3698 }
3699
3700 ErrorSinkTest errorSink = new ErrorSinkTest;
3701
3702 void test2(string sequence, string[2] expectedError, dchar expectedReturnValue, uint expectedScanLength, bool Ccompile = false)
3703 {
3704 errorSink.expected = expectedError[0];
3705 errorSink.expectedSupplemental = expectedError[1];
3706 errorSink.gotError = false;
3707 auto p = cast(const(char)*)sequence.ptr;
3708 Lexer lexer = new Lexer(errorSink);
3709 dchar c2;
3710 auto actualReturnValue = lexer.escapeSequence(Loc.initial, p, Ccompile, c2);
3711 assert(errorSink.gotError);
3712 assert(expectedReturnValue == actualReturnValue);
3713
3714 auto actualScanLength = p - sequence.ptr;
3715 assert(expectedScanLength == actualScanLength);
3716 }
3717
3718 void test(string sequence, string expectedError, dchar expectedReturnValue, uint expectedScanLength, bool Ccompile = false)
3719 {
3720 test2(sequence, [expectedError, null], expectedReturnValue, expectedScanLength, Ccompile);
3721 }
3722
3723 test("c", `undefined escape sequence \c`, 'c', 1);
3724 test("!", `undefined escape sequence \!`, '!', 1);
3725 test("&quot;", `undefined escape sequence \&`, '&', 1, true);
3726
3727 test("x1", `escape hex sequence has 1 hex digits instead of 2`, '\x01', 2);
3728
3729 test("u1" , `escape hex sequence has 1 hex digits instead of 4`, 0x1, 2);
3730 test("u12" , `escape hex sequence has 2 hex digits instead of 4`, 0x12, 3);
3731 test("u123", `escape hex sequence has 3 hex digits instead of 4`, 0x123, 4);
3732
3733 test("U0" , `escape hex sequence has 1 hex digits instead of 8`, 0x0, 2);
3734 test("U00" , `escape hex sequence has 2 hex digits instead of 8`, 0x00, 3);
3735 test("U000" , `escape hex sequence has 3 hex digits instead of 8`, 0x000, 4);
3736 test("U0000" , `escape hex sequence has 4 hex digits instead of 8`, 0x0000, 5);
3737 test("U0001f" , `escape hex sequence has 5 hex digits instead of 8`, 0x0001f, 6);
3738 test("U0001f6" , `escape hex sequence has 6 hex digits instead of 8`, 0x0001f6, 7);
3739 test("U0001f60", `escape hex sequence has 7 hex digits instead of 8`, 0x0001f60, 8);
3740
3741 test("U00110000", `invalid UTF character \U00110000`, '?', 9);
3742
3743 test("xg0" , `undefined escape hex sequence \xg`, 'g', 2);
3744 test("ug000" , `undefined escape hex sequence \ug`, 'g', 2);
3745 test("Ug0000000", `undefined escape hex sequence \Ug`, 'g', 2);
3746
3747 test("&BAD;", `unnamed character entity &BAD;` , '?', 5);
3748 test("&quot", `unterminated named entity &quot;`, '?', 5);
3749 test("&quot", `unterminated named entity &quot;`, '?', 5);
3750
3751 test("400", `escape octal sequence \400 is larger than \377`, 0x100, 3);
3752
3753 test2("uD800", [`invalid UTF character \U0000d800`, `The code unit is a UTF-16 surrogate, is the escape UTF-16 not a Unicode code point?`], '?', 5);
3754 test2("uDFFF", [`invalid UTF character \U0000dfff`, `The code unit is a UTF-16 surrogate, is the escape UTF-16 not a Unicode code point?`], '?', 5);
3755 }
3756
3757 unittest
3758 {
3759 fprintf(stderr, "Lexer.unittest %d\n", __LINE__);
3760 /* Not much here, just trying things out.
3761 */
3762 string text = "int"; // We rely on the implicit null-terminator
3763 ErrorSink errorSink = new ErrorSinkStderr;
3764 scope Lexer lex1 = new Lexer(null, text.ptr, 0, text.length, false, false, errorSink, null);
3765 TOK tok;
3766 tok = lex1.nextToken();
3767 //printf("tok == %s, %d, %d\n", Token::toChars(tok), tok, TOK.int32);
3768 assert(tok == TOK.int32);
3769 tok = lex1.nextToken();
3770 assert(tok == TOK.endOfFile);
3771 tok = lex1.nextToken();
3772 assert(tok == TOK.endOfFile);
3773 tok = lex1.nextToken();
3774 assert(tok == TOK.endOfFile);
3775 }
3776
3777 unittest
3778 {
3779 fprintf(stderr, "Lexer.unittest %d\n", __LINE__);
3780
3781 // We don't want to see Lexer error output during these tests.
3782 ErrorSink errorSink = new ErrorSinkNull;
3783
3784 // Test malformed input: even malformed input should end in a TOK.endOfFile.
3785 static immutable char[][] testcases =
3786 [ // Testcase must end with 0 or 0x1A.
3787 [0], // not malformed, but pathological
3788 ['\'', 0],
3789 ['\'', 0x1A],
3790 ['{', '{', 'q', '{', 0],
3791 [0xFF, 0],
3792 [0xFF, 0x80, 0],
3793 [0xFF, 0xFF, 0],
3794 [0xFF, 0xFF, 0],
3795 ['x', '"', 0x1A],
3796 ];
3797
3798 foreach (testcase; testcases)
3799 {
3800 scope Lexer lex2 = new Lexer(null, testcase.ptr, 0, testcase.length-1, false, false, errorSink, null);
3801 TOK tok = lex2.nextToken();
3802 size_t iterations = 1;
3803 while ((tok != TOK.endOfFile) && (iterations++ < testcase.length))
3804 {
3805 tok = lex2.nextToken();
3806 }
3807 assert(tok == TOK.endOfFile);
3808 tok = lex2.nextToken();
3809 assert(tok == TOK.endOfFile);
3810 }
3811 }