Debian Codegraph @

gcc/d/dmd/parse.d

raw
1 /**
2 * Takes a token stream from the lexer, and parses it into an abstract syntax tree.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/grammar.html, D Grammar)
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/parse.d, _parse.d)
10 * Documentation: https://dlang.org/phobos/dmd_parse.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/parse.d
12 */
13
14 module dmd.parse;
15
16 import core.stdc.stdio;
17 import core.stdc.string;
18
19 import dmd.astenums;
20 import dmd.errorsink;
21 import dmd.id;
22 import dmd.identifier;
23 import dmd.lexer;
24 import dmd.location;
25 import dmd.root.filename;
26 import dmd.common.outbuffer;
27 import dmd.root.rmem;
28 import dmd.rootobject;
29 import dmd.root.string;
30 import dmd.tokens;
31
32 alias CompileEnv = dmd.lexer.CompileEnv;
33
34 /***********************************************************
35 */
36 class Parser(AST, Lexer = dmd.lexer.Lexer) : Lexer
37 {
38 AST.ModuleDeclaration* md;
39
40 protected
41 {
42 AST.Module mod;
43 LINK linkage;
44 Loc linkLoc;
45 CPPMANGLE cppmangle;
46 Loc endloc; // set to location of last right curly
47 int inBrackets; // inside [] of array index or slice
48 Loc lookingForElse; // location of lonely if looking for an else
49 bool doUnittests; // parse unittest blocks
50 }
51
52 /*********************
53 * Use this constructor for string mixins.
54 * Input:
55 * loc = location in source file of mixin
56 */
57 extern (D) this(Loc loc, AST.Module _module, const(char)[] input, bool doDocComment,
58 ErrorSink errorSink, const CompileEnv* compileEnv, const bool doUnittests) scope
59 {
60 //printf("Parser::Parser()1 %d\n", doUnittests);
61 this(_module, input, doDocComment, errorSink, compileEnv, doUnittests);
62 scanloc = loc;
63 }
64
65 /**************************************************
66 * Main Parser constructor.
67 */
68 extern (D) this(AST.Module _module, const(char)[] input, bool doDocComment, ErrorSink errorSink,
69 const CompileEnv* compileEnv, const bool doUnittests) scope
70 {
71 super(_module ? _module.srcfile.toChars() : null, input.ptr, 0, input.length, doDocComment, false,
72 errorSink,
73 compileEnv);
74
75 //printf("Parser::Parser()2 %d\n", doUnittests);
76 this.mod = _module;
77 this.linkage = LINK.d;
78 this.doUnittests = doUnittests;
79 }
80
81 /++
82 + Parse a module, i.e. the optional `module x.y.z` declaration and all declarations
83 + found in the current file.
84 +
85 + Returns: the list of declarations or an empty list in case of malformed declarations,
86 + the module declaration will be stored as `this.md` if found
87 +/
88 AST.Dsymbols* parseModule()
89 {
90 if (!parseModuleDeclaration())
91 return errorReturn();
92
93 return parseModuleContent();
94 }
95
96 /++
97 + Parse the optional module declaration
98 +
99 + Returns: false if a malformed module declaration was found
100 +/
101 final bool parseModuleDeclaration()
102 {
103 const comment = token.blockComment;
104 bool isdeprecated = false;
105 AST.Expression msg = null;
106
107 // Parse optional module attributes
108 parseModuleAttributes(msg, isdeprecated);
109
110 // ModuleDeclaration leads off
111 if (token.value != TOK.module_)
112 return true;
113
114 const loc = token.loc;
115 nextToken();
116
117 /* parse ModuleFullyQualifiedName
118 * https://dlang.org/spec/module.html#ModuleFullyQualifiedName
119 */
120
121 if (token.value != TOK.identifier)
122 {
123 error("identifier expected following `module`");
124 return false;
125 }
126
127 Identifier[] a;
128 Identifier id = token.ident;
129
130 while (nextToken() == TOK.dot)
131 {
132 a ~= id;
133 nextToken();
134 if (token.value != TOK.identifier)
135 {
136 error("identifier expected following `package`");
137 return false;
138 }
139 id = token.ident;
140 }
141
142 md = new AST.ModuleDeclaration(loc, a, id, msg, isdeprecated);
143
144 if (token.value != TOK.semicolon)
145 error("`;` expected following module declaration instead of `%s`", token.toChars());
146 nextToken();
147 addComment(mod, comment);
148
149 return true;
150 }
151
152 /++
153 + Parse the content of a module, i.e. all declarations found until the end of file.
154 +
155 + Returns: the list of declarations or an empty list in case of malformed declarations
156 +/
157 final AST.Dsymbols* parseModuleContent()
158 {
159 AST.Dsymbol lastDecl = mod;
160 AST.Dsymbols* decldefs = parseDeclDefs(0, &lastDecl);
161
162 if (token.value == TOK.rightCurly)
163 {
164 error("unmatched closing brace");
165 return errorReturn();
166 }
167
168 if (token.value != TOK.endOfFile)
169 {
170 error("unrecognized declaration");
171 return errorReturn();
172 }
173 return decldefs;
174 }
175
176 /++
177 + Skips to the end of the current declaration - denoted by either `;` or EOF
178 +
179 + Returns: An empty list of Dsymbols
180 +/
181 private AST.Dsymbols* errorReturn()
182 {
183 while (token.value != TOK.semicolon && token.value != TOK.endOfFile)
184 nextToken();
185 nextToken();
186 return new AST.Dsymbols();
187 }
188
189 /**********************************
190 * Parse the ModuleAttributes preceding a module declaration.
191 * ModuleDeclaration:
192 * ModuleAttributes(opt) module ModuleFullyQualifiedName ;
193 * https://dlang.org/spec/module.html#ModuleAttributes
194 * Params:
195 * msg = set to the AssignExpression from DeprecatedAttribute https://dlang.org/spec/module.html#DeprecatedAttribute
196 * isdeprecated = set to true if a DeprecatedAttribute is seen
197 */
198 private
199 void parseModuleAttributes(out AST.Expression msg, out bool isdeprecated)
200 {
201 Token* tk;
202 if (!(skipAttributes(&token, &tk) && tk.value == TOK.module_))
203 return; // no module attributes
204
205 AST.Expressions* udas = null;
206 while (token.value != TOK.module_)
207 {
208 switch (token.value)
209 {
210 case TOK.deprecated_:
211 {
212 // deprecated (...) module ...
213 if (isdeprecated)
214 error("there is only one deprecation attribute allowed for module declaration");
215 isdeprecated = true;
216 nextToken();
217 if (token.value == TOK.leftParenthesis)
218 {
219 check(TOK.leftParenthesis);
220 msg = parseAssignExp();
221 check(TOK.rightParenthesis);
222 }
223 break;
224 }
225 case TOK.at:
226 {
227 AST.Expressions* exps = null;
228 const stc = parseAttribute(exps);
229 if (stc & atAttrGroup)
230 {
231 error("`@%s` attribute for module declaration is not supported", token.toChars());
232 }
233 else
234 {
235 static if (is(typeof(mod.edition)))
236 if (exps && exps.length > 0)
237 if (auto id = (*exps)[0].isIdentifierExp())
238 if (id.ident == Id.__edition_latest_do_not_use)
239 {
240 mod.edition = Edition.latest;
241 continue;
242 }
243
244 udas = AST.UserAttributeDeclaration.concat(udas, exps);
245 }
246 if (stc)
247 nextToken();
248 break;
249 }
250 default:
251 {
252 error("`module` expected instead of `%s`", token.toChars());
253 nextToken();
254 break;
255 }
256 }
257 }
258
259 if (udas)
260 {
261 auto a = new AST.Dsymbols();
262 auto udad = new AST.UserAttributeDeclaration(udas, a);
263 mod.userAttribDecl = udad;
264 }
265 }
266
267 final:
268
269 /**
270 * Parses a `deprecated` declaration
271 *
272 * Params:
273 * msg = Deprecated message, if any.
274 * Used to support overriding a deprecated storage class with
275 * a deprecated declaration with a message, but to error
276 * if both declaration have a message.
277 *
278 * Returns:
279 * Whether the deprecated declaration has a message
280 */
281 private bool parseDeprecatedAttribute(ref AST.Expression msg)
282 {
283 if (peekNext() != TOK.leftParenthesis)
284 return false;
285
286 nextToken();
287 check(TOK.leftParenthesis);
288 AST.Expression e = parseAssignExp();
289 check(TOK.rightParenthesis);
290 if (msg)
291 {
292 error(token.loc, "conflicting storage class `deprecated(%s)` and `deprecated(%s)`", msg.toChars(), e.toChars());
293 }
294 msg = e;
295 return true;
296 }
297
298 /************************************
299 * Parse declarations and definitions
300 * Params:
301 * once = !=0 means parse exactly one decl or def
302 * pLastDecl = set to last decl or def parsed
303 * pAttrs = keep track of attributes
304 * Returns:
305 * array of declared symbols
306 */
307 AST.Dsymbols* parseDeclDefs(int once, AST.Dsymbol* pLastDecl = null, PrefixAttributes!AST* pAttrs = null)
308 {
309 AST.Dsymbol lastDecl = null; // used to link unittest to its previous declaration
310 if (!pLastDecl)
311 pLastDecl = &lastDecl;
312
313 const linksave = linkage; // save global state
314
315 //printf("Parser::parseDeclDefs()\n");
316 auto decldefs = new AST.Dsymbols();
317 do
318 {
319 // parse result
320 AST.Dsymbol s = null;
321 AST.Dsymbols* a = null;
322
323 PrefixAttributes!AST attrs;
324 if (!once || !pAttrs)
325 {
326 pAttrs = &attrs;
327 pAttrs.comment = token.blockComment.ptr;
328 }
329 AST.Visibility.Kind prot;
330 STC stc;
331 AST.Condition condition;
332
333 linkage = linksave;
334
335 Loc startloc;
336 Loc scdLoc;
337
338 switch (token.value)
339 {
340 case TOK.enum_:
341 {
342 /* Determine if this is a manifest constant declaration,
343 * or a conventional enum.
344 */
345 const tv = peekNext();
346 if (tv == TOK.leftCurly || tv == TOK.colon)
347 s = parseEnum();
348 else if (tv != TOK.identifier)
349 goto Ldeclaration;
350 else
351 {
352 const nextv = peekNext2();
353 if (nextv == TOK.leftCurly || nextv == TOK.colon || nextv == TOK.semicolon)
354 s = parseEnum();
355 else
356 goto Ldeclaration;
357 }
358 break;
359 }
360 case TOK.import_:
361 a = parseImport();
362 // keep pLastDecl
363 break;
364
365 case TOK.template_:
366 s = cast(AST.Dsymbol)parseTemplateDeclaration();
367 break;
368
369 case TOK.mixin_:
370 {
371 const loc = token.loc;
372 switch (peekNext())
373 {
374 case TOK.leftParenthesis:
375 {
376 // MixinType
377 if (isDeclaration(&token, NeedDeclaratorId.mustIfDstyle, TOK.reserved, null))
378 goto Ldeclaration;
379 // mixin(string)
380 nextToken();
381 auto exps = parseArguments();
382 check(TOK.semicolon);
383 s = new AST.MixinDeclaration(loc, exps);
384 break;
385 }
386 case TOK.template_:
387 // mixin template
388 nextToken();
389 s = cast(AST.Dsymbol)parseTemplateDeclaration(true);
390 break;
391
392 default:
393 s = parseMixin();
394 break;
395 }
396 break;
397 }
398 case TOK.wchar_:
399 case TOK.dchar_:
400 case TOK.bool_:
401 case TOK.char_:
402 case TOK.int8:
403 case TOK.uns8:
404 case TOK.int16:
405 case TOK.uns16:
406 case TOK.int32:
407 case TOK.uns32:
408 case TOK.int64:
409 case TOK.uns64:
410 case TOK.int128:
411 case TOK.uns128:
412 case TOK.float32:
413 case TOK.float64:
414 case TOK.float80:
415 case TOK.imaginary32:
416 case TOK.imaginary64:
417 case TOK.imaginary80:
418 case TOK.complex32:
419 case TOK.complex64:
420 case TOK.complex80:
421 case TOK.void_:
422 case TOK.alias_:
423 case TOK.identifier:
424 case TOK.super_:
425 case TOK.typeof_:
426 case TOK.dot:
427 case TOK.vector:
428 case TOK.struct_:
429 case TOK.union_:
430 case TOK.class_:
431 case TOK.interface_:
432 case TOK.traits:
433 Ldeclaration:
434 a = parseDeclarations(false, pAttrs, pAttrs.comment);
435 if (a && a.length)
436 *pLastDecl = (*a)[a.length - 1];
437 break;
438
439 case TOK.this_:
440 if (peekNext() == TOK.dot)
441 goto Ldeclaration;
442 s = parseCtor(pAttrs);
443 break;
444
445 case TOK.tilde:
446 s = parseDtor(pAttrs);
447 break;
448
449 case TOK.invariant_:
450 const tv = peekNext();
451 if (tv == TOK.leftParenthesis || tv == TOK.leftCurly)
452 {
453 // invariant { statements... }
454 // invariant() { statements... }
455 // invariant (expression);
456 s = parseInvariant(pAttrs);
457 break;
458 }
459 error("invariant body expected, not `%s`", token.toChars());
460 goto Lerror;
461
462 case TOK.unittest_:
463 /**
464 * Ignore unittests in non-root modules.
465 *
466 * This mainly means that unittests *inside templates* are only
467 * ever instantiated if the module lexically declaring the
468 * template is one of the root modules.
469 *
470 * E.g., compiling some project with `-unittest` does NOT
471 * compile and later run any unittests in instantiations of
472 * templates declared in other libraries.
473 *
474 * Declaring unittests *inside* templates is considered an anti-
475 * pattern. In almost all cases, the unittests don't depend on
476 * the template parameters, but instantiate the template with
477 * fixed arguments (e.g., Nullable!T unittests instantiating
478 * Nullable!int), so compiling and running identical tests for
479 * each template instantiation is hardly desirable.
480 * But adding a unittest right below some function being tested
481 * is arguably good for locality, so unittests end up inside
482 * templates.
483 * To make sure a template's unittests are run, it should be
484 * instantiated in the same module, e.g., some module-level
485 * unittest.
486 *
487 * Another reason for ignoring unittests in templates from non-
488 * root modules is for template codegen culling via
489 * TemplateInstance.needsCodegen(). If the compiler decides not
490 * to emit some Nullable!bool because there's an existing
491 * instantiation in some non-root module, it has no idea whether
492 * that module was compiled with -unittest too, and so whether
493 * Nullable!int (instantiated in some unittest inside the
494 * Nullable template) can be culled too. By ignoring unittests
495 * in non-root modules, the compiler won't consider any
496 * template instantiations in these unittests as candidates for
497 * further codegen culling.
498 */
499 // The isRoot check is here because it can change after parsing begins (see dmodule.d)
500 if (doUnittests && mod.isRoot())
501 {
502 linkage = LINK.d; // unittests have D linkage
503 s = parseUnitTest(pAttrs);
504 if (*pLastDecl)
505 (*pLastDecl).ddocUnittest = cast(AST.UnitTestDeclaration)s;
506 }
507 else
508 {
509 // Skip over unittest block by counting { }
510 Loc loc = token.loc;
511 int braces = 0;
512 while (1)
513 {
514 nextToken();
515 switch (token.value)
516 {
517 case TOK.leftCurly:
518 ++braces;
519 continue;
520
521 case TOK.rightCurly:
522 if (--braces)
523 continue;
524 nextToken();
525 break;
526
527 case TOK.endOfFile:
528 /* { */
529 error(loc, "closing `}` of unittest not found before end of file");
530 goto Lerror;
531
532 default:
533 continue;
534 }
535 break;
536 }
537 // Workaround 14894. Add an empty unittest declaration to keep
538 // the number of symbols in this scope independent of -unittest.
539 s = new AST.UnitTestDeclaration(loc, token.loc, STC.none, null);
540 }
541 break;
542
543 case TOK.new_:
544 s = parseNewDeclaration(pAttrs);
545 break;
546
547 case TOK.colon:
548 case TOK.leftCurly:
549 error("declaration expected, not `%s`", token.toChars());
550 goto Lerror;
551
552 case TOK.rightCurly:
553 case TOK.endOfFile:
554 if (once)
555 error("declaration expected, not `%s`", token.toChars());
556 return decldefs;
557
558 case TOK.static_:
559 {
560 const next = peekNext();
561 if (next == TOK.this_)
562 s = parseStaticCtor(pAttrs);
563 else if (next == TOK.tilde)
564 s = parseStaticDtor(pAttrs);
565 else if (next == TOK.assert_)
566 s = parseStaticAssert();
567 else if (next == TOK.if_)
568 {
569 const Loc loc = token.loc;
570 condition = parseStaticIfCondition();
571 AST.Dsymbols* athen;
572 if (token.value == TOK.colon)
573 athen = parseBlock(pLastDecl);
574 else
575 {
576 const lookingForElseSave = lookingForElse;
577 lookingForElse = token.loc;
578 athen = parseBlock(pLastDecl);
579 lookingForElse = lookingForElseSave;
580 }
581 AST.Dsymbols* aelse = null;
582 if (token.value == TOK.else_)
583 {
584 const elseloc = token.loc;
585 nextToken();
586 aelse = parseBlock(pLastDecl);
587 checkDanglingElse(elseloc);
588 }
589 s = new AST.StaticIfDeclaration(loc, condition, athen, aelse);
590 }
591 else if (next == TOK.import_)
592 {
593 a = parseImport();
594 // keep pLastDecl
595 }
596 else if (next == TOK.foreach_ || next == TOK.foreach_reverse_)
597 {
598 s = parseForeach!(AST.StaticForeachDeclaration)(token.loc, pLastDecl);
599 }
600 else
601 {
602 stc = STC.static_;
603 goto Lstc;
604 }
605 break;
606 }
607 case TOK.const_:
608 if (peekNext() == TOK.leftParenthesis)
609 goto Ldeclaration;
610 stc = STC.const_;
611 goto Lstc;
612
613 case TOK.immutable_:
614 if (peekNext() == TOK.leftParenthesis)
615 goto Ldeclaration;
616 stc = STC.immutable_;
617 goto Lstc;
618
619 case TOK.shared_:
620 {
621 const next = peekNext();
622 if (next == TOK.leftParenthesis)
623 goto Ldeclaration;
624 if (next == TOK.static_)
625 {
626 TOK next2 = peekNext2();
627 if (next2 == TOK.this_)
628 {
629 s = parseSharedStaticCtor(pAttrs);
630 break;
631 }
632 if (next2 == TOK.tilde)
633 {
634 s = parseSharedStaticDtor(pAttrs);
635 break;
636 }
637 }
638 stc = STC.shared_;
639 goto Lstc;
640 }
641 case TOK.inout_:
642 if (peekNext() == TOK.leftParenthesis)
643 goto Ldeclaration;
644 stc = STC.wild;
645 goto Lstc;
646
647 case TOK.final_:
648 stc = STC.final_;
649 goto Lstc;
650
651 case TOK.auto_:
652 stc = STC.auto_;
653 if (peekNext() == TOK.ref_)
654 stc |= STC.autoref;
655 goto Lstc;
656
657 case TOK.scope_:
658 stc = STC.scope_;
659 goto Lstc;
660
661 case TOK.override_:
662 stc = STC.override_;
663 goto Lstc;
664
665 case TOK.abstract_:
666 stc = STC.abstract_;
667 goto Lstc;
668
669 case TOK.synchronized_:
670 stc = STC.synchronized_;
671 goto Lstc;
672
673 case TOK.nothrow_:
674 stc = STC.nothrow_;
675 goto Lstc;
676
677 case TOK.pure_:
678 stc = STC.pure_;
679 goto Lstc;
680
681 case TOK.ref_:
682 stc = STC.ref_;
683 goto Lstc;
684
685 case TOK.gshared:
686 stc = STC.gshared;
687 goto Lstc;
688
689 case TOK.at:
690 {
691 AST.Expressions* exps = null;
692 stc = parseAttribute(exps);
693 if (stc)
694 goto Lstc; // it's a predefined attribute
695 // no redundant/conflicting check for UDAs
696 pAttrs.udas = AST.UserAttributeDeclaration.concat(pAttrs.udas, exps);
697 goto Lautodecl;
698 }
699 Lstc:
700 pAttrs.storageClass = appendStorageClass(pAttrs.storageClass, stc);
701 scdLoc = token.loc;
702 nextToken();
703
704 Lautodecl:
705
706 /* Look for auto initializers:
707 * storage_class identifier = initializer;
708 * storage_class identifier(...) = initializer;
709 */
710 if (token.value == TOK.identifier && hasOptionalParensThen(peek(&token), TOK.assign))
711 {
712 a = parseAutoDeclarations(getStorageClass!AST(pAttrs), pAttrs.comment);
713 if (a && a.length)
714 *pLastDecl = (*a)[a.length - 1];
715 if (pAttrs.udas)
716 {
717 s = new AST.UserAttributeDeclaration(pAttrs.udas, a);
718 pAttrs.udas = null;
719 }
720 break;
721 }
722
723 /* Look for return type inference for template functions.
724 */
725 Token* tk;
726 if (token.value == TOK.identifier && skipParens(peek(&token), &tk) && skipAttributes(tk, &tk) &&
727 (tk.value == TOK.leftParenthesis || tk.value == TOK.leftCurly || tk.value == TOK.in_ ||
728 tk.value == TOK.out_ || tk.value == TOK.do_ || tk.value == TOK.goesTo ||
729 tk.value == TOK.identifier && tk.ident == Id._body))
730 {
731 if (tk.value == TOK.identifier && tk.ident == Id._body)
732 usageOfBodyKeyword();
733
734 a = parseDeclarations(true, pAttrs, pAttrs.comment);
735 if (a && a.length)
736 *pLastDecl = (*a)[a.length - 1];
737 if (pAttrs.udas)
738 {
739 s = new AST.UserAttributeDeclaration(pAttrs.udas, a);
740 pAttrs.udas = null;
741 }
742 break;
743 }
744
745 a = parseBlock(pLastDecl, pAttrs);
746 auto stc2 = getStorageClass!AST(pAttrs);
747 if (stc2 != STC.none)
748 {
749 s = new AST.StorageClassDeclaration(scdLoc, stc2, a);
750 }
751 if (pAttrs.udas)
752 {
753 if (s)
754 {
755 a = new AST.Dsymbols();
756 a.push(s);
757 }
758 s = new AST.UserAttributeDeclaration(pAttrs.udas, a);
759 pAttrs.udas = null;
760 }
761 break;
762
763 case TOK.deprecated_:
764 {
765 stc |= STC.deprecated_;
766 if (!parseDeprecatedAttribute(pAttrs.depmsg))
767 goto Lstc;
768
769 a = parseBlock(pLastDecl, pAttrs);
770 s = new AST.DeprecatedDeclaration(pAttrs.depmsg, a);
771 pAttrs.depmsg = null;
772 break;
773 }
774 case TOK.leftBracket:
775 {
776 if (peekNext() == TOK.rightBracket)
777 error("empty attribute list is not allowed");
778 error("use `@(attributes)` instead of `[attributes]`");
779 AST.Expressions* exps = parseArguments();
780 // no redundant/conflicting check for UDAs
781
782 pAttrs.udas = AST.UserAttributeDeclaration.concat(pAttrs.udas, exps);
783 a = parseBlock(pLastDecl, pAttrs);
784 if (pAttrs.udas)
785 {
786 s = new AST.UserAttributeDeclaration(pAttrs.udas, a);
787 pAttrs.udas = null;
788 }
789 break;
790 }
791 case TOK.extern_:
792 {
793 if (peekNext() != TOK.leftParenthesis)
794 {
795 stc = STC.extern_;
796 goto Lstc;
797 }
798
799 const linkLoc = token.loc;
800 auto res = parseLinkage();
801 if (pAttrs.link != LINK.default_)
802 {
803 if (pAttrs.link != res.link)
804 {
805 error(token.loc, "conflicting linkage `extern (%s)` and `extern (%s)`", AST.linkageToChars(pAttrs.link), AST.linkageToChars(res.link));
806 }
807 else if (res.idents || res.identExps || res.cppmangle != CPPMANGLE.def)
808 {
809 // Allow:
810 // extern(C++, foo) extern(C++, bar) void foo();
811 // to be equivalent with:
812 // extern(C++, foo.bar) void foo();
813 // Allow also:
814 // extern(C++, "ns") extern(C++, class) struct test {}
815 // extern(C++, class) extern(C++, "ns") struct test {}
816 }
817 else
818 error("redundant linkage `extern (%s)`", AST.linkageToChars(pAttrs.link));
819 }
820 pAttrs.link = res.link;
821 this.linkage = res.link;
822 this.linkLoc = linkLoc;
823 a = parseBlock(pLastDecl, pAttrs);
824 if (res.idents)
825 {
826 assert(res.link == LINK.cpp);
827 assert(res.idents.length);
828 for (size_t i = res.idents.length; i;)
829 {
830 Identifier id = (*res.idents)[--i];
831 if (s)
832 {
833 a = new AST.Dsymbols();
834 a.push(s);
835 }
836 s = new AST.Nspace(linkLoc, id, null, a);
837 }
838 pAttrs.link = LINK.default_;
839 }
840 else if (res.identExps)
841 {
842 assert(res.link == LINK.cpp);
843 assert(res.identExps.length);
844 for (size_t i = res.identExps.length; i;)
845 {
846 AST.Expression exp = (*res.identExps)[--i];
847 if (s)
848 {
849 a = new AST.Dsymbols();
850 a.push(s);
851 }
852 s = new AST.CPPNamespaceDeclaration(linkLoc, exp, a);
853 }
854 pAttrs.link = LINK.default_;
855 }
856 else if (res.cppmangle != CPPMANGLE.def)
857 {
858 assert(res.link == LINK.cpp);
859 s = new AST.CPPMangleDeclaration(linkLoc, res.cppmangle, a);
860 }
861 else if (pAttrs.link != LINK.default_)
862 {
863 s = new AST.LinkDeclaration(linkLoc, pAttrs.link, a);
864 pAttrs.link = LINK.default_;
865 }
866 break;
867 }
868
869 case TOK.private_:
870 prot = AST.Visibility.Kind.private_;
871 goto Lprot;
872
873 case TOK.package_:
874 prot = AST.Visibility.Kind.package_;
875 goto Lprot;
876
877 case TOK.protected_:
878 prot = AST.Visibility.Kind.protected_;
879 goto Lprot;
880
881 case TOK.public_:
882 prot = AST.Visibility.Kind.public_;
883 goto Lprot;
884
885 case TOK.export_:
886 prot = AST.Visibility.Kind.export_;
887 goto Lprot;
888 Lprot:
889 {
890 if (pAttrs.visibility.kind != AST.Visibility.Kind.undefined)
891 {
892 if (pAttrs.visibility.kind != prot)
893 error(token.loc, "conflicting visibility attribute `%s` and `%s`", AST.visibilityToChars(pAttrs.visibility.kind), AST.visibilityToChars(prot));
894 else
895 error("redundant visibility attribute `%s`", AST.visibilityToChars(prot));
896 }
897 pAttrs.visibility.kind = prot;
898 const attrloc = token.loc;
899
900 nextToken();
901
902 // optional qualified package identifier to bind
903 // visibility to
904 Identifier[] pkg_prot_idents;
905 if (pAttrs.visibility.kind == AST.Visibility.Kind.package_ && token.value == TOK.leftParenthesis)
906 {
907 pkg_prot_idents = parseQualifiedIdentifier("protection package");
908 if (pkg_prot_idents)
909 check(TOK.rightParenthesis);
910 else
911 {
912 while (token.value != TOK.semicolon && token.value != TOK.endOfFile)
913 nextToken();
914 nextToken();
915 break;
916 }
917 }
918
919 a = parseBlock(pLastDecl, pAttrs);
920 if (pAttrs.visibility.kind != AST.Visibility.Kind.undefined)
921 {
922 if (pAttrs.visibility.kind == AST.Visibility.Kind.package_ && pkg_prot_idents)
923 s = new AST.VisibilityDeclaration(attrloc, pkg_prot_idents, a);
924 else
925 s = new AST.VisibilityDeclaration(attrloc, pAttrs.visibility, a);
926
927 pAttrs.visibility = AST.Visibility(AST.Visibility.Kind.undefined);
928 }
929 break;
930 }
931 case TOK.align_:
932 {
933 const attrLoc = token.loc;
934
935 AST.Expression e = parseAlign();
936
937 if (pAttrs.setAlignment)
938 {
939 if (e)
940 error("redundant alignment attribute `align(%s)`", e.toChars());
941 else
942 error("redundant alignment attribute `align(default)`");
943 }
944
945 pAttrs.setAlignment = true;
946 pAttrs.ealign = e;
947 a = parseBlock(pLastDecl, pAttrs);
948 if (pAttrs.setAlignment)
949 {
950 s = new AST.AlignDeclaration(attrLoc, pAttrs.ealign, a);
951 pAttrs.setAlignment = false;
952 pAttrs.ealign = null;
953 }
954 break;
955 }
956 case TOK.pragma_:
957 {
958 AST.Expressions* args = null;
959 const loc = token.loc;
960
961 nextToken();
962 check(TOK.leftParenthesis);
963 if (token.value != TOK.identifier)
964 {
965 error("`pragma(identifier)` expected");
966 goto Lerror;
967 }
968 Identifier ident = token.ident;
969 nextToken();
970 if (token.value == TOK.comma && peekNext() != TOK.rightParenthesis)
971 args = parseArguments(); // pragma(identifier, args...)
972 else
973 check(TOK.rightParenthesis); // pragma(identifier)
974
975 AST.Dsymbols* a2 = null;
976 if (token.value == TOK.semicolon)
977 {
978 /* https://issues.dlang.org/show_bug.cgi?id=2354
979 * Accept single semicolon as an empty
980 * DeclarationBlock following attribute.
981 *
982 * Attribute DeclarationBlock
983 * Pragma DeclDef
984 * ;
985 */
986 nextToken();
987 }
988 else
989 a2 = parseBlock(pLastDecl);
990 s = new AST.PragmaDeclaration(loc, ident, args, a2);
991 break;
992 }
993 case TOK.debug_:
994 startloc = token.loc;
995 nextToken();
996 if (token.value == TOK.assign)
997 {
998 s = parseDebugSpecification();
999 break;
1000 }
1001 condition = parseDebugCondition();
1002 goto Lcondition;
1003
1004 case TOK.version_:
1005 startloc = token.loc;
1006 nextToken();
1007 if (token.value == TOK.assign)
1008 {
1009 s = parseVersionSpecification();
1010 break;
1011 }
1012 condition = parseVersionCondition();
1013 goto Lcondition;
1014
1015 Lcondition:
1016 {
1017 AST.Dsymbols* athen;
1018 if (token.value == TOK.colon)
1019 athen = parseBlock(pLastDecl);
1020 else
1021 {
1022 const lookingForElseSave = lookingForElse;
1023 lookingForElse = token.loc;
1024 athen = parseBlock(pLastDecl);
1025 lookingForElse = lookingForElseSave;
1026 }
1027 AST.Dsymbols* aelse = null;
1028 if (token.value == TOK.else_)
1029 {
1030 const elseloc = token.loc;
1031 nextToken();
1032 aelse = parseBlock(pLastDecl);
1033 checkDanglingElse(elseloc);
1034 }
1035 s = new AST.ConditionalDeclaration(startloc, condition, athen, aelse);
1036 break;
1037 }
1038 case TOK.semicolon:
1039 // empty declaration
1040 //error("empty declaration");
1041 nextToken();
1042 continue;
1043
1044 // The following are all errors, the cases are just for better error messages than the default case
1045 case TOK.return_:
1046 case TOK.goto_:
1047 case TOK.break_:
1048 case TOK.continue_:
1049 error("`%s` statement must be inside function scope", token.toChars());
1050 goto Lerror;
1051 case TOK.asm_:
1052 case TOK.do_:
1053 case TOK.for_:
1054 case TOK.foreach_:
1055 case TOK.foreach_reverse_:
1056 case TOK.if_:
1057 case TOK.switch_:
1058 case TOK.try_:
1059 case TOK.while_:
1060 error("`%s` statement must be inside function scope", token.toChars());
1061 if (peekNext() == TOK.leftParenthesis || peekNext() == TOK.leftCurly)
1062 {
1063 parseStatement(0);
1064 s = null;
1065 continue;
1066 }
1067 goto Lerror;
1068 default:
1069 error("declaration expected, not `%s`", token.toChars());
1070 Lerror:
1071 while (token.value != TOK.semicolon && token.value != TOK.endOfFile)
1072 nextToken();
1073 nextToken();
1074 s = null;
1075 continue;
1076 }
1077
1078 if (s)
1079 {
1080 if (!s.isAttribDeclaration())
1081 *pLastDecl = s;
1082 decldefs.push(s);
1083 addComment(s, pAttrs.comment);
1084 }
1085 else if (a && a.length)
1086 {
1087 decldefs.append(a);
1088 }
1089 }
1090 while (!once);
1091
1092 linkage = linksave;
1093
1094 return decldefs;
1095 }
1096
1097 /*****************************************
1098 * Parse auto declarations of the form:
1099 * storageClass ident = init, ident = init, ... ;
1100 * and return the array of them.
1101 * Starts with token on the first ident.
1102 * Ends with scanner past closing ';'
1103 */
1104 private AST.Dsymbols* parseAutoDeclarations(STC storageClass, const(char)* comment)
1105 {
1106 //printf("parseAutoDeclarations\n");
1107 auto a = new AST.Dsymbols();
1108
1109 while (1)
1110 {
1111 const loc = token.loc;
1112 Identifier ident = token.ident;
1113 nextToken(); // skip over ident
1114
1115 AST.TemplateParameters* tpl = null;
1116 if (token.value == TOK.leftParenthesis)
1117 tpl = parseTemplateParameterList();
1118
1119 check(TOK.assign); // skip over '='
1120 AST.Initializer _init = parseInitializer();
1121 auto v = new AST.VarDeclaration(loc, null, ident, _init, storageClass);
1122
1123 AST.Dsymbol s = v;
1124 if (tpl)
1125 {
1126 auto a2 = new AST.Dsymbols();
1127 a2.push(v);
1128 auto tempdecl = new AST.TemplateDeclaration(loc, ident, tpl, null, a2, 0);
1129 s = tempdecl;
1130 }
1131 a.push(s);
1132 switch (token.value)
1133 {
1134 case TOK.semicolon:
1135 nextToken();
1136 addComment(s, comment);
1137 break;
1138
1139 case TOK.comma:
1140 nextToken();
1141 if (!(token.value == TOK.identifier && hasOptionalParensThen(peek(&token), TOK.assign)))
1142 {
1143 error("identifier expected following comma");
1144 break;
1145 }
1146 addComment(s, comment);
1147 continue;
1148
1149 default:
1150 error("semicolon expected following auto declaration, not `%s`", token.toChars());
1151 break;
1152 }
1153 break;
1154 }
1155 return a;
1156 }
1157
1158 /********************************************
1159 * Parse declarations after an align, visibility, or extern decl.
1160 */
1161 private AST.Dsymbols* parseBlock(AST.Dsymbol* pLastDecl, PrefixAttributes!AST* pAttrs = null)
1162 {
1163 AST.Dsymbols* a = null;
1164
1165 //printf("parseBlock()\n");
1166 switch (token.value)
1167 {
1168 case TOK.semicolon:
1169 error("declaration expected following attribute, not `;`");
1170 nextToken();
1171 break;
1172
1173 case TOK.endOfFile:
1174 error("declaration expected following attribute, not end of file");
1175 break;
1176
1177 case TOK.leftCurly:
1178 {
1179 const lcLoc = token.loc;
1180 const lookingForElseSave = lookingForElse;
1181 lookingForElse = Loc();
1182
1183 nextToken();
1184 a = parseDeclDefs(0, pLastDecl);
1185 if (token.value != TOK.rightCurly)
1186 {
1187 /* left curly brace */
1188 error("matching `}` expected, not `%s`", token.toChars());
1189 eSink.errorSupplemental(lcLoc, "unmatched `{`");
1190 }
1191 else
1192 nextToken();
1193 lookingForElse = lookingForElseSave;
1194 break;
1195 }
1196 case TOK.colon:
1197 nextToken();
1198 a = parseDeclDefs(0, pLastDecl); // grab declarations up to closing curly bracket
1199 break;
1200
1201 default:
1202 a = parseDeclDefs(1, pLastDecl, pAttrs);
1203 break;
1204 }
1205 return a;
1206 }
1207
1208 /**
1209 * Provide an error message if `added` contains storage classes which are
1210 * redundant with those in `orig`; otherwise, return the combination.
1211 *
1212 * Params:
1213 * orig = The already applied storage class.
1214 * added = The new storage class to add to `orig`.
1215 *
1216 * Returns:
1217 * The combination of both storage classes (`orig | added`).
1218 */
1219 private STC appendStorageClass(STC orig, STC added)
1220 {
1221 void checkConflictSTCGroup(bool at = false)(STC group)
1222 {
1223 if (added & group && orig & group & ((orig & group) - 1))
1224 error(
1225 at ? "conflicting attribute `@%s`"
1226 : "conflicting attribute `%s`",
1227 token.toChars());
1228 }
1229
1230 if (orig & added)
1231 {
1232 OutBuffer buf;
1233 AST.stcToBuffer(buf, added);
1234 error("redundant attribute `%s`", buf.peekChars());
1235 return orig | added;
1236 }
1237
1238 const Redundant = (STC.const_ | STC.scope_ | STC.ref_);
1239 orig |= added;
1240
1241 if ((orig & STC.in_) && (added & Redundant))
1242 {
1243 if (added & STC.const_)
1244 error("attribute `const` is redundant with previously-applied `in`");
1245 else if (compileEnv.previewIn)
1246 {
1247 error("attribute `%s` is redundant with previously-applied `in`",
1248 (orig & STC.scope_) ? "scope".ptr : "ref".ptr);
1249 }
1250 else if (added & STC.ref_)
1251 {
1252 // accept using `in ref` for legacy compatibility
1253 }
1254 else
1255 {
1256 version (IN_GCC)
1257 error("attribute `scope` cannot be applied with `in`, use `-fpreview=in` instead");
1258 else
1259 error("attribute `scope` cannot be applied with `in`, use `-preview=in` instead");
1260 }
1261 return orig;
1262 }
1263
1264 if ((added & STC.in_) && (orig & Redundant))
1265 {
1266 if (orig & STC.const_)
1267 error("attribute `in` cannot be added after `const`: remove `const`");
1268 else if (compileEnv.previewIn)
1269 {
1270 // Windows `printf` does not support `%1$s`
1271 const(char*) stc_str = (orig & STC.scope_) ? "scope".ptr : "ref".ptr;
1272 error(token.loc, "attribute `in` cannot be added after `%s`: remove `%s`",
1273 stc_str, stc_str);
1274 }
1275 else if (orig & STC.ref_)
1276 {
1277 // accept using `in ref` for legacy compatibility
1278 }
1279 else
1280 {
1281 version (IN_GCC)
1282 error("attribute `in` cannot be added after `scope`: remove `scope` and use `-fpreview=in`");
1283 else
1284 error("attribute `in` cannot be added after `scope`: remove `scope` and use `-preview=in`");
1285 }
1286 return orig;
1287 }
1288
1289 checkConflictSTCGroup(STC.const_ | STC.immutable_ | STC.manifest);
1290 checkConflictSTCGroup(STC.gshared | STC.shared_);
1291 checkConflictSTCGroup!true(STC.safeGroup);
1292
1293 return orig;
1294 }
1295
1296 /***********************************************
1297 * Parse attribute(s), lexer is on '@'.
1298 *
1299 * Attributes can be builtin (e.g. `@safe`, `@nogc`, etc...),
1300 * or be user-defined (UDAs). In the former case, we return the storage
1301 * class via the return value, while in thelater case we return `0`
1302 * and set `pudas`.
1303 *
1304 * Params:
1305 * pudas = An array of UDAs to append to
1306 *
1307 * Returns:
1308 * If the attribute is builtin, the return value will be non-zero.
1309 * Otherwise, 0 is returned, and `pudas` will be appended to.
1310 */
1311 private STC parseAttribute(ref AST.Expressions* udas)
1312 {
1313 nextToken();
1314 if (token.value == TOK.identifier)
1315 {
1316 // If we find a builtin attribute, we're done, return immediately.
1317 if (STC stc = isBuiltinAtAttribute(token.ident))
1318 return stc;
1319
1320 // Allow identifier, template instantiation, or function call
1321 // for `@Argument` (single UDA) form.
1322 AST.Expression exp = parsePrimaryExp();
1323 if (token.value == TOK.leftParenthesis)
1324 {
1325 const loc = token.loc;
1326 AST.Expressions* args = new AST.Expressions();
1327 AST.Identifiers* names = new AST.Identifiers();
1328 parseNamedArguments(args, names);
1329 exp = new AST.CallExp(loc, exp, args, names);
1330 }
1331
1332 if (udas is null)
1333 udas = new AST.Expressions();
1334 udas.push(exp);
1335 return STC.none;
1336 }
1337
1338 AST.Expression templateArgToExp(RootObject o, Loc loc)
1339 {
1340 switch (o.dyncast)
1341 {
1342 case DYNCAST.expression:
1343 return cast(AST.Expression) o;
1344 case DYNCAST.type:
1345 return new AST.TypeExp(loc, cast(AST.Type)o);
1346 default:
1347 assert(0);
1348 }
1349 }
1350
1351 if (token.value == TOK.leftParenthesis)
1352 {
1353 // Multi-UDAs ( `@( ArgumentList )`) form, concatenate with existing
1354 if (peekNext() == TOK.rightParenthesis)
1355 error("empty attribute list is not allowed");
1356
1357 if (udas is null)
1358 udas = new AST.Expressions();
1359 auto args = parseTemplateArgumentList();
1360 foreach (arg; *args)
1361 udas.push(templateArgToExp(arg, token.loc));
1362 return STC.none;
1363 }
1364
1365 if (auto o = parseTemplateSingleArgument())
1366 {
1367 if (udas is null)
1368 udas = new AST.Expressions();
1369 udas.push(templateArgToExp(o, token.loc));
1370 return STC.none;
1371 }
1372
1373 if (token.isKeyword())
1374 error("`%s` is a keyword, not an `@` attribute", token.toChars());
1375 else
1376 error("`@identifier` or `@(ArgumentList)` expected, not `@%s`", token.toChars());
1377
1378 return STC.none;
1379 }
1380
1381 /***********************************************
1382 * Parse const/immutable/shared/inout/nothrow/pure postfix
1383 */
1384 private STC parsePostfix(STC storageClass, AST.Expressions** pudas)
1385 {
1386 while (1)
1387 {
1388 STC stc;
1389 switch (token.value)
1390 {
1391 case TOK.const_:
1392 stc = STC.const_;
1393 break;
1394
1395 case TOK.immutable_:
1396 stc = STC.immutable_;
1397 break;
1398
1399 case TOK.shared_:
1400 stc = STC.shared_;
1401 break;
1402
1403 case TOK.inout_:
1404 stc = STC.wild;
1405 break;
1406
1407 case TOK.nothrow_:
1408 stc = STC.nothrow_;
1409 break;
1410
1411 case TOK.pure_:
1412 stc = STC.pure_;
1413 break;
1414
1415 case TOK.return_:
1416 stc = STC.return_;
1417 if (peekNext() == TOK.scope_)
1418 stc |= STC.returnScope; // recognize `return scope`
1419 break;
1420
1421 case TOK.scope_:
1422 stc = STC.scope_;
1423 break;
1424
1425 case TOK.rvalue:
1426 stc = STC.rvalue;
1427 break;
1428
1429 case TOK.at:
1430 {
1431 AST.Expressions* udas = null;
1432 stc = parseAttribute(udas);
1433 if (udas)
1434 {
1435 if (pudas)
1436 *pudas = AST.UserAttributeDeclaration.concat(*pudas, udas);
1437 else
1438 {
1439 // Disallow:
1440 // void function() @uda fp;
1441 // () @uda { return 1; }
1442 error("user-defined attributes cannot appear as postfixes");
1443 }
1444 continue;
1445 }
1446 break;
1447 }
1448 default:
1449 Token* tk;
1450 if (skipAttributes(&token, &tk) && tk.ptr != token.ptr ||
1451 token.value == TOK.static_ || token.value == TOK.extern_)
1452 {
1453 error("`%s` token is not allowed in postfix position",
1454 Token.toChars(token.value));
1455 nextToken();
1456 continue;
1457 }
1458 return storageClass;
1459 }
1460 storageClass = appendStorageClass(storageClass, stc);
1461 nextToken();
1462 }
1463 }
1464
1465 private STC parseTypeCtor()
1466 {
1467 STC storageClass = STC.none;
1468
1469 while (1)
1470 {
1471 if (peekNext() == TOK.leftParenthesis)
1472 return storageClass;
1473
1474 STC stc;
1475 switch (token.value)
1476 {
1477 case TOK.const_:
1478 stc = STC.const_;
1479 break;
1480
1481 case TOK.immutable_:
1482 stc = STC.immutable_;
1483 break;
1484
1485 case TOK.shared_:
1486 stc = STC.shared_;
1487 break;
1488
1489 case TOK.inout_:
1490 stc = STC.wild;
1491 break;
1492
1493 default:
1494 return storageClass;
1495 }
1496 storageClass = appendStorageClass(storageClass, stc);
1497 nextToken();
1498 }
1499 }
1500
1501 /**************************************
1502 * Parse constraint.
1503 * Constraint is of the form:
1504 * if ( ConstraintExpression )
1505 */
1506 private AST.Expression parseConstraint()
1507 {
1508 AST.Expression e = null;
1509 if (token.value == TOK.if_)
1510 {
1511 nextToken(); // skip over 'if'
1512 check(TOK.leftParenthesis);
1513 e = parseExpression();
1514 check(TOK.rightParenthesis);
1515 }
1516 return e;
1517 }
1518
1519 /**************************************
1520 * Parse a TemplateDeclaration.
1521 */
1522 private AST.TemplateDeclaration parseTemplateDeclaration(bool ismixin = false)
1523 {
1524 AST.TemplateDeclaration tempdecl;
1525 Identifier id;
1526 AST.TemplateParameters* tpl;
1527 AST.Dsymbols* decldefs;
1528 AST.Expression constraint = null;
1529 const loc = token.loc;
1530
1531 nextToken();
1532 if (token.value != TOK.identifier)
1533 {
1534 error("identifier expected following `template`");
1535 return null;
1536 }
1537 id = token.ident;
1538 nextToken();
1539 tpl = parseTemplateParameterList();
1540 if (!tpl)
1541 return null;
1542
1543 constraint = parseConstraint();
1544
1545 if (token.value != TOK.leftCurly)
1546 {
1547 error("`{` expected after template parameter list, not `%s`", token.toChars()); /* } */
1548 nextToken();
1549 return null;
1550 }
1551 decldefs = parseBlock(null);
1552
1553 tempdecl = new AST.TemplateDeclaration(loc, id, tpl, constraint, decldefs, ismixin);
1554 return tempdecl;
1555 }
1556
1557 /******************************************
1558 * Parse template parameter list.
1559 * Input:
1560 * flag 0: parsing "( list )"
1561 * 1: parsing non-empty "list $(RPAREN)"
1562 */
1563 private AST.TemplateParameters* parseTemplateParameterList(int flag = 0)
1564 {
1565 auto tpl = new AST.TemplateParameters();
1566
1567 if (!flag && token.value != TOK.leftParenthesis)
1568 {
1569 error("parenthesized template parameter list expected following template identifier");
1570 goto Lerr;
1571 }
1572 nextToken();
1573
1574 // Get array of TemplateParameters
1575 if (flag || token.value != TOK.rightParenthesis)
1576 {
1577 while (token.value != TOK.rightParenthesis)
1578 {
1579 AST.TemplateParameter tp;
1580 Loc loc;
1581 Identifier tp_ident = null;
1582 AST.Type tp_spectype = null;
1583 AST.Type tp_valtype = null;
1584 AST.Type tp_defaulttype = null;
1585 AST.Expression tp_specvalue = null;
1586 AST.Expression tp_defaultvalue = null;
1587
1588 // Get TemplateParameter
1589
1590 // First, look ahead to see if it is a TypeParameter or a ValueParameter
1591 const tv = peekNext();
1592 if (token.value == TOK.alias_)
1593 {
1594 // AliasParameter
1595 nextToken();
1596 loc = token.loc; // todo
1597 AST.Type spectype = null;
1598 if (isDeclaration(&token, NeedDeclaratorId.must, TOK.reserved, null))
1599 {
1600 spectype = parseType(&tp_ident);
1601 }
1602 else
1603 {
1604 if (token.value != TOK.identifier)
1605 {
1606 error("identifier expected for template `alias` parameter");
1607 goto Lerr;
1608 }
1609 tp_ident = token.ident;
1610 nextToken();
1611 }
1612 RootObject spec = null;
1613 if (token.value == TOK.colon) // : Type
1614 {
1615 nextToken();
1616 if (isDeclaration(&token, NeedDeclaratorId.no, TOK.reserved, null))
1617 spec = parseType();
1618 else
1619 spec = parseCondExp();
1620 }
1621 RootObject def = null;
1622 if (token.value == TOK.assign) // = Type
1623 {
1624 nextToken();
1625 if (isDeclaration(&token, NeedDeclaratorId.no, TOK.reserved, null))
1626 def = parseType();
1627 else
1628 def = parseCondExp();
1629 }
1630 tp = new AST.TemplateAliasParameter(loc, tp_ident, spectype, spec, def);
1631 }
1632 else if (tv == TOK.colon || tv == TOK.assign || tv == TOK.comma || tv == TOK.rightParenthesis)
1633 {
1634 // TypeParameter
1635 if (token.value != TOK.identifier)
1636 {
1637 error("identifier expected for template type parameter");
1638 goto Lerr;
1639 }
1640 loc = token.loc;
1641 tp_ident = token.ident;
1642 nextToken();
1643 if (token.value == TOK.colon) // : Type
1644 {
1645 nextToken();
1646 tp_spectype = parseType();
1647 }
1648 if (token.value == TOK.assign) // = Type
1649 {
1650 nextToken();
1651 tp_defaulttype = parseType();
1652 }
1653 tp = new AST.TemplateTypeParameter(loc, tp_ident, tp_spectype, tp_defaulttype);
1654 }
1655 else if (token.value == TOK.identifier && tv == TOK.dotDotDot)
1656 {
1657 // ident...
1658 loc = token.loc;
1659 tp_ident = token.ident;
1660 nextToken();
1661 nextToken();
1662 tp = new AST.TemplateTupleParameter(loc, tp_ident);
1663 }
1664 else if (token.value == TOK.this_)
1665 {
1666 // ThisParameter
1667 nextToken();
1668 if (token.value != TOK.identifier)
1669 {
1670 error("identifier expected for template `this` parameter");
1671 goto Lerr;
1672 }
1673 loc = token.loc;
1674 tp_ident = token.ident;
1675 nextToken();
1676 if (token.value == TOK.colon) // : Type
1677 {
1678 nextToken();
1679 tp_spectype = parseType();
1680 }
1681 if (token.value == TOK.assign) // = Type
1682 {
1683 nextToken();
1684 tp_defaulttype = parseType();
1685 }
1686 tp = new AST.TemplateThisParameter(loc, tp_ident, tp_spectype, tp_defaulttype);
1687 }
1688 else
1689 {
1690 // ValueParameter
1691 loc = token.loc; // todo
1692 tp_valtype = parseType(&tp_ident);
1693 if (!tp_ident)
1694 {
1695 error("identifier expected for template value parameter");
1696 tp_ident = Identifier.idPool("error");
1697 }
1698 if (token.value == TOK.colon) // : CondExpression
1699 {
1700 nextToken();
1701 tp_specvalue = parseCondExp();
1702 }
1703 if (token.value == TOK.assign) // = CondExpression
1704 {
1705 nextToken();
1706 tp_defaultvalue = parseAssignExp();
1707 }
1708 tp = new AST.TemplateValueParameter(loc, tp_ident, tp_valtype, tp_specvalue, tp_defaultvalue);
1709 }
1710 tpl.push(tp);
1711 if (token.value != TOK.comma)
1712 break;
1713 nextToken();
1714 }
1715 }
1716 check(TOK.rightParenthesis);
1717
1718 Lerr:
1719 return tpl;
1720 }
1721
1722 /******************************************
1723 * Parse template mixin.
1724 * mixin Foo;
1725 * mixin Foo!(args);
1726 * mixin a.b.c!(args).Foo!(args);
1727 * mixin typeof(expr).identifier!(args);
1728 * mixin Foo!(args) identifier;
1729 * mixin identifier = Foo!(args);
1730 */
1731 private AST.Dsymbol parseMixin()
1732 {
1733 AST.TemplateMixin tm;
1734 Identifier id, name;
1735 AST.Objects* tiargs;
1736
1737 //printf("parseMixin()\n");
1738 const locMixin = token.loc;
1739 nextToken(); // skip 'mixin'
1740
1741 // mixin Identifier = MixinTemplateName TemplateArguments;
1742 if (token.value == TOK.identifier && peekNext() == TOK.assign)
1743 {
1744 name = token.ident;
1745 nextToken();
1746 nextToken();
1747 }
1748
1749 auto loc = token.loc;
1750 AST.TypeQualified tqual = null;
1751 if (token.value == TOK.dot)
1752 {
1753 id = Id.empty;
1754 }
1755 else
1756 {
1757 if (token.value == TOK.typeof_)
1758 {
1759 tqual = parseTypeof();
1760 check(TOK.dot);
1761 }
1762 if (token.value != TOK.identifier)
1763 {
1764 error("identifier expected, not `%s`", token.toChars());
1765 id = Id.empty;
1766 }
1767 else
1768 id = token.ident;
1769 nextToken();
1770 }
1771
1772 while (1)
1773 {
1774 tiargs = null;
1775 if (token.value == TOK.not)
1776 {
1777 tiargs = parseTemplateArguments();
1778 }
1779
1780 if (tiargs && token.value == TOK.dot)
1781 {
1782 auto tempinst = new AST.TemplateInstance(loc, id, tiargs);
1783 if (!tqual)
1784 tqual = new AST.TypeInstance(loc, tempinst);
1785 else
1786 tqual.addInst(tempinst);
1787 tiargs = null;
1788 }
1789 else
1790 {
1791 if (!tqual)
1792 tqual = new AST.TypeIdentifier(loc, id);
1793 else
1794 tqual.addIdent(id);
1795 }
1796
1797 if (token.value != TOK.dot)
1798 break;
1799
1800 nextToken();
1801 if (token.value != TOK.identifier)
1802 {
1803 error("identifier expected following `.` instead of `%s`", token.toChars());
1804 break;
1805 }
1806 loc = token.loc;
1807 id = token.ident;
1808 nextToken();
1809 }
1810
1811 // mixin MixinTemplateName TemplateArguments Identifier;
1812 if (!name && token.value == TOK.identifier)
1813 {
1814 name = token.ident;
1815 nextToken();
1816 }
1817
1818 tm = new AST.TemplateMixin(locMixin, name, tqual, tiargs);
1819 if (token.value != TOK.semicolon)
1820 error("`;` expected after `mixin`");
1821 nextToken();
1822
1823 return tm;
1824 }
1825
1826 /******************************************
1827 * Parse template arguments.
1828 * Input:
1829 * current token is opening '!'
1830 * Output:
1831 * current token is one after closing '$(RPAREN)'
1832 */
1833 private AST.Objects* parseTemplateArguments()
1834 {
1835 AST.Objects* tiargs;
1836
1837 nextToken();
1838 if (token.value == TOK.leftParenthesis)
1839 {
1840 // ident!(template_arguments)
1841 tiargs = parseTemplateArgumentList();
1842 }
1843 else
1844 {
1845 // ident!template_argument
1846 RootObject o = parseTemplateSingleArgument();
1847 if (!o)
1848 {
1849 error("template argument expected following `!`");
1850 }
1851 else
1852 {
1853 tiargs = new AST.Objects();
1854 tiargs.push(o);
1855 }
1856 }
1857 if (token.value == TOK.not)
1858 {
1859 TOK tok = peekNext();
1860 if (tok != TOK.is_ && tok != TOK.in_)
1861 {
1862 error("multiple ! arguments are not allowed");
1863 Lagain:
1864 nextToken();
1865 if (token.value == TOK.leftParenthesis)
1866 parseTemplateArgumentList();
1867 else
1868 parseTemplateSingleArgument();
1869 if (token.value == TOK.not && (tok = peekNext()) != TOK.is_ && tok != TOK.in_)
1870 goto Lagain;
1871 }
1872 }
1873 return tiargs;
1874 }
1875
1876 /******************************************
1877 * Parse template argument list.
1878 * Input:
1879 * current token is opening '$(LPAREN)',
1880 * or ',' for __traits
1881 * Output:
1882 * current token is one after closing '$(RPAREN)'
1883 */
1884 private AST.Objects* parseTemplateArgumentList()
1885 {
1886 //printf("Parser::parseTemplateArgumentList()\n");
1887 auto tiargs = new AST.Objects();
1888 TOK endtok = TOK.rightParenthesis;
1889 assert(token.value == TOK.leftParenthesis || token.value == TOK.comma);
1890 nextToken();
1891
1892 // Get TemplateArgumentList
1893 while (token.value != endtok)
1894 {
1895 tiargs.push(parseTypeOrAssignExp());
1896 if (token.value != TOK.comma)
1897 break;
1898 nextToken();
1899 }
1900 check(endtok, "template argument list");
1901 return tiargs;
1902 }
1903
1904 /***************************************
1905 * Parse a Type or an Expression
1906 * Returns:
1907 * RootObject representing the AST
1908 */
1909 RootObject parseTypeOrAssignExp(TOK endtoken = TOK.reserved)
1910 {
1911 return isDeclaration(&token, NeedDeclaratorId.no, endtoken, null)
1912 ? parseType() // argument is a type
1913 : parseAssignExp(); // argument is an expression
1914 }
1915
1916 /*****************************
1917 * Parse single template argument, to support the syntax:
1918 * foo!arg
1919 * Input:
1920 * current token is the arg
1921 * Returns: An AST.Type, AST.Expression, or `null` on error
1922 */
1923 private RootObject parseTemplateSingleArgument()
1924 {
1925 //printf("parseTemplateSingleArgument()\n");
1926 AST.Type ta;
1927 switch (token.value)
1928 {
1929 case TOK.identifier:
1930 ta = new AST.TypeIdentifier(token.loc, token.ident);
1931 goto LabelX;
1932
1933 case TOK.vector:
1934 ta = parseVector();
1935 goto LabelX;
1936
1937 case TOK.void_:
1938 ta = AST.Type.tvoid;
1939 goto LabelX;
1940
1941 case TOK.int8:
1942 ta = AST.Type.tint8;
1943 goto LabelX;
1944
1945 case TOK.uns8:
1946 ta = AST.Type.tuns8;
1947 goto LabelX;
1948
1949 case TOK.int16:
1950 ta = AST.Type.tint16;
1951 goto LabelX;
1952
1953 case TOK.uns16:
1954 ta = AST.Type.tuns16;
1955 goto LabelX;
1956
1957 case TOK.int32:
1958 ta = AST.Type.tint32;
1959 goto LabelX;
1960
1961 case TOK.uns32:
1962 ta = AST.Type.tuns32;
1963 goto LabelX;
1964
1965 case TOK.int64:
1966 ta = AST.Type.tint64;
1967 goto LabelX;
1968
1969 case TOK.uns64:
1970 ta = AST.Type.tuns64;
1971 goto LabelX;
1972
1973 case TOK.int128:
1974 ta = AST.Type.tint128;
1975 goto LabelX;
1976
1977 case TOK.uns128:
1978 ta = AST.Type.tuns128;
1979 goto LabelX;
1980
1981 case TOK.float32:
1982 ta = AST.Type.tfloat32;
1983 goto LabelX;
1984
1985 case TOK.float64:
1986 ta = AST.Type.tfloat64;
1987 goto LabelX;
1988
1989 case TOK.float80:
1990 ta = AST.Type.tfloat80;
1991 goto LabelX;
1992
1993 case TOK.imaginary32:
1994 ta = AST.Type.timaginary32;
1995 goto LabelX;
1996
1997 case TOK.imaginary64:
1998 ta = AST.Type.timaginary64;
1999 goto LabelX;
2000
2001 case TOK.imaginary80:
2002 ta = AST.Type.timaginary80;
2003 goto LabelX;
2004
2005 case TOK.complex32:
2006 ta = AST.Type.tcomplex32;
2007 goto LabelX;
2008
2009 case TOK.complex64:
2010 ta = AST.Type.tcomplex64;
2011 goto LabelX;
2012
2013 case TOK.complex80:
2014 ta = AST.Type.tcomplex80;
2015 goto LabelX;
2016
2017 case TOK.bool_:
2018 ta = AST.Type.tbool;
2019 goto LabelX;
2020
2021 case TOK.char_:
2022 ta = AST.Type.tchar;
2023 goto LabelX;
2024
2025 case TOK.wchar_:
2026 ta = AST.Type.twchar;
2027 goto LabelX;
2028
2029 case TOK.dchar_:
2030 ta = AST.Type.tdchar;
2031 goto LabelX;
2032 LabelX:
2033 nextToken();
2034 return ta;
2035
2036 case TOK.int32Literal:
2037 case TOK.uns32Literal:
2038 case TOK.int64Literal:
2039 case TOK.uns64Literal:
2040 case TOK.int128Literal:
2041 case TOK.uns128Literal:
2042 case TOK.float32Literal:
2043 case TOK.float64Literal:
2044 case TOK.float80Literal:
2045 case TOK.imaginary32Literal:
2046 case TOK.imaginary64Literal:
2047 case TOK.imaginary80Literal:
2048 case TOK.null_:
2049 case TOK.true_:
2050 case TOK.false_:
2051 case TOK.charLiteral:
2052 case TOK.wcharLiteral:
2053 case TOK.dcharLiteral:
2054 case TOK.string_:
2055 case TOK.interpolated:
2056 case TOK.hexadecimalString:
2057 case TOK.file:
2058 case TOK.fileFullPath:
2059 case TOK.line:
2060 case TOK.moduleString:
2061 case TOK.functionString:
2062 case TOK.prettyFunction:
2063 case TOK.this_:
2064 {
2065 // Template argument is an expression
2066 return parsePrimaryExp();
2067 }
2068 default:
2069 return null;
2070 }
2071 }
2072
2073 /**********************************
2074 * Parse a static assertion.
2075 * Current token is 'static'.
2076 */
2077 private AST.StaticAssert parseStaticAssert()
2078 {
2079 const loc = token.loc;
2080 AST.Expression exp;
2081 AST.Expressions* msg = null;
2082
2083 //printf("parseStaticAssert()\n");
2084 nextToken();
2085 nextToken();
2086 check(TOK.leftParenthesis);
2087 exp = parseAssignExp();
2088 if (token.value == TOK.comma)
2089 {
2090 if (peekNext() == TOK.rightParenthesis)
2091 {
2092 nextToken(); // consume `,`
2093 nextToken(); // consume `)`
2094 }
2095 else
2096 msg = parseArguments();
2097 }
2098 else
2099 check(TOK.rightParenthesis);
2100 check(TOK.semicolon, "static assert");
2101 return new AST.StaticAssert(loc, exp, msg);
2102 }
2103
2104 /***********************************
2105 * Parse typeof(expression).
2106 * Current token is on the 'typeof'.
2107 */
2108 private AST.TypeQualified parseTypeof()
2109 {
2110 AST.TypeQualified t;
2111 const loc = token.loc;
2112
2113 nextToken();
2114 check(TOK.leftParenthesis);
2115 if (token.value == TOK.return_) // typeof(return)
2116 {
2117 nextToken();
2118 t = new AST.TypeReturn(loc);
2119 }
2120 else
2121 {
2122 AST.Expression exp = parseExpression(); // typeof(expression)
2123 t = new AST.TypeTypeof(loc, exp);
2124 }
2125 check(TOK.rightParenthesis);
2126 return t;
2127 }
2128
2129 /***********************************
2130 * Parse __vector(type).
2131 * Current token is on the '__vector'.
2132 */
2133 private AST.Type parseVector()
2134 {
2135 nextToken();
2136 check(TOK.leftParenthesis);
2137 AST.Type tb = parseType();
2138 check(TOK.rightParenthesis);
2139 return new AST.TypeVector(tb);
2140 }
2141
2142 /***********************************
2143 * Parse:
2144 * extern (linkage)
2145 * extern (C++, namespaces)
2146 * extern (C++, "namespace", "namespaces", ...)
2147 * extern (C++, (StringExp))
2148 * The parser is on the 'extern' token.
2149 */
2150 private ParsedLinkage!(AST) parseLinkage()
2151 {
2152 ParsedLinkage!(AST) result;
2153 nextToken();
2154 assert(token.value == TOK.leftParenthesis);
2155 nextToken();
2156 ParsedLinkage!(AST) returnLinkage(LINK link)
2157 {
2158 check(TOK.rightParenthesis);
2159 result.link = link;
2160 return result;
2161 }
2162 ParsedLinkage!(AST) invalidLinkage()
2163 {
2164 error("valid linkage identifiers are `D`, `C`, `C++`, `Objective-C`, `Windows`, `System`");
2165 return returnLinkage(LINK.d);
2166 }
2167
2168 if (token.value != TOK.identifier)
2169 return returnLinkage(LINK.d);
2170
2171 Identifier id = token.ident;
2172 nextToken();
2173 if (id == Id.Windows)
2174 return returnLinkage(LINK.windows);
2175 if (id == Id.D)
2176 return returnLinkage(LINK.d);
2177 if (id == Id.System)
2178 return returnLinkage(LINK.system);
2179 if (id == Id.Objective) // Looking for tokens "Objective-C"
2180 {
2181 if (token.value != TOK.min)
2182 return invalidLinkage();
2183
2184 nextToken();
2185 if (token.ident != Id.C)
2186 return invalidLinkage();
2187
2188 nextToken();
2189 return returnLinkage(LINK.objc);
2190 }
2191 else if (id != Id.C)
2192 return invalidLinkage();
2193
2194 if (token.value != TOK.plusPlus)
2195 return returnLinkage(LINK.c);
2196
2197 nextToken();
2198 if (token.value != TOK.comma) // , namespaces or class or struct
2199 return returnLinkage(LINK.cpp);
2200
2201 nextToken();
2202
2203 if (token.value == TOK.rightParenthesis)
2204 return returnLinkage(LINK.cpp); // extern(C++,)
2205
2206 if (token.value == TOK.class_ || token.value == TOK.struct_)
2207 {
2208 result.cppmangle = token.value == TOK.class_ ? CPPMANGLE.asClass : CPPMANGLE.asStruct;
2209 nextToken();
2210 }
2211 else if (token.value == TOK.identifier) // named scope namespace
2212 {
2213 result.idents = new AST.Identifiers();
2214 while (1)
2215 {
2216 Identifier idn = token.ident;
2217 result.idents.push(idn);
2218 nextToken();
2219 if (token.value == TOK.dot)
2220 {
2221 nextToken();
2222 if (token.value == TOK.identifier)
2223 continue;
2224 error("identifier expected for C++ namespace");
2225 result.idents = null; // error occurred, invalidate list of elements.
2226 }
2227 break;
2228 }
2229 }
2230 else // non-scoped StringExp namespace
2231 {
2232 result.identExps = new AST.Expressions();
2233 while (1)
2234 {
2235 result.identExps.push(parseCondExp());
2236 if (token.value != TOK.comma)
2237 break;
2238 nextToken();
2239 // Allow trailing commas as done for argument lists, arrays, ...
2240 if (token.value == TOK.rightParenthesis)
2241 break;
2242 }
2243 }
2244 return returnLinkage(LINK.cpp);
2245 }
2246
2247 /***********************************
2248 * Parse ident1.ident2.ident3
2249 *
2250 * Params:
2251 * entity = what qualified identifier is expected to resolve into.
2252 * Used only for better error message
2253 *
2254 * Returns:
2255 * array of identifiers with actual qualified one stored last
2256 */
2257 private Identifier[] parseQualifiedIdentifier(const(char)* entity)
2258 {
2259 Identifier[] qualified;
2260
2261 do
2262 {
2263 nextToken();
2264 if (token.value != TOK.identifier)
2265 {
2266 error(token.loc, "`%s` expected as dot-separated identifiers, got `%s`", entity, token.toChars());
2267 return qualified;
2268 }
2269
2270 Identifier id = token.ident;
2271 qualified ~= id;
2272
2273 nextToken();
2274 }
2275 while (token.value == TOK.dot);
2276
2277 return qualified;
2278 }
2279
2280 private AST.DebugSymbol parseDebugSpecification()
2281 {
2282 AST.DebugSymbol s;
2283 nextToken();
2284 if (token.value == TOK.identifier)
2285 s = new AST.DebugSymbol(token.loc, token.ident);
2286 else
2287 {
2288 error("identifier expected, not `%s`", token.toChars());
2289 s = null;
2290 }
2291 nextToken();
2292 if (token.value != TOK.semicolon)
2293 error("semicolon expected");
2294 nextToken();
2295 return s;
2296 }
2297
2298 /**************************************
2299 * Parse a debug conditional
2300 */
2301 private AST.Condition parseDebugCondition()
2302 {
2303 Identifier id = null;
2304 Loc loc = token.loc;
2305
2306 if (token.value == TOK.leftParenthesis)
2307 {
2308 nextToken();
2309
2310 if (token.value == TOK.identifier)
2311 id = token.ident;
2312 else
2313 error("identifier expected inside `debug(...)`, not `%s`", token.toChars());
2314 loc = token.loc;
2315 nextToken();
2316 check(TOK.rightParenthesis);
2317 }
2318 return new AST.DebugCondition(loc, mod, id);
2319 }
2320
2321 /**************************************
2322 * Parse a version specification
2323 */
2324 private AST.VersionSymbol parseVersionSpecification()
2325 {
2326 AST.VersionSymbol s;
2327 nextToken();
2328 if (token.value == TOK.identifier)
2329 s = new AST.VersionSymbol(token.loc, token.ident);
2330 else
2331 {
2332 error("identifier expected, not `%s`", token.toChars());
2333 s = null;
2334 }
2335 nextToken();
2336 if (token.value != TOK.semicolon)
2337 error("semicolon expected");
2338 nextToken();
2339 return s;
2340 }
2341
2342 /**************************************
2343 * Parse a version conditional
2344 */
2345 private AST.Condition parseVersionCondition()
2346 {
2347 Identifier id = null;
2348 Loc loc;
2349
2350 if (token.value == TOK.leftParenthesis)
2351 {
2352 nextToken();
2353 /* Allow:
2354 * version (unittest)
2355 * version (assert)
2356 * even though they are keywords
2357 */
2358 loc = token.loc;
2359 if (token.value == TOK.identifier)
2360 id = token.ident;
2361 else if (token.value == TOK.unittest_)
2362 id = Identifier.idPool(Token.toString(TOK.unittest_));
2363 else if (token.value == TOK.assert_)
2364 id = Identifier.idPool(Token.toString(TOK.assert_));
2365 else
2366 error("identifier expected inside `version(...)`, not `%s`", token.toChars());
2367 nextToken();
2368 check(TOK.rightParenthesis);
2369 }
2370 else
2371 error("(condition) expected following `version`");
2372 return new AST.VersionCondition(loc, mod, id);
2373 }
2374
2375 /***********************************************
2376 * static if (expression)
2377 * body
2378 * else
2379 * body
2380 * Current token is 'static'.
2381 */
2382 private AST.Condition parseStaticIfCondition()
2383 {
2384 AST.Expression exp;
2385 AST.Condition condition;
2386 const loc = token.loc;
2387
2388 nextToken();
2389 nextToken();
2390 if (token.value == TOK.leftParenthesis)
2391 {
2392 nextToken();
2393 exp = parseAssignExp();
2394 check(TOK.rightParenthesis);
2395 }
2396 else
2397 {
2398 error("(expression) expected following `static if`");
2399 exp = null;
2400 }
2401 condition = new AST.StaticIfCondition(loc, exp);
2402 return condition;
2403 }
2404
2405 /*****************************************
2406 * Parse a constructor definition:
2407 * this(parameters) { body }
2408 * or postblit:
2409 * this(this) { body }
2410 * or constructor template:
2411 * this(templateparameters)(parameters) { body }
2412 * Current token is 'this'.
2413 */
2414 private AST.Dsymbol parseCtor(PrefixAttributes!AST* pAttrs)
2415 {
2416 AST.Expressions* udas = null;
2417 const loc = token.loc;
2418 STC stc = getStorageClass!AST(pAttrs);
2419
2420 nextToken();
2421 if (token.value == TOK.leftParenthesis && peekNext() == TOK.this_ && peekNext2() == TOK.rightParenthesis)
2422 {
2423 // this(this) { ... }
2424 nextToken();
2425 nextToken();
2426 check(TOK.rightParenthesis);
2427
2428 stc = parsePostfix(stc, &udas);
2429 if (stc & STC.immutable_)
2430 deprecation("`immutable` postblit is deprecated. Please use an unqualified postblit.");
2431 if (stc & STC.shared_)
2432 deprecation("`shared` postblit is deprecated. Please use an unqualified postblit.");
2433 if (stc & STC.const_)
2434 deprecation("`const` postblit is deprecated. Please use an unqualified postblit.");
2435 if (stc & STC.static_)
2436 error(loc, "postblit cannot be `static`");
2437
2438 auto f = new AST.PostBlitDeclaration(loc, Loc.initial, stc, Id.postblit);
2439 AST.Dsymbol s = parseContracts(f);
2440 if (udas)
2441 {
2442 auto a = new AST.Dsymbols();
2443 a.push(f);
2444 s = new AST.UserAttributeDeclaration(udas, a);
2445 }
2446 return s;
2447 }
2448
2449 /* Look ahead to see if:
2450 * this(...)(...)
2451 * which is a constructor template
2452 */
2453 AST.TemplateParameters* tpl = null;
2454 if (token.value == TOK.leftParenthesis && peekPastParen(&token).value == TOK.leftParenthesis)
2455 {
2456 tpl = parseTemplateParameterList();
2457 }
2458
2459 /* Just a regular constructor
2460 */
2461 auto parameterList = parseParameterList(null);
2462 stc = parsePostfix(stc, &udas);
2463
2464 if (parameterList.varargs != VarArg.none || AST.Parameter.dim(parameterList.parameters) != 0)
2465 {
2466 if (stc & STC.static_)
2467 error(loc, "constructor cannot be static");
2468 }
2469 else if (STC ss = stc & (STC.shared_ | STC.static_)) // this()
2470 {
2471 if (ss == STC.static_)
2472 error(loc, "use `static this()` to declare a static constructor");
2473 else if (ss == (STC.shared_ | STC.static_))
2474 error(loc, "use `shared static this()` to declare a shared static constructor");
2475 }
2476
2477 AST.Expression constraint = tpl ? parseConstraint() : null;
2478
2479 AST.Type tf = new AST.TypeFunction(parameterList, null, linkage, stc); // ReturnType -> auto
2480 tf = tf.addSTC(stc);
2481
2482 auto f = new AST.CtorDeclaration(loc, Loc.initial, stc, tf);
2483 AST.Dsymbol s = parseContracts(f, !!tpl);
2484 if (udas)
2485 {
2486 auto a = new AST.Dsymbols();
2487 a.push(f);
2488 s = new AST.UserAttributeDeclaration(udas, a);
2489 }
2490
2491 if (tpl)
2492 {
2493 // Wrap a template around it
2494 auto decldefs = new AST.Dsymbols();
2495 decldefs.push(s);
2496 s = new AST.TemplateDeclaration(loc, f.ident, tpl, constraint, decldefs);
2497 }
2498
2499 return s;
2500 }
2501
2502 /*****************************************
2503 * Parse a destructor definition:
2504 * ~this() { body }
2505 * Current token is '~'.
2506 */
2507 private AST.Dsymbol parseDtor(PrefixAttributes!AST* pAttrs)
2508 {
2509 AST.Expressions* udas = null;
2510 const loc = token.loc;
2511 STC stc = getStorageClass!AST(pAttrs);
2512
2513 nextToken();
2514 check(TOK.this_);
2515 check(TOK.leftParenthesis);
2516 check(TOK.rightParenthesis);
2517
2518 stc = parsePostfix(stc, &udas);
2519 if (STC ss = stc & (STC.shared_ | STC.static_))
2520 {
2521 if (ss == STC.static_)
2522 error(loc, "use `static ~this()` to declare a static destructor");
2523 else if (ss == (STC.shared_ | STC.static_))
2524 error(loc, "use `shared static ~this()` to declare a shared static destructor");
2525 }
2526
2527 auto f = new AST.DtorDeclaration(loc, Loc.initial, stc, Id.dtor);
2528 AST.Dsymbol s = parseContracts(f);
2529 if (udas)
2530 {
2531 auto a = new AST.Dsymbols();
2532 a.push(f);
2533 s = new AST.UserAttributeDeclaration(udas, a);
2534 }
2535 return s;
2536 }
2537
2538 /*****************************************
2539 * Parse a static constructor definition:
2540 * static this() { body }
2541 * Current token is 'static'.
2542 */
2543 private AST.Dsymbol parseStaticCtor(PrefixAttributes!AST* pAttrs)
2544 {
2545 //Expressions *udas = NULL;
2546 const loc = token.loc;
2547 STC stc = getStorageClass!AST(pAttrs);
2548
2549 nextToken();
2550 nextToken();
2551 check(TOK.leftParenthesis);
2552 check(TOK.rightParenthesis);
2553
2554 stc = parsePostfix(stc & ~STC.TYPECTOR, null) | stc;
2555 if (stc & STC.shared_)
2556 error(loc, "use `shared static this()` to declare a shared static constructor");
2557 else if (stc & STC.static_)
2558 appendStorageClass(stc, STC.static_); // complaint for the redundancy
2559 else if (STC modStc = stc & STC.TYPECTOR)
2560 {
2561 OutBuffer buf;
2562 AST.stcToBuffer(buf, modStc);
2563 error(loc, "static constructor cannot be `%s`", buf.peekChars());
2564 }
2565 stc &= ~(STC.static_ | STC.TYPECTOR);
2566
2567 auto f = new AST.StaticCtorDeclaration(loc, Loc.initial, stc);
2568 AST.Dsymbol s = parseContracts(f);
2569 return s;
2570 }
2571
2572 /*****************************************
2573 * Parse a static destructor definition:
2574 * static ~this() { body }
2575 * Current token is 'static'.
2576 */
2577 private AST.Dsymbol parseStaticDtor(PrefixAttributes!AST* pAttrs)
2578 {
2579 AST.Expressions* udas = null;
2580 const loc = token.loc;
2581 STC stc = getStorageClass!AST(pAttrs);
2582
2583 nextToken();
2584 nextToken();
2585 check(TOK.this_);
2586 check(TOK.leftParenthesis);
2587 check(TOK.rightParenthesis);
2588
2589 stc = parsePostfix(stc & ~STC.TYPECTOR, &udas) | stc;
2590 if (stc & STC.shared_)
2591 error(loc, "use `shared static ~this()` to declare a shared static destructor");
2592 else if (stc & STC.static_)
2593 appendStorageClass(stc, STC.static_); // complaint for the redundancy
2594 else if (STC modStc = stc & STC.TYPECTOR)
2595 {
2596 OutBuffer buf;
2597 AST.stcToBuffer(buf, modStc);
2598 error(loc, "static destructor cannot be `%s`", buf.peekChars());
2599 }
2600 stc &= ~(STC.static_ | STC.TYPECTOR);
2601
2602 auto f = new AST.StaticDtorDeclaration(loc, Loc.initial, stc);
2603 AST.Dsymbol s = parseContracts(f);
2604 if (udas)
2605 {
2606 auto a = new AST.Dsymbols();
2607 a.push(f);
2608 s = new AST.UserAttributeDeclaration(udas, a);
2609 }
2610 return s;
2611 }
2612
2613 /*****************************************
2614 * Parse a shared static constructor definition:
2615 * shared static this() { body }
2616 * Current token is 'shared'.
2617 */
2618 private AST.Dsymbol parseSharedStaticCtor(PrefixAttributes!AST* pAttrs)
2619 {
2620 //Expressions *udas = NULL;
2621 const loc = token.loc;
2622 STC stc = getStorageClass!AST(pAttrs);
2623
2624 nextToken();
2625 nextToken();
2626 nextToken();
2627 check(TOK.leftParenthesis);
2628 check(TOK.rightParenthesis);
2629
2630 stc = parsePostfix(stc & ~STC.TYPECTOR, null) | stc;
2631 if (STC ss = stc & (STC.shared_ | STC.static_))
2632 appendStorageClass(stc, ss); // complaint for the redundancy
2633 else if (STC modStc = stc & STC.TYPECTOR)
2634 {
2635 OutBuffer buf;
2636 AST.stcToBuffer(buf, modStc);
2637 error(loc, "shared static constructor cannot be `%s`", buf.peekChars());
2638 }
2639 stc &= ~(STC.static_ | STC.TYPECTOR);
2640
2641 auto f = new AST.SharedStaticCtorDeclaration(loc, Loc.initial, stc);
2642 AST.Dsymbol s = parseContracts(f);
2643 return s;
2644 }
2645
2646 /*****************************************
2647 * Parse a shared static destructor definition:
2648 * shared static ~this() { body }
2649 * Current token is 'shared'.
2650 */
2651 private AST.Dsymbol parseSharedStaticDtor(PrefixAttributes!AST* pAttrs)
2652 {
2653 AST.Expressions* udas = null;
2654 const loc = token.loc;
2655 STC stc = getStorageClass!AST(pAttrs);
2656
2657 nextToken();
2658 nextToken();
2659 nextToken();
2660 check(TOK.this_);
2661 check(TOK.leftParenthesis);
2662 check(TOK.rightParenthesis);
2663
2664 stc = parsePostfix(stc & ~STC.TYPECTOR, &udas) | stc;
2665 if (STC ss = stc & (STC.shared_ | STC.static_))
2666 appendStorageClass(stc, ss); // complaint for the redundancy
2667 else if (STC modStc = stc & STC.TYPECTOR)
2668 {
2669 OutBuffer buf;
2670 AST.stcToBuffer(buf, modStc);
2671 error(loc, "shared static destructor cannot be `%s`", buf.peekChars());
2672 }
2673 stc &= ~(STC.static_ | STC.TYPECTOR);
2674
2675 auto f = new AST.SharedStaticDtorDeclaration(loc, Loc.initial, stc);
2676 AST.Dsymbol s = parseContracts(f);
2677 if (udas)
2678 {
2679 auto a = new AST.Dsymbols();
2680 a.push(f);
2681 s = new AST.UserAttributeDeclaration(udas, a);
2682 }
2683 return s;
2684 }
2685
2686 /*****************************************
2687 * Parse an invariant definition:
2688 * invariant { statements... }
2689 * invariant() { statements... }
2690 * invariant (expression);
2691 * Current token is 'invariant'.
2692 */
2693 private AST.Dsymbol parseInvariant(PrefixAttributes!AST* pAttrs)
2694 {
2695 const loc = token.loc;
2696 STC stc = getStorageClass!AST(pAttrs);
2697
2698 nextToken();
2699 if (token.value == TOK.leftParenthesis) // optional () or invariant (expression);
2700 {
2701 nextToken();
2702 if (token.value != TOK.rightParenthesis) // invariant (expression);
2703 {
2704 AST.Expression e = parseAssignExp(), msg = null;
2705 if (token.value == TOK.comma)
2706 {
2707 nextToken();
2708 if (token.value != TOK.rightParenthesis)
2709 {
2710 msg = parseAssignExp();
2711 if (token.value == TOK.comma)
2712 nextToken();
2713 }
2714 }
2715 check(TOK.rightParenthesis);
2716 check(TOK.semicolon, "invariant");
2717 e = new AST.AssertExp(loc, e, msg);
2718 auto fbody = new AST.ExpStatement(loc, e);
2719 auto f = new AST.InvariantDeclaration(loc, token.loc, stc, null, fbody);
2720 return f;
2721 }
2722 nextToken();
2723 }
2724
2725 auto fbody = parseStatement(ParseStatementFlags.curly);
2726 auto f = new AST.InvariantDeclaration(loc, token.loc, stc, null, fbody);
2727 return f;
2728 }
2729
2730 /*****************************************
2731 * Parse a unittest definition:
2732 * unittest { body }
2733 * Current token is 'unittest'.
2734 */
2735 private AST.Dsymbol parseUnitTest(PrefixAttributes!AST* pAttrs)
2736 {
2737 const loc = token.loc;
2738 STC stc = getStorageClass!AST(pAttrs);
2739
2740 nextToken();
2741
2742 const(char)* begPtr = token.ptr + 1; // skip left curly brace
2743 const(char)* endPtr = null;
2744 AST.Statement sbody = parseStatement(ParseStatementFlags.curly, &endPtr);
2745
2746 /** Extract unittest body as a string. Must be done eagerly since memory
2747 will be released by the lexer before doc gen. */
2748 char* docline = null;
2749 if (compileEnv.ddocOutput && endPtr > begPtr)
2750 {
2751 /* Remove trailing whitespaces */
2752 for (const(char)* p = endPtr - 1; begPtr <= p && (*p == ' ' || *p == '\r' || *p == '\n' || *p == '\t'); --p)
2753 {
2754 endPtr = p;
2755 }
2756
2757 size_t len = endPtr - begPtr;
2758 if (len > 0)
2759 {
2760 docline = cast(char*)mem.xmalloc_noscan(len + 2);
2761 memcpy(docline, begPtr, len);
2762 docline[len] = '\n'; // Terminate all lines by LF
2763 docline[len + 1] = '\0';
2764 }
2765 }
2766
2767 auto f = new AST.UnitTestDeclaration(loc, token.loc, stc, docline);
2768 f.fbody = sbody;
2769 return f;
2770 }
2771
2772 /*****************************************
2773 * Parse a new definition:
2774 * @disable new();
2775 * Current token is 'new'.
2776 */
2777 private AST.Dsymbol parseNewDeclaration(PrefixAttributes!AST* pAttrs)
2778 {
2779 const loc = token.loc;
2780 STC stc = getStorageClass!AST(pAttrs);
2781 if (!(stc & STC.disable))
2782 {
2783 error("`new` allocator must be annotated with `@disabled`");
2784 }
2785 nextToken();
2786 check(TOK.leftParenthesis);
2787 check(TOK.rightParenthesis);
2788 check(TOK.semicolon);
2789 return new AST.NewDeclaration(loc, stc);
2790 }
2791
2792 /**********************************************
2793 * Parse parameter list.
2794 */
2795 private AST.ParameterList parseParameterList(AST.TemplateParameters** tpl)
2796 {
2797 auto parameters = new AST.Parameters();
2798 VarArg varargs = VarArg.none;
2799 STC varargsStc;
2800
2801 // Attributes allowed for ...
2802 enum VarArgsStc = STC.const_ | STC.immutable_ | STC.shared_ | STC.scope_ | STC.return_ | STC.returnScope;
2803
2804 check(TOK.leftParenthesis);
2805 while (1)
2806 {
2807 Identifier ai = null;
2808 AST.Type at;
2809 STC storageClass = STC.none;
2810 STC stc;
2811 AST.Expression ae;
2812 AST.Expressions* udas = null;
2813 for (; 1; nextToken())
2814 {
2815 L3:
2816 switch (token.value)
2817 {
2818 case TOK.rightParenthesis:
2819 if (storageClass != 0 || udas !is null)
2820 error("basic type expected, not `)`");
2821 break;
2822
2823 case TOK.dotDotDot:
2824 varargs = VarArg.variadic;
2825 varargsStc = storageClass;
2826 if (varargsStc & ~VarArgsStc)
2827 {
2828 OutBuffer buf;
2829 AST.stcToBuffer(buf, varargsStc & ~VarArgsStc);
2830 error("variadic parameter cannot have attributes `%s`", buf.peekChars());
2831 varargsStc &= VarArgsStc;
2832 }
2833 nextToken();
2834 break;
2835
2836 case TOK.const_:
2837 if (peekNext() == TOK.leftParenthesis)
2838 goto default;
2839 stc = STC.const_;
2840 goto L2;
2841
2842 case TOK.immutable_:
2843 if (peekNext() == TOK.leftParenthesis)
2844 goto default;
2845 stc = STC.immutable_;
2846 goto L2;
2847
2848 case TOK.shared_:
2849 if (peekNext() == TOK.leftParenthesis)
2850 goto default;
2851 stc = STC.shared_;
2852 goto L2;
2853
2854 case TOK.inout_:
2855 if (peekNext() == TOK.leftParenthesis)
2856 goto default;
2857 stc = STC.wild;
2858 goto L2;
2859 case TOK.at:
2860 {
2861 AST.Expressions* exps = null;
2862 STC stc2 = parseAttribute(exps);
2863 if (stc2 & atAttrGroup)
2864 {
2865 error("`@%s` attribute for function parameter is not supported", token.toChars());
2866 }
2867 else
2868 {
2869 udas = AST.UserAttributeDeclaration.concat(udas, exps);
2870 }
2871 if (token.value == TOK.dotDotDot)
2872 error("variadic parameter cannot have user-defined attributes");
2873 if (stc2)
2874 nextToken();
2875 goto L3;
2876 // Don't call nextToken again.
2877 }
2878 case TOK.in_:
2879 if (compileEnv.transitionIn)
2880 eSink.message(scanloc, "Usage of 'in' on parameter");
2881 stc = STC.in_;
2882 if (compileEnv.previewIn)
2883 stc |= STC.constscoperef;
2884 goto L2;
2885
2886 case TOK.out_:
2887 stc = STC.out_;
2888 goto L2;
2889
2890 case TOK.ref_:
2891 stc = STC.ref_;
2892 goto L2;
2893
2894 case TOK.lazy_:
2895 stc = STC.lazy_;
2896 goto L2;
2897
2898 case TOK.scope_:
2899 stc = STC.scope_;
2900 goto L2;
2901
2902 case TOK.final_:
2903 stc = STC.final_;
2904 goto L2;
2905
2906 case TOK.auto_:
2907 stc = STC.auto_;
2908 if (peekNext() == TOK.ref_)
2909 stc |= STC.autoref;
2910 goto L2;
2911
2912 case TOK.return_:
2913 stc = STC.return_;
2914 if (peekNext() == TOK.scope_)
2915 stc |= STC.returnScope;
2916 goto L2;
2917 L2:
2918 storageClass = appendStorageClass(storageClass, stc);
2919 continue;
2920
2921 default:
2922 {
2923 const stcx = storageClass & (STC.in_ | STC.ref_ | STC.out_ | STC.lazy_);
2924 // if stcx is not a power of 2
2925 if (stcx & (stcx - 1) && !(stcx == (STC.in_ | STC.ref_)))
2926 error("incompatible parameter storage classes");
2927
2928 // Deprecated in 2.111
2929 if ((storageClass & STC.auto_) && (storageClass & STC.ref_) && !(storageClass & STC.autoref))
2930 deprecation("`auto` and `ref` storage classes should be adjacent");
2931
2932 const tv = peekNext();
2933 Loc loc;
2934 if (tpl && token.value == TOK.identifier &&
2935 (tv == TOK.comma || tv == TOK.rightParenthesis || tv == TOK.dotDotDot))
2936 {
2937 Identifier id = Identifier.generateId("__T");
2938 loc = token.loc;
2939 at = new AST.TypeIdentifier(loc, id);
2940 if (!*tpl)
2941 *tpl = new AST.TemplateParameters();
2942 AST.TemplateParameter tp = new AST.TemplateTypeParameter(loc, id, null, null);
2943 (*tpl).push(tp);
2944
2945 ai = token.ident;
2946 nextToken();
2947 }
2948 else
2949 {
2950 at = parseType(&ai, null, &loc);
2951 }
2952 ae = null;
2953 if (token.value == TOK.assign) // = defaultArg
2954 {
2955 nextToken();
2956 ae = parseAssignExp();
2957 }
2958 auto param = new AST.Parameter(loc, storageClass | STC.parameter, at, ai, ae, null);
2959 if (udas)
2960 {
2961 auto a = new AST.Dsymbols();
2962 auto udad = new AST.UserAttributeDeclaration(udas, a);
2963 param.userAttribDecl = udad;
2964 }
2965 if (token.value == TOK.at)
2966 {
2967 AST.Expressions* exps = null;
2968 STC stc2 = parseAttribute(exps);
2969 if (stc2 & atAttrGroup)
2970 {
2971 error("`@%s` attribute for function parameter is not supported", token.toChars());
2972 }
2973 else
2974 {
2975 error("user-defined attributes cannot appear as postfixes", token.toChars());
2976 }
2977 if (stc2)
2978 nextToken();
2979 }
2980 if (token.value == TOK.dotDotDot)
2981 {
2982 /* This is:
2983 * at ai ...
2984 */
2985 if (storageClass & (STC.out_ | STC.ref_))
2986 error("variadic argument cannot be `out` or `ref`");
2987 varargs = VarArg.typesafe;
2988 parameters.push(param);
2989 nextToken();
2990 break;
2991 }
2992 parameters.push(param);
2993 if (token.value == TOK.comma)
2994 {
2995 nextToken();
2996 goto L1;
2997 }
2998 break;
2999 }
3000 }
3001 break;
3002 }
3003 break;
3004
3005 L1:
3006 }
3007 check(TOK.rightParenthesis);
3008 return AST.ParameterList(parameters, varargs, varargsStc);
3009 }
3010
3011 /*************************************
3012 */
3013 private AST.EnumDeclaration parseEnum()
3014 {
3015 AST.EnumDeclaration e;
3016 Identifier id;
3017 AST.Type memtype;
3018 auto loc = token.loc;
3019
3020 // printf("Parser::parseEnum()\n");
3021 nextToken();
3022 id = null;
3023 if (token.value == TOK.identifier)
3024 {
3025 id = token.ident;
3026 nextToken();
3027 }
3028
3029 memtype = null;
3030 if (token.value == TOK.colon)
3031 {
3032 nextToken();
3033 int alt = 0;
3034 const typeLoc = token.loc;
3035 memtype = parseBasicType();
3036 memtype = parseDeclarator(memtype, alt, null);
3037 checkCstyleTypeSyntax(typeLoc, memtype, alt, null);
3038 }
3039
3040 e = new AST.EnumDeclaration(loc, id, memtype);
3041 // opaque type
3042 if (token.value == TOK.semicolon && id)
3043 nextToken();
3044 else if (token.value == TOK.leftCurly)
3045 {
3046 bool isAnonymousEnum = !id;
3047
3048 //printf("enum definition\n");
3049 e.members = new AST.Dsymbols();
3050 nextToken();
3051 const(char)[] comment = token.blockComment;
3052 while (token.value != TOK.rightCurly)
3053 {
3054 /* Can take the following forms...
3055 * 1. ident
3056 * 2. ident = value
3057 * 3. type ident = value
3058 * ... prefixed by valid attributes
3059 */
3060 loc = token.loc;
3061
3062 AST.Type type = null;
3063 Identifier ident = null;
3064
3065 AST.Expressions* udas;
3066 STC stc;
3067 AST.Expression deprecationMessage;
3068 enum attributeErrorMessage = "`%s` is not a valid attribute for enum members";
3069 Lattrs:
3070 while (1)
3071 {
3072 switch (token.value)
3073 {
3074 case TOK.at:
3075 if (STC _stc = parseAttribute(udas))
3076 {
3077 if (_stc == STC.disable)
3078 stc |= _stc;
3079 else
3080 {
3081 OutBuffer buf;
3082 AST.stcToBuffer(buf, _stc);
3083 error(attributeErrorMessage, buf.peekChars());
3084 }
3085 nextToken();
3086 }
3087 break;
3088 case TOK.deprecated_:
3089 stc |= STC.deprecated_;
3090 if (!parseDeprecatedAttribute(deprecationMessage))
3091 {
3092 nextToken();
3093 }
3094 break;
3095 default:
3096 break Lattrs;
3097 }
3098 }
3099 if (token.value == TOK.identifier)
3100 {
3101 const tv = peekNext();
3102 if (tv == TOK.assign || tv == TOK.comma || tv == TOK.rightCurly)
3103 {
3104 ident = token.ident;
3105 type = null;
3106 nextToken();
3107 }
3108 else
3109 {
3110 if (isAnonymousEnum)
3111 goto Ltype;
3112
3113 nextToken();
3114 error("expected `,` or `=` after identifier, not `%s`", token.toChars());
3115 }
3116 }
3117 else
3118 {
3119 if (isAnonymousEnum)
3120 {
3121 Ltype:
3122 // Type identifier
3123 type = parseType(&ident, null);
3124 if (type == AST.Type.terror)
3125 {
3126 type = null;
3127 nextToken();
3128 }
3129 else if (!ident)
3130 {
3131 error("no identifier for declarator `%s`", type.toChars());
3132 type = null;
3133 }
3134 else
3135 {
3136 const tv = token.value;
3137 if (tv != TOK.assign && tv != TOK.comma && tv != TOK.rightCurly)
3138 {
3139 error("expected `,` or `=` after identifier, not `%s`", token.toChars());
3140 nextToken();
3141 }
3142 }
3143 }
3144 else
3145 {
3146 Token* t = &token;
3147 if (isBasicType(&t))
3148 {
3149 error("named enum cannot declare member with type", (*t).toChars());
3150 nextToken();
3151 }
3152 else
3153 check(TOK.identifier);
3154
3155 // avoid extra error messages
3156 const tv = token.value;
3157 if (tv != TOK.assign && tv != TOK.comma && tv != TOK.rightCurly && tv != TOK.endOfFile)
3158 continue;
3159 }
3160 }
3161
3162 AST.Expression value;
3163 if (token.value == TOK.assign)
3164 {
3165 nextToken();
3166 value = parseAssignExp();
3167 }
3168 else
3169 {
3170 value = null;
3171 if (type && isAnonymousEnum)
3172 error("initializer required after `%s` when type is specified", ident.toChars());
3173 }
3174
3175 AST.DeprecatedDeclaration dd;
3176 if (deprecationMessage)
3177 {
3178 dd = new AST.DeprecatedDeclaration(deprecationMessage, null);
3179 stc |= STC.deprecated_;
3180 }
3181
3182 auto em = new AST.EnumMember(loc, ident, value, type, stc, null, dd);
3183 e.members.push(em);
3184
3185 if (udas)
3186 {
3187 auto uad = new AST.UserAttributeDeclaration(udas, new AST.Dsymbols());
3188 em.userAttribDecl = uad;
3189 }
3190
3191 if (token.value != TOK.rightCurly)
3192 {
3193 addComment(em, comment);
3194 comment = null;
3195 check(TOK.comma);
3196 }
3197 addComment(em, comment);
3198 comment = token.blockComment;
3199
3200 if (token.value == TOK.endOfFile)
3201 {
3202 error("premature end of file");
3203 break;
3204 }
3205 }
3206 nextToken();
3207 }
3208 else
3209 {
3210 nextToken();
3211 error("expected `{`, not `%s` for enum declaration", token.toChars());
3212 }
3213 //printf("-parseEnum() %s\n", e.toChars());
3214 return e;
3215 }
3216
3217 /********************************
3218 * Parse struct, union, interface, class.
3219 */
3220 private AST.Dsymbol parseAggregate()
3221 {
3222 AST.TemplateParameters* tpl = null;
3223 AST.Expression constraint;
3224 const loc = token.loc;
3225 TOK tok = token.value;
3226
3227 //printf("Parser::parseAggregate()\n");
3228 nextToken();
3229 Identifier id;
3230 if (token.value != TOK.identifier)
3231 {
3232 id = null;
3233 }
3234 else
3235 {
3236 id = token.ident;
3237 nextToken();
3238
3239 if (token.value == TOK.leftParenthesis)
3240 {
3241 // struct/class template declaration.
3242 tpl = parseTemplateParameterList();
3243 constraint = parseConstraint();
3244 }
3245 }
3246
3247 // Collect base class(es)
3248 AST.BaseClasses* baseclasses = null;
3249 if (token.value == TOK.colon)
3250 {
3251 if (tok != TOK.interface_ && tok != TOK.class_)
3252 error("base classes are not allowed for `%s`, did you mean `;`?", Token.toChars(tok));
3253 nextToken();
3254 baseclasses = parseBaseClasses();
3255 }
3256
3257 if (token.value == TOK.if_)
3258 {
3259 if (constraint)
3260 error("template constraints appear both before and after BaseClassList, put them before");
3261 constraint = parseConstraint();
3262 }
3263 if (constraint)
3264 {
3265 if (!id)
3266 error("template constraints not allowed for anonymous `%s`", Token.toChars(tok));
3267 if (!tpl)
3268 error("template constraints only allowed for templates");
3269 }
3270
3271 AST.Dsymbols* members = null;
3272 if (token.value == TOK.leftCurly)
3273 {
3274 //printf("aggregate definition\n");
3275 const lookingForElseSave = lookingForElse;
3276 lookingForElse = Loc();
3277 nextToken();
3278 members = parseDeclDefs(0);
3279 lookingForElse = lookingForElseSave;
3280 if (token.value != TOK.rightCurly)
3281 {
3282 /* { */
3283 error(token.loc, "`}` expected following members in `%s` declaration",
3284 Token.toChars(tok));
3285 if (id)
3286 eSink.errorSupplemental(loc, "%s `%s` starts here",
3287 Token.toChars(tok), id.toChars());
3288 else
3289 eSink.errorSupplemental(loc, "%s starts here",
3290 Token.toChars(tok));
3291 }
3292 nextToken();
3293 }
3294 else if (token.value == TOK.semicolon && id)
3295 {
3296 if (baseclasses || constraint)
3297 error("members expected");
3298 nextToken();
3299 }
3300 else
3301 {
3302 error(token.loc, "{ } expected following `%s` declaration", Token.toChars(tok));
3303 }
3304
3305 AST.AggregateDeclaration a;
3306 switch (tok)
3307 {
3308 case TOK.interface_:
3309 if (!id)
3310 error(loc, "anonymous interfaces not allowed");
3311 a = new AST.InterfaceDeclaration(loc, id, baseclasses);
3312 a.members = members;
3313 break;
3314
3315 case TOK.class_:
3316 if (!id)
3317 error(loc, "anonymous classes not allowed");
3318 bool inObject = md && !md.packages && md.id == Id.object;
3319 a = new AST.ClassDeclaration(loc, id, baseclasses, members, inObject);
3320 break;
3321
3322 case TOK.struct_:
3323 if (id)
3324 {
3325 bool inObject = md && !md.packages && md.id == Id.object;
3326 a = new AST.StructDeclaration(loc, id, inObject);
3327 a.members = members;
3328 }
3329 else
3330 {
3331 /* Anonymous structs/unions are more like attributes.
3332 */
3333 assert(!tpl);
3334 return new AST.AnonDeclaration(loc, false, members);
3335 }
3336 break;
3337
3338 case TOK.union_:
3339 if (id)
3340 {
3341 a = new AST.UnionDeclaration(loc, id);
3342 a.members = members;
3343 }
3344 else
3345 {
3346 /* Anonymous structs/unions are more like attributes.
3347 */
3348 assert(!tpl);
3349 return new AST.AnonDeclaration(loc, true, members);
3350 }
3351 break;
3352
3353 default:
3354 assert(0);
3355 }
3356
3357 if (tpl)
3358 {
3359 // Wrap a template around the aggregate declaration
3360 auto decldefs = new AST.Dsymbols();
3361 decldefs.push(a);
3362 auto tempdecl = new AST.TemplateDeclaration(loc, id, tpl, constraint, decldefs);
3363 return tempdecl;
3364 }
3365 return a;
3366 }
3367
3368 /*******************************************
3369 */
3370 private AST.BaseClasses* parseBaseClasses()
3371 {
3372 auto baseclasses = new AST.BaseClasses();
3373
3374 for (; 1; nextToken())
3375 {
3376 auto b = new AST.BaseClass(parseBasicType());
3377 baseclasses.push(b);
3378 if (token.value != TOK.comma)
3379 break;
3380 }
3381 return baseclasses;
3382 }
3383
3384 AST.Dsymbols* parseImport()
3385 {
3386 auto decldefs = new AST.Dsymbols();
3387 Identifier aliasid = null;
3388
3389 int isstatic = token.value == TOK.static_;
3390 if (isstatic)
3391 nextToken();
3392
3393 //printf("Parser::parseImport()\n");
3394 do
3395 {
3396 L1:
3397 nextToken();
3398 if (token.value != TOK.identifier)
3399 {
3400 error("identifier expected following `import`");
3401 break;
3402 }
3403
3404 const loc = token.loc;
3405 Identifier id = token.ident;
3406 Identifier[] a;
3407 nextToken();
3408 if (!aliasid && token.value == TOK.assign)
3409 {
3410 aliasid = id;
3411 goto L1;
3412 }
3413 while (token.value == TOK.dot)
3414 {
3415 a ~= id;
3416 nextToken();
3417 if (token.value != TOK.identifier)
3418 {
3419 error("identifier expected following `package`");
3420 break;
3421 }
3422 id = token.ident;
3423 nextToken();
3424 }
3425
3426 auto s = new AST.Import(loc, a, id, aliasid, isstatic);
3427 decldefs.push(s);
3428
3429 /* Look for
3430 * : alias=name, alias=name;
3431 * syntax.
3432 */
3433 if (token.value == TOK.colon)
3434 {
3435 do
3436 {
3437 nextToken();
3438 if (token.value != TOK.identifier)
3439 {
3440 error("identifier expected following `:`");
3441 break;
3442 }
3443 Identifier _alias = token.ident;
3444 Identifier name;
3445 nextToken();
3446 if (token.value == TOK.assign)
3447 {
3448 nextToken();
3449 if (token.value != TOK.identifier)
3450 {
3451 error("identifier expected following `%s=`", _alias.toChars());
3452 break;
3453 }
3454 name = token.ident;
3455 nextToken();
3456 }
3457 else
3458 {
3459 name = _alias;
3460 _alias = null;
3461 }
3462 if (s.isstatic)
3463 error(loc, "static import `%s` cannot have an import bind list", s.toPrettyChars());
3464 if (!s.aliasId)
3465 s.ident = null; // make it an anonymous import
3466 s.names.push(name);
3467 s.aliases.push(_alias);
3468 }
3469 while (token.value == TOK.comma);
3470 break; // no comma-separated imports of this form
3471 }
3472 aliasid = null;
3473 }
3474 while (token.value == TOK.comma);
3475
3476 if (token.value == TOK.semicolon)
3477 nextToken();
3478 else
3479 {
3480 error("`;` expected");
3481 nextToken();
3482 }
3483
3484 return decldefs;
3485 }
3486
3487 /* Parse a type and optional identifier
3488 * Params:
3489 * pident = set to Identifier if there is one, null if not
3490 * ptpl = if !null, then set to TemplateParameterList
3491 * pdeclLoc = if !null, then set to location of the declarator
3492 */
3493 AST.Type parseType(Identifier* pident = null, AST.TemplateParameters** ptpl = null, Loc* pdeclLoc = null)
3494 {
3495 /* Take care of the storage class prefixes that
3496 * serve as type attributes:
3497 * const type
3498 * immutable type
3499 * shared type
3500 * inout type
3501 * inout const type
3502 * shared const type
3503 * shared inout type
3504 * shared inout const type
3505 */
3506 STC stc = STC.none;
3507 while (1)
3508 {
3509 switch (token.value)
3510 {
3511 case TOK.const_:
3512 if (peekNext() == TOK.leftParenthesis)
3513 break; // const as type constructor
3514 stc |= STC.const_; // const as storage class
3515 nextToken();
3516 continue;
3517
3518 case TOK.immutable_:
3519 if (peekNext() == TOK.leftParenthesis)
3520 break;
3521 stc |= STC.immutable_;
3522 nextToken();
3523 continue;
3524
3525 case TOK.shared_:
3526 if (peekNext() == TOK.leftParenthesis)
3527 break;
3528 stc |= STC.shared_;
3529 nextToken();
3530 continue;
3531
3532 case TOK.inout_:
3533 if (peekNext() == TOK.leftParenthesis)
3534 break;
3535 stc |= STC.wild;
3536 nextToken();
3537 continue;
3538
3539 default:
3540 break;
3541 }
3542 break;
3543 }
3544
3545 const typeLoc = token.loc;
3546
3547 AST.Type t;
3548 t = parseBasicType();
3549
3550 if (pdeclLoc)
3551 *pdeclLoc = token.loc;
3552 int alt = 0;
3553 t = parseDeclarator(t, alt, pident, ptpl);
3554 checkCstyleTypeSyntax(typeLoc, t, alt, pident ? *pident : null);
3555
3556 t = t.addSTC(stc);
3557 return t;
3558 }
3559
3560 private AST.Type parseBasicType(bool dontLookDotIdents = false)
3561 {
3562 AST.Type t;
3563 Loc loc;
3564 Identifier id;
3565 //printf("parseBasicType()\n");
3566 switch (token.value)
3567 {
3568 case TOK.void_:
3569 t = AST.Type.tvoid;
3570 goto LabelX;
3571
3572 case TOK.int8:
3573 t = AST.Type.tint8;
3574 goto LabelX;
3575
3576 case TOK.uns8:
3577 t = AST.Type.tuns8;
3578 goto LabelX;
3579
3580 case TOK.int16:
3581 t = AST.Type.tint16;
3582 goto LabelX;
3583
3584 case TOK.uns16:
3585 t = AST.Type.tuns16;
3586 goto LabelX;
3587
3588 case TOK.int32:
3589 t = AST.Type.tint32;
3590 goto LabelX;
3591
3592 case TOK.uns32:
3593 t = AST.Type.tuns32;
3594 goto LabelX;
3595
3596 case TOK.int64:
3597 t = AST.Type.tint64;
3598 nextToken();
3599 if (token.value == TOK.int64) // if `long long`
3600 {
3601 error("use `long` for a 64 bit integer instead of `long long`");
3602 nextToken();
3603 }
3604 else if (token.value == TOK.float64) // if `long double`
3605 {
3606 error("use `real` instead of `long double`");
3607 t = AST.Type.tfloat80;
3608 nextToken();
3609 }
3610 break;
3611
3612 case TOK.uns64:
3613 t = AST.Type.tuns64;
3614 goto LabelX;
3615
3616 case TOK.int128:
3617 t = AST.Type.tint128;
3618 goto LabelX;
3619
3620 case TOK.uns128:
3621 t = AST.Type.tuns128;
3622 goto LabelX;
3623
3624 case TOK.float32:
3625 t = AST.Type.tfloat32;
3626 goto LabelX;
3627
3628 case TOK.float64:
3629 t = AST.Type.tfloat64;
3630 goto LabelX;
3631
3632 case TOK.float80:
3633 t = AST.Type.tfloat80;
3634 goto LabelX;
3635
3636 case TOK.imaginary32:
3637 t = AST.Type.timaginary32;
3638 goto LabelX;
3639
3640 case TOK.imaginary64:
3641 t = AST.Type.timaginary64;
3642 goto LabelX;
3643
3644 case TOK.imaginary80:
3645 t = AST.Type.timaginary80;
3646 goto LabelX;
3647
3648 case TOK.complex32:
3649 t = AST.Type.tcomplex32;
3650 goto LabelX;
3651
3652 case TOK.complex64:
3653 t = AST.Type.tcomplex64;
3654 goto LabelX;
3655
3656 case TOK.complex80:
3657 t = AST.Type.tcomplex80;
3658 goto LabelX;
3659
3660 case TOK.bool_:
3661 t = AST.Type.tbool;
3662 goto LabelX;
3663
3664 case TOK.char_:
3665 t = AST.Type.tchar;
3666 goto LabelX;
3667
3668 case TOK.wchar_:
3669 t = AST.Type.twchar;
3670 goto LabelX;
3671
3672 case TOK.dchar_:
3673 t = AST.Type.tdchar;
3674 goto LabelX;
3675 LabelX:
3676 nextToken();
3677 break;
3678
3679 case TOK.this_:
3680 case TOK.super_:
3681 case TOK.identifier:
3682 loc = token.loc;
3683 id = token.ident;
3684 nextToken();
3685 if (token.value == TOK.not)
3686 {
3687 // ident!(template_arguments)
3688 auto tempinst = new AST.TemplateInstance(loc, id, parseTemplateArguments());
3689 t = parseBasicTypeStartingAt(new AST.TypeInstance(loc, tempinst), dontLookDotIdents);
3690 }
3691 else
3692 {
3693 t = parseBasicTypeStartingAt(new AST.TypeIdentifier(loc, id), dontLookDotIdents);
3694 }
3695 break;
3696
3697 case TOK.mixin_:
3698 // https://dlang.org/spec/expression.html#mixin_types
3699 loc = token.loc;
3700 nextToken();
3701 if (token.value != TOK.leftParenthesis)
3702 error(token.loc, "found `%s` when expecting `%s` following `mixin`", token.toChars(), Token.toChars(TOK.leftParenthesis));
3703 auto exps = parseArguments();
3704 t = new AST.TypeMixin(loc, exps);
3705 break;
3706
3707 case TOK.dot:
3708 // Leading . as in .foo
3709 t = parseBasicTypeStartingAt(new AST.TypeIdentifier(token.loc, Id.empty), dontLookDotIdents);
3710 break;
3711
3712 case TOK.typeof_:
3713 // typeof(expression)
3714 t = parseBasicTypeStartingAt(parseTypeof(), dontLookDotIdents);
3715 break;
3716
3717 case TOK.vector:
3718 t = parseVector();
3719 break;
3720
3721 case TOK.traits:
3722 if (AST.TraitsExp te = cast(AST.TraitsExp) parsePrimaryExp())
3723 if (te.ident)
3724 {
3725 t = new AST.TypeTraits(token.loc, te);
3726 break;
3727 }
3728 t = new AST.TypeError;
3729 break;
3730
3731 case TOK.const_:
3732 // const(type)
3733 nextToken();
3734 check(TOK.leftParenthesis);
3735 t = parseType().addSTC(STC.const_);
3736 check(TOK.rightParenthesis);
3737 break;
3738
3739 case TOK.immutable_:
3740 // immutable(type)
3741 nextToken();
3742 check(TOK.leftParenthesis);
3743 t = parseType().addSTC(STC.immutable_);
3744 check(TOK.rightParenthesis);
3745 break;
3746
3747 case TOK.shared_:
3748 // shared(type)
3749 nextToken();
3750 check(TOK.leftParenthesis);
3751 t = parseType().addSTC(STC.shared_);
3752 check(TOK.rightParenthesis);
3753 break;
3754
3755 case TOK.inout_:
3756 // wild(type)
3757 nextToken();
3758 check(TOK.leftParenthesis);
3759 t = parseType().addSTC(STC.wild);
3760 check(TOK.rightParenthesis);
3761 break;
3762
3763 default:
3764 error("basic type expected, not `%s`", token.toChars());
3765 if (token.value == TOK.else_)
3766 eSink.errorSupplemental(token.loc, "There's no `static else`, use `else` instead.");
3767 t = AST.Type.terror;
3768 break;
3769 }
3770 return t;
3771 }
3772
3773 private AST.Type parseBasicTypeStartingAt(AST.TypeQualified tid, bool dontLookDotIdents)
3774 {
3775 AST.Type maybeArray = null;
3776 // See https://issues.dlang.org/show_bug.cgi?id=1215
3777 // A basic type can look like MyType (typical case), but also:
3778 // MyType.T -> A type
3779 // MyType[expr] -> Either a static array of MyType or a type (iif MyType is a Ttuple)
3780 // MyType[expr].T -> A type.
3781 // MyType[expr].T[expr] -> Either a static array of MyType[expr].T or a type
3782 // (iif MyType[expr].T is a Ttuple)
3783 while (1)
3784 {
3785 switch (token.value)
3786 {
3787 case TOK.dot:
3788 {
3789 nextToken();
3790 if (token.value != TOK.identifier)
3791 {
3792 error("identifier expected following `.` instead of `%s`", token.toChars());
3793 break;
3794 }
3795 if (maybeArray)
3796 {
3797 // This is actually a TypeTuple index, not an {a/s}array.
3798 // We need to have a while loop to unwind all index taking:
3799 // T[e1][e2].U -> T, addIndex(e1), addIndex(e2)
3800 AST.Objects dimStack;
3801 AST.Type t = maybeArray;
3802 while (true)
3803 {
3804 if (t.ty == Tsarray)
3805 {
3806 // The index expression is an Expression.
3807 AST.TypeSArray a = cast(AST.TypeSArray)t;
3808 dimStack.push(a.dim.syntaxCopy());
3809 t = a.next.syntaxCopy();
3810 }
3811 else if (t.ty == Taarray)
3812 {
3813 // The index expression is a Type. It will be interpreted as an expression at semantic time.
3814 AST.TypeAArray a = cast(AST.TypeAArray)t;
3815 dimStack.push(a.index.syntaxCopy());
3816 t = a.next.syntaxCopy();
3817 }
3818 else
3819 {
3820 break;
3821 }
3822 }
3823 assert(dimStack.length > 0);
3824 // We're good. Replay indices in the reverse order.
3825 tid = cast(AST.TypeQualified)t;
3826 while (dimStack.length)
3827 {
3828 tid.addIndex(dimStack.pop());
3829 }
3830 maybeArray = null;
3831 }
3832 const loc = token.loc;
3833 Identifier id = token.ident;
3834 nextToken();
3835 if (token.value == TOK.not)
3836 {
3837 auto tempinst = new AST.TemplateInstance(loc, id, parseTemplateArguments());
3838 tid.addInst(tempinst);
3839 }
3840 else
3841 tid.addIdent(id);
3842 continue;
3843 }
3844 case TOK.leftBracket:
3845 {
3846 if (dontLookDotIdents) // workaround for https://issues.dlang.org/show_bug.cgi?id=14911
3847 goto Lend;
3848
3849 nextToken();
3850 AST.Type t = maybeArray ? maybeArray : cast(AST.Type)tid;
3851 if (token.value == TOK.rightBracket)
3852 {
3853 // It's a dynamic array, and we're done:
3854 // T[].U does not make sense.
3855 t = new AST.TypeDArray(t);
3856 nextToken();
3857 return t;
3858 }
3859 else if (isDeclaration(&token, NeedDeclaratorId.no, TOK.rightBracket, null))
3860 {
3861 // This can be one of two things:
3862 // 1 - an associative array declaration, T[type]
3863 // 2 - an associative array declaration, T[expr]
3864 // These can only be disambiguated later.
3865 AST.Type index = parseType(); // [ type ]
3866 maybeArray = new AST.TypeAArray(t, index);
3867 check(TOK.rightBracket);
3868 }
3869 else
3870 {
3871 // This can be one of three things:
3872 // 1 - an static array declaration, T[expr]
3873 // 2 - a slice, T[expr .. expr]
3874 // 3 - a template parameter pack index expression, T[expr].U
3875 // 1 and 3 can only be disambiguated later.
3876 //printf("it's type[expression]\n");
3877 inBrackets++;
3878 AST.Expression e = parseAssignExp(); // [ expression ]
3879 if (token.value == TOK.slice)
3880 {
3881 // It's a slice, and we're done.
3882 nextToken();
3883 AST.Expression e2 = parseAssignExp(); // [ exp .. exp ]
3884 t = new AST.TypeSlice(t, e, e2);
3885 inBrackets--;
3886 check(TOK.rightBracket);
3887 return t;
3888 }
3889 else
3890 {
3891 maybeArray = new AST.TypeSArray(t, e);
3892 inBrackets--;
3893 check(TOK.rightBracket);
3894 continue;
3895 }
3896 }
3897 break;
3898 }
3899 default:
3900 goto Lend;
3901 }
3902 }
3903 Lend:
3904 return maybeArray ? maybeArray : cast(AST.Type)tid;
3905 }
3906
3907 /******************************************
3908 * Parse suffixes to type t.
3909 * *
3910 * []
3911 * [AssignExpression]
3912 * [AssignExpression .. AssignExpression]
3913 * [Type]
3914 * delegate Parameters MemberFunctionAttributes(opt)
3915 * function Parameters FunctionAttributes(opt)
3916 * Params:
3917 * t = the already parsed type
3918 * Returns:
3919 * t with the suffixes added
3920 * See_Also:
3921 * https://dlang.org/spec/declaration.html#TypeSuffixes
3922 */
3923 private AST.Type parseTypeSuffixes(AST.Type t)
3924 {
3925 //printf("parseTypeSuffixes()\n");
3926 while (1)
3927 {
3928 switch (token.value)
3929 {
3930 case TOK.mul:
3931 t = new AST.TypePointer(t);
3932 nextToken();
3933 continue;
3934
3935 case TOK.leftBracket:
3936 // Handle []. Make sure things like
3937 // int[3][1] a;
3938 // is (array[1] of array[3] of int)
3939 nextToken();
3940 if (token.value == TOK.rightBracket)
3941 {
3942 t = new AST.TypeDArray(t); // []
3943 nextToken();
3944 }
3945 else if (isDeclaration(&token, NeedDeclaratorId.no, TOK.rightBracket, null))
3946 {
3947 // It's an associative array declaration
3948 //printf("it's an associative array\n");
3949 AST.Type index = parseType(); // [ type ]
3950 t = new AST.TypeAArray(t, index);
3951 check(TOK.rightBracket);
3952 }
3953 else
3954 {
3955 //printf("it's type[expression]\n");
3956 inBrackets++;
3957 AST.Expression e = parseAssignExp(); // [ expression ]
3958 if (!e)
3959 {
3960 inBrackets--;
3961 check(TOK.rightBracket);
3962 continue;
3963 }
3964 if (token.value == TOK.slice)
3965 {
3966 nextToken();
3967 AST.Expression e2 = parseAssignExp(); // [ exp .. exp ]
3968 t = new AST.TypeSlice(t, e, e2);
3969 }
3970 else
3971 {
3972 t = new AST.TypeSArray(t, e);
3973 }
3974 inBrackets--;
3975 check(TOK.rightBracket);
3976 }
3977 continue;
3978
3979 case TOK.delegate_:
3980 case TOK.function_:
3981 {
3982 // Handle delegate declaration:
3983 // t delegate(parameter list) nothrow pure
3984 // t function(parameter list) nothrow pure
3985 const save = token.value;
3986 nextToken();
3987
3988 auto parameterList = parseParameterList(null);
3989
3990 STC stc = parsePostfix(STC.none, null);
3991 auto tf = new AST.TypeFunction(parameterList, t, linkage, stc);
3992 if (stc & (STC.const_ | STC.immutable_ | STC.shared_ | STC.wild | STC.return_))
3993 {
3994 if (save == TOK.function_)
3995 error("`const`/`immutable`/`shared`/`inout`/`return` attributes are only valid for non-static member functions");
3996 else
3997 tf = cast(AST.TypeFunction)tf.addSTC(stc);
3998 }
3999 t = save == TOK.delegate_ ? new AST.TypeDelegate(tf) : new AST.TypePointer(tf); // pointer to function
4000 continue;
4001 }
4002 default:
4003 return t;
4004 }
4005 assert(0);
4006 }
4007 assert(0);
4008 }
4009
4010 /**********************
4011 * Parse Declarator
4012 * Params:
4013 * t = base type to start with
4014 * palt = OR in 1 for C-style function pointer declaration syntax,
4015 * 2 for C-style array declaration syntax, otherwise don't modify
4016 * pident = set to Identifier if there is one, null if not
4017 * tpl = if !null, then set to TemplateParameterList
4018 * storageClass = any storage classes seen so far
4019 * pdisable = set to true if @disable seen
4020 * pudas = any user defined attributes seen so far. Merged with any more found
4021 * Returns:
4022 * type declared
4023 * Reference: https://dlang.org/spec/declaration.html#Declarator
4024 */
4025 private AST.Type parseDeclarator(AST.Type t, ref int palt, Identifier* pident,
4026 AST.TemplateParameters** tpl = null, STC storageClass = STC.none,
4027 bool* pdisable = null, AST.Expressions** pudas = null)
4028 {
4029 //printf("parseDeclarator(tpl = %p)\n", tpl);
4030 t = parseTypeSuffixes(t);
4031 AST.Type ts;
4032 switch (token.value)
4033 {
4034 case TOK.identifier:
4035 if (pident)
4036 *pident = token.ident;
4037 else
4038 error("unexpected identifier `%s` in declarator", token.ident.toChars());
4039 ts = t;
4040 nextToken();
4041 break;
4042
4043 case TOK.leftParenthesis:
4044 {
4045 // like: T (*fp)();
4046 // like: T ((*fp))();
4047 if (peekNext() == TOK.mul || peekNext() == TOK.leftParenthesis)
4048 {
4049 /* Parse things with parentheses around the identifier, like:
4050 * int (*ident[3])[]
4051 * although the D style would be:
4052 * int[]*[3] ident
4053 */
4054 palt |= 1;
4055 nextToken();
4056 ts = parseDeclarator(t, palt, pident);
4057 check(TOK.rightParenthesis);
4058 break;
4059 }
4060 ts = t;
4061
4062 Token* peekt = &token;
4063 /* Completely disallow C-style things like:
4064 * T (a);
4065 * Improve error messages for the common bug of a missing return type
4066 * by looking to see if (a) looks like a parameter list.
4067 */
4068 if (isParameters(&peekt))
4069 {
4070 error("function declaration without return type. (Note that constructors are always named `this`)");
4071 }
4072 else
4073 error("unexpected `(` in declarator");
4074 break;
4075 }
4076 default:
4077 ts = t;
4078 break;
4079 }
4080
4081 // parse DeclaratorSuffixes
4082 while (1)
4083 {
4084 switch (token.value)
4085 {
4086 static if (CARRAYDECL)
4087 {
4088 /* Support C style array syntax:
4089 * int ident[]
4090 * as opposed to D-style:
4091 * int[] ident
4092 */
4093 case TOK.leftBracket:
4094 {
4095 // This is the old C-style post [] syntax.
4096 AST.TypeNext ta;
4097 nextToken();
4098 if (token.value == TOK.rightBracket)
4099 {
4100 // It's a dynamic array
4101 ta = new AST.TypeDArray(t); // []
4102 nextToken();
4103 palt |= 2;
4104 }
4105 else if (isDeclaration(&token, NeedDeclaratorId.no, TOK.rightBracket, null))
4106 {
4107 // It's an associative array
4108 //printf("it's an associative array\n");
4109 AST.Type index = parseType(); // [ type ]
4110 check(TOK.rightBracket);
4111 ta = new AST.TypeAArray(t, index);
4112 palt |= 2;
4113 }
4114 else
4115 {
4116 //printf("It's a static array\n");
4117 AST.Expression e = parseAssignExp(); // [ expression ]
4118 ta = new AST.TypeSArray(t, e);
4119 check(TOK.rightBracket);
4120 palt |= 2;
4121 }
4122
4123 /* Insert ta into
4124 * ts -> ... -> t
4125 * so that
4126 * ts -> ... -> ta -> t
4127 */
4128 AST.Type* pt;
4129 for (pt = &ts; *pt != t; pt = &(cast(AST.TypeNext)*pt).next)
4130 {
4131 }
4132 *pt = ta;
4133 continue;
4134 }
4135 }
4136 case TOK.leftParenthesis:
4137 {
4138 if (tpl)
4139 {
4140 Token* tk = peekPastParen(&token);
4141 if (tk.value == TOK.leftParenthesis)
4142 {
4143 /* Look ahead to see if this is (...)(...),
4144 * i.e. a function template declaration
4145 */
4146 //printf("function template declaration\n");
4147
4148 // Gather template parameter list
4149 *tpl = parseTemplateParameterList();
4150 }
4151 else if (tk.value == TOK.assign)
4152 {
4153 /* or (...) =,
4154 * i.e. a variable template declaration
4155 */
4156 //printf("variable template declaration\n");
4157 *tpl = parseTemplateParameterList();
4158 break;
4159 }
4160 }
4161
4162 auto parameterList = parseParameterList(null);
4163
4164 /* Parse const/immutable/shared/inout/nothrow/pure/return postfix
4165 */
4166 // merge prefix storage classes
4167 STC stc = parsePostfix(storageClass, pudas);
4168
4169 AST.Type tf = new AST.TypeFunction(parameterList, t, linkage, stc);
4170 tf = tf.addSTC(stc);
4171 if (pdisable)
4172 *pdisable = stc & STC.disable ? true : false;
4173
4174 /* Insert tf into
4175 * ts -> ... -> t
4176 * so that
4177 * ts -> ... -> tf -> t
4178 */
4179 AST.Type* pt;
4180 for (pt = &ts; *pt != t; pt = &(cast(AST.TypeNext)*pt).next)
4181 {
4182 }
4183 *pt = tf;
4184 break;
4185 }
4186 default:
4187 break;
4188 }
4189 break;
4190 }
4191 return ts;
4192 }
4193
4194 private void parseStorageClasses(ref STC storage_class, ref LINK link,
4195 ref bool setAlignment, ref AST.Expression ealign, ref AST.Expressions* udas,
4196 out Loc linkloc)
4197 {
4198 STC stc;
4199 bool sawLinkage = false; // seen a linkage declaration
4200
4201 linkloc = Loc.initial;
4202
4203 while (1)
4204 {
4205 switch (token.value)
4206 {
4207 case TOK.const_:
4208 if (peekNext() == TOK.leftParenthesis)
4209 break; // const as type constructor
4210 stc = STC.const_; // const as storage class
4211 goto L1;
4212
4213 case TOK.immutable_:
4214 if (peekNext() == TOK.leftParenthesis)
4215 break;
4216 stc = STC.immutable_;
4217 goto L1;
4218
4219 case TOK.shared_:
4220 if (peekNext() == TOK.leftParenthesis)
4221 break;
4222 stc = STC.shared_;
4223 goto L1;
4224
4225 case TOK.inout_:
4226 if (peekNext() == TOK.leftParenthesis)
4227 break;
4228 stc = STC.wild;
4229 goto L1;
4230
4231 case TOK.static_:
4232 stc = STC.static_;
4233 goto L1;
4234
4235 case TOK.final_:
4236 stc = STC.final_;
4237 goto L1;
4238
4239 case TOK.auto_:
4240 stc = STC.auto_;
4241 if (peekNext() == TOK.ref_)
4242 stc |= STC.autoref;
4243 goto L1;
4244
4245 case TOK.scope_:
4246 stc = STC.scope_;
4247 goto L1;
4248
4249 case TOK.override_:
4250 stc = STC.override_;
4251 goto L1;
4252
4253 case TOK.abstract_:
4254 stc = STC.abstract_;
4255 goto L1;
4256
4257 case TOK.synchronized_:
4258 stc = STC.synchronized_;
4259 goto L1;
4260
4261 case TOK.deprecated_:
4262 stc = STC.deprecated_;
4263 goto L1;
4264
4265 case TOK.nothrow_:
4266 stc = STC.nothrow_;
4267 goto L1;
4268
4269 case TOK.pure_:
4270 stc = STC.pure_;
4271 goto L1;
4272
4273 case TOK.ref_:
4274 stc = STC.ref_;
4275 goto L1;
4276
4277 case TOK.gshared:
4278 stc = STC.gshared;
4279 goto L1;
4280
4281 case TOK.enum_:
4282 {
4283 const tv = peekNext();
4284 if (tv == TOK.leftCurly || tv == TOK.colon)
4285 break;
4286 if (tv == TOK.identifier)
4287 {
4288 const nextv = peekNext2();
4289 if (nextv == TOK.leftCurly || nextv == TOK.colon || nextv == TOK.semicolon)
4290 break;
4291 }
4292 stc = STC.manifest;
4293 goto L1;
4294 }
4295
4296 case TOK.at:
4297 {
4298 stc = parseAttribute(udas);
4299 if (stc)
4300 goto L1;
4301 continue;
4302 }
4303 L1:
4304 storage_class = appendStorageClass(storage_class, stc);
4305 nextToken();
4306 continue;
4307
4308 case TOK.extern_:
4309 {
4310 if (peekNext() != TOK.leftParenthesis)
4311 {
4312 stc = STC.extern_;
4313 goto L1;
4314 }
4315
4316 if (sawLinkage)
4317 error("redundant linkage declaration");
4318 sawLinkage = true;
4319 linkloc = token.loc;
4320 auto res = parseLinkage();
4321 link = res.link;
4322 if (res.idents || res.identExps)
4323 {
4324 error("C++ name spaces not allowed here");
4325 }
4326 if (res.cppmangle != CPPMANGLE.def)
4327 {
4328 error("C++ mangle declaration not allowed here");
4329 }
4330 continue;
4331 }
4332 case TOK.align_:
4333 {
4334 setAlignment = true;
4335 ealign = parseAlign();
4336 continue;
4337 }
4338 default:
4339 break;
4340 }
4341 break;
4342 }
4343 }
4344
4345 /**
4346 * Parse `align` or `align(n)`
4347 * Returns:
4348 * expression `n` if it is present, or `null` otherwise.
4349 */
4350 private AST.Expression parseAlign()
4351 {
4352 assert(token.value == TOK.align_);
4353 AST.Expression e = null;
4354 nextToken();
4355 if (token.value == TOK.leftParenthesis)
4356 {
4357 nextToken();
4358 if (token.value == TOK.default_)
4359 nextToken();
4360 else
4361 e = parseAssignExp();
4362 check(TOK.rightParenthesis);
4363 }
4364 return e;
4365 }
4366 /**********************************
4367 * Parse Declarations.
4368 * These can be:
4369 * 1. declarations at global/class level
4370 * 2. declarations at statement level
4371 * Returns:
4372 * array of Declarations.
4373 */
4374 private AST.Dsymbols* parseDeclarations(bool autodecl, PrefixAttributes!AST* pAttrs, const(char)* comment)
4375 {
4376 STC storage_class = STC.none;
4377 LINK link = linkage;
4378 Loc linkloc = this.linkLoc;
4379 bool setAlignment = false;
4380 AST.Expression ealign;
4381 AST.Expressions* udas = null;
4382
4383 //printf("parseDeclarations() %s\n", token.toChars());
4384 if (!comment)
4385 comment = token.blockComment.ptr;
4386
4387 /* Look for AliasReassignment
4388 */
4389 if (token.value == TOK.identifier && peekNext() == TOK.assign)
4390 return parseAliasReassignment(comment);
4391
4392 /* Declarations that start with `alias`
4393 */
4394 bool isAliasDeclaration = false;
4395 auto aliasLoc = token.loc;
4396 if (token.value == TOK.alias_)
4397 {
4398 if (auto a = parseAliasDeclarations(comment))
4399 return a;
4400 /* Handle these later:
4401 * alias StorageClasses type ident;
4402 */
4403 isAliasDeclaration = true;
4404 }
4405
4406 AST.Type ts;
4407
4408 if (!autodecl)
4409 {
4410 parseStorageClasses(storage_class, link, setAlignment, ealign, udas, linkloc);
4411
4412 if (token.value == TOK.enum_)
4413 {
4414 AST.Dsymbol d = parseEnum();
4415 auto a = new AST.Dsymbols();
4416 a.push(d);
4417
4418 if (udas)
4419 {
4420 d = new AST.UserAttributeDeclaration(udas, a);
4421 a = new AST.Dsymbols();
4422 a.push(d);
4423 }
4424
4425 addComment(d, comment);
4426 return a;
4427 }
4428 if (token.value == TOK.struct_ ||
4429 token.value == TOK.union_ ||
4430 token.value == TOK.class_ ||
4431 token.value == TOK.interface_)
4432 {
4433 AST.Dsymbol s = parseAggregate();
4434 auto a = new AST.Dsymbols();
4435 a.push(s);
4436
4437 if (storage_class)
4438 {
4439 s = new AST.StorageClassDeclaration(storage_class, a);
4440 a = new AST.Dsymbols();
4441 a.push(s);
4442 }
4443 if (setAlignment)
4444 {
4445 s = new AST.AlignDeclaration(s.loc, ealign, a);
4446 a = new AST.Dsymbols();
4447 a.push(s);
4448 }
4449 if (link != linkage)
4450 {
4451 s = new AST.LinkDeclaration(linkloc, link, a);
4452 a = new AST.Dsymbols();
4453 a.push(s);
4454 }
4455 if (udas)
4456 {
4457 s = new AST.UserAttributeDeclaration(udas, a);
4458 a = new AST.Dsymbols();
4459 a.push(s);
4460 }
4461
4462 addComment(s, comment);
4463 return a;
4464 }
4465
4466 /* Look for auto initializers:
4467 * storage_class identifier = initializer;
4468 * storage_class identifier(...) = initializer;
4469 */
4470 if ((storage_class || udas) && token.value == TOK.identifier && hasOptionalParensThen(peek(&token), TOK.assign))
4471 {
4472 AST.Dsymbols* a = parseAutoDeclarations(storage_class, comment);
4473 if (udas)
4474 {
4475 AST.Dsymbol s = new AST.UserAttributeDeclaration(udas, a);
4476 a = new AST.Dsymbols();
4477 a.push(s);
4478 }
4479 return a;
4480 }
4481
4482 /* Look for return type inference for template functions.
4483 */
4484 {
4485 Token* tk;
4486 if ((storage_class || udas) && token.value == TOK.identifier && skipParens(peek(&token), &tk) &&
4487 skipAttributes(tk, &tk) &&
4488 (tk.value == TOK.leftParenthesis || tk.value == TOK.leftCurly || tk.value == TOK.in_ || tk.value == TOK.out_ || tk.value == TOK.goesTo ||
4489 tk.value == TOK.do_ || tk.value == TOK.identifier && tk.ident == Id._body))
4490 {
4491 if (tk.value == TOK.identifier && tk.ident == Id._body)
4492 usageOfBodyKeyword();
4493
4494 ts = null;
4495 }
4496 else
4497 {
4498 ts = parseBasicType();
4499 ts = parseTypeSuffixes(ts);
4500 }
4501 }
4502 }
4503
4504 if (pAttrs)
4505 {
4506 storage_class |= pAttrs.storageClass;
4507 //pAttrs.storageClass = STC.none;
4508 }
4509
4510 AST.Type tfirst = null;
4511 auto a = new AST.Dsymbols();
4512
4513 while (1)
4514 {
4515 AST.TemplateParameters* tpl = null;
4516 bool disable;
4517 int alt = 0;
4518
4519 const loc = token.loc;
4520 Identifier ident;
4521 auto t = parseDeclarator(ts, alt, &ident, &tpl, storage_class, &disable, &udas);
4522 assert(t);
4523 if (!tfirst)
4524 tfirst = t;
4525 else if (t != tfirst)
4526 error(token.loc, "multiple declarations must have the same type, not `%s` and `%s`", tfirst.toChars(), t.toChars());
4527
4528 if (token.value == TOK.colon && !ident && t.ty != Tfunction)
4529 {
4530 // Unnamed bit field
4531 ident = Identifier.generateAnonymousId("BitField");
4532 }
4533
4534 bool isThis = (t.ty == Tident && (cast(AST.TypeIdentifier)t).ident == Id.This && token.value == TOK.assign);
4535 if (ident)
4536 checkCstyleTypeSyntax(loc, t, alt, ident);
4537 else if (!isThis && (t != AST.Type.terror))
4538 noIdentifierForDeclarator(t, token);
4539
4540 if (isAliasDeclaration)
4541 {
4542 AST.Declaration v;
4543 AST.Initializer _init = null;
4544
4545 /* Aliases can no longer have multiple declarators, storage classes,
4546 * linkages, or auto declarations.
4547 * These never made any sense, anyway.
4548 * The code below needs to be fixed to reject them.
4549 * The grammar has already been fixed to preclude them.
4550 */
4551
4552 if (udas)
4553 error("user-defined attributes not allowed for `alias` declarations");
4554
4555 if (token.value == TOK.assign)
4556 {
4557 nextToken();
4558 _init = parseInitializer();
4559 }
4560 if (_init)
4561 {
4562 error("alias cannot have initializer");
4563 }
4564 v = new AST.AliasDeclaration(aliasLoc, ident, t);
4565
4566 v.storage_class = storage_class;
4567 if (pAttrs)
4568 {
4569 /* AliasDeclaration distinguish @safe, @system, @trusted attributes
4570 * on prefix and postfix.
4571 * @safe alias void function() FP1;
4572 * alias @safe void function() FP2; // FP2 is not @safe
4573 * alias void function() @safe FP3;
4574 */
4575 pAttrs.storageClass &= STC.safeGroup;
4576 }
4577 AST.Dsymbol s = v;
4578
4579 if (link != linkage)
4580 {
4581 auto ax = new AST.Dsymbols();
4582 ax.push(v);
4583 s = new AST.LinkDeclaration(linkloc, link, ax);
4584 }
4585 a.push(s);
4586 switch (token.value)
4587 {
4588 case TOK.semicolon:
4589 nextToken();
4590 addComment(s, comment);
4591 break;
4592
4593 case TOK.comma:
4594 nextToken();
4595 addComment(s, comment);
4596 continue;
4597
4598 default:
4599 error("semicolon expected to close `alias` declaration, not `%s`", token.toChars());
4600 nextToken();
4601 break;
4602 }
4603 }
4604 else if (t.ty == Tfunction)
4605 {
4606 /* @@@DEPRECATED_2.115@@@
4607 * change to error, deprecated in 2.105.1 */
4608 if (storage_class & STC.manifest)
4609 deprecation("function cannot have enum storage class");
4610
4611 AST.Expression constraint = null;
4612 //printf("%s funcdecl t = %s, storage_class = x%lx\n", loc.toChars(), t.toChars(), storage_class);
4613 auto f = new AST.FuncDeclaration(loc, Loc.initial, ident, storage_class | (disable ? STC.disable : STC.none), t);
4614 if (pAttrs)
4615 pAttrs.storageClass = STC.none;
4616 if (tpl)
4617 constraint = parseConstraint();
4618 AST.Dsymbol s = parseContracts(f, !!tpl);
4619 auto tplIdent = s.ident;
4620
4621 if (link != linkage)
4622 {
4623 auto ax = new AST.Dsymbols();
4624 ax.push(s);
4625 s = new AST.LinkDeclaration(linkloc, link, ax);
4626 }
4627 if (udas)
4628 {
4629 auto ax = new AST.Dsymbols();
4630 ax.push(s);
4631 s = new AST.UserAttributeDeclaration(udas, ax);
4632 }
4633
4634 /* A template parameter list means it's a function template
4635 */
4636 if (tpl)
4637 {
4638 // @@@DEPRECATED_2.114@@@
4639 // Both deprecated in 2.104, change to error
4640 if (storage_class & STC.override_)
4641 deprecation(loc, "a function template is not virtual so cannot be marked `override`");
4642 else if (storage_class & STC.abstract_)
4643 deprecation(loc, "a function template is not virtual so cannot be marked `abstract`");
4644
4645 // Wrap a template around the function declaration
4646 auto decldefs = new AST.Dsymbols();
4647 decldefs.push(s);
4648 auto tempdecl = new AST.TemplateDeclaration(loc, tplIdent, tpl, constraint, decldefs);
4649 s = tempdecl;
4650
4651 STC stc2 = STC.none;
4652 if (storage_class & STC.static_)
4653 {
4654 assert(f.storage_class & STC.static_);
4655 f.storage_class &= ~STC.static_;
4656 stc2 |= STC.static_;
4657 }
4658 if (storage_class & STC.deprecated_)
4659 {
4660 assert(f.storage_class & STC.deprecated_);
4661 f.storage_class &= ~STC.deprecated_;
4662 stc2 |= STC.deprecated_;
4663 }
4664 if (stc2 != STC.none)
4665 {
4666 auto ax = new AST.Dsymbols();
4667 ax.push(s);
4668 s = new AST.StorageClassDeclaration(stc2, ax);
4669 }
4670 }
4671 a.push(s);
4672 addComment(s, comment);
4673 }
4674 else if (ident)
4675 {
4676 AST.Expression width;
4677 if (token.value == TOK.colon)
4678 {
4679 nextToken();
4680 width = parseCondExp();
4681 }
4682
4683 AST.Initializer _init = null;
4684 if (token.value == TOK.assign)
4685 {
4686 nextToken();
4687 _init = parseInitializer();
4688 }
4689
4690 AST.Dsymbol s;
4691 if (width)
4692 {
4693 if (_init)
4694 error("initializer not allowed for bit-field declaration");
4695 if (storage_class)
4696 error("storage class not allowed for bit-field declaration");
4697 s = new AST.BitFieldDeclaration(width.loc, t, ident, width);
4698 }
4699 else
4700 {
4701 auto v = new AST.VarDeclaration(loc, t, ident, _init);
4702 v.storage_class = storage_class;
4703 if (pAttrs)
4704 pAttrs.storageClass = STC.none;
4705 s = v;
4706 }
4707
4708 if (tpl && _init)
4709 {
4710 auto a2 = new AST.Dsymbols();
4711 a2.push(s);
4712 auto tempdecl = new AST.TemplateDeclaration(loc, ident, tpl, null, a2, 0);
4713 s = tempdecl;
4714 }
4715 if (setAlignment)
4716 {
4717 auto ax = new AST.Dsymbols();
4718 ax.push(s);
4719 s = new AST.AlignDeclaration(s.loc, ealign, ax);
4720 }
4721 if (link != linkage)
4722 {
4723 auto ax = new AST.Dsymbols();
4724 ax.push(s);
4725 s = new AST.LinkDeclaration(linkloc, link, ax);
4726 }
4727 if (udas)
4728 {
4729 auto ax = new AST.Dsymbols();
4730 ax.push(s);
4731 s = new AST.UserAttributeDeclaration(udas, ax);
4732 }
4733 a.push(s);
4734 switch (token.value)
4735 {
4736 case TOK.semicolon:
4737 nextToken();
4738 addComment(s, comment);
4739 break;
4740
4741 case TOK.comma:
4742 nextToken();
4743 addComment(s, comment);
4744 continue;
4745
4746 default:
4747 if (loc.linnum != token.loc.linnum)
4748 {
4749 error(token.loc, "semicolon needed to end declaration of `%s`, instead of `%s`", s.toChars(), token.toChars());
4750 eSink.errorSupplemental(loc, "`%s` declared here", s.toChars());
4751 }
4752 else
4753 {
4754 error(token.loc, "semicolon needed to end declaration of `%s` instead of `%s`", s.toChars(), token.toChars());
4755 }
4756 break;
4757 }
4758 }
4759 break;
4760 }
4761 return a;
4762 }
4763
4764 /// Report an error that a declaration of type `t` is missing an identifier and got `tok` instead
4765 /// The parser is expected to sit on the next token after the type.
4766 private void noIdentifierForDeclarator(AST.Type t, Token tok)
4767 {
4768 error("variable name expected after type `%s`, not `%s`", t.toChars(), tok.toChars);
4769
4770 // A common mistake is to use a reserved keyword as an identifier, e.g. `in` or `out`
4771 if (token.isKeyword)
4772 {
4773 eSink.errorSupplemental(token.loc, "`%s` is a keyword, perhaps append `_` to make it an identifier", token.toChars());
4774 nextToken();
4775 }
4776 }
4777
4778 /********************************
4779 * Parse AliasReassignment:
4780 * identifier = type;
4781 * Parser is sitting on the identifier.
4782 * https://dlang.org/spec/declaration.html#alias-reassignment
4783 * Params:
4784 * comment = if not null, comment to attach to symbol
4785 * Returns:
4786 * array of symbols
4787 */
4788 private AST.Dsymbols* parseAliasReassignment(const(char)* comment)
4789 {
4790 const loc = token.loc;
4791 auto ident = token.ident;
4792 nextToken();
4793 nextToken(); // advance past =
4794 auto t = parseType();
4795 AST.Dsymbol s = new AST.AliasAssign(loc, ident, t, null);
4796 check(TOK.semicolon, "alias reassignment");
4797 addComment(s, comment);
4798 auto a = new AST.Dsymbols();
4799 a.push(s);
4800 return a;
4801 }
4802
4803 /********************************
4804 * Parse declarations that start with `alias`
4805 * Parser is sitting on the `alias`.
4806 * https://dlang.org/spec/declaration.html#alias
4807 * Params:
4808 * comment = if not null, comment to attach to symbol
4809 * Returns:
4810 * array of symbols
4811 */
4812 private AST.Dsymbols* parseAliasDeclarations(const(char)* comment)
4813 {
4814 const loc = token.loc;
4815 nextToken();
4816 Loc linkloc = this.linkLoc;
4817 AST.Expressions* udas;
4818 LINK link = linkage;
4819 STC storage_class = STC.none;
4820 AST.Expression ealign;
4821 bool setAlignment = false;
4822
4823 /* Look for:
4824 * alias Identifier this;
4825 * https://dlang.org/spec/class.html#alias-this
4826 */
4827 if (token.value == TOK.identifier && peekNext() == TOK.this_)
4828 {
4829 auto s = new AST.AliasThis(loc, token.ident);
4830 nextToken();
4831 check(TOK.this_);
4832 check(TOK.semicolon, "`alias Identifier this`");
4833 auto a = new AST.Dsymbols();
4834 a.push(s);
4835 addComment(s, comment);
4836 return a;
4837 }
4838 /* Look for:
4839 * alias this = identifier;
4840 */
4841 if (token.value == TOK.this_ && peekNext() == TOK.assign && peekNext2() == TOK.identifier)
4842 {
4843 check(TOK.this_);
4844 check(TOK.assign);
4845 auto s = new AST.AliasThis(loc, token.ident);
4846 nextToken();
4847 check(TOK.semicolon, "`alias this = Identifier`");
4848 auto a = new AST.Dsymbols();
4849 a.push(s);
4850 addComment(s, comment);
4851 return a;
4852 }
4853 /* Look for:
4854 * alias identifier = type;
4855 * alias identifier(...) = type;
4856 * https://dlang.org/spec/declaration.html#alias
4857 */
4858 if (token.value == TOK.identifier && hasOptionalParensThen(peek(&token), TOK.assign))
4859 {
4860 auto a = new AST.Dsymbols();
4861 while (1)
4862 {
4863 auto ident = token.ident;
4864 nextToken();
4865 AST.TemplateParameters* tpl = null;
4866 if (token.value == TOK.leftParenthesis)
4867 tpl = parseTemplateParameterList();
4868 check(TOK.assign);
4869
4870 bool hasParsedAttributes;
4871 void parseAttributes()
4872 {
4873 if (hasParsedAttributes) // only parse once
4874 return;
4875 hasParsedAttributes = true;
4876 udas = null;
4877 storage_class = STC.none;
4878 link = linkage;
4879 linkloc = this.linkLoc;
4880 setAlignment = false;
4881 ealign = null;
4882 parseStorageClasses(storage_class, link, setAlignment, ealign, udas, linkloc);
4883 }
4884
4885 if (token.value == TOK.at)
4886 parseAttributes;
4887
4888 AST.Declaration v;
4889 AST.Dsymbol s;
4890
4891 bool attributesAppended;
4892 const STC funcStc = parseTypeCtor();
4893 Token* tk;
4894 // function literal?
4895 if (token.value == TOK.function_ ||
4896 token.value == TOK.delegate_ ||
4897 token.value == TOK.leftParenthesis &&
4898 skipAttributes(peekPastParen(&token), &tk) &&
4899 (tk.value == TOK.goesTo || tk.value == TOK.leftCurly) ||
4900 token.value == TOK.leftCurly ||
4901 token.value == TOK.identifier && peekNext() == TOK.goesTo ||
4902 token.value == TOK.ref_ && peekNext() == TOK.leftParenthesis &&
4903 skipAttributes(peekPastParen(peek(&token)), &tk) &&
4904 (tk.value == TOK.goesTo || tk.value == TOK.leftCurly) ||
4905 token.value == TOK.auto_ &&
4906 (peekNext() == TOK.leftParenthesis || // for better error
4907 peekNext() == TOK.ref_ &&
4908 peekNext2() == TOK.leftParenthesis)
4909 )
4910 {
4911 // function (parameters) { statements... }
4912 // delegate (parameters) { statements... }
4913 // (parameters) { statements... }
4914 // (parameters) => expression
4915 // { statements... }
4916 // identifier => expression
4917 // ref (parameters) { statements... }
4918 // ref (parameters) => expression
4919 // auto ref (parameters) { statements... }
4920 // auto ref (parameters) => expression
4921
4922 s = parseFunctionLiteral();
4923
4924 if (udas !is null)
4925 {
4926 if (storage_class != 0)
4927 error("cannot put a storage-class in an `alias` declaration.");
4928 // parseAttributes shouldn't have set these variables
4929 assert(link == linkage && !setAlignment && ealign is null);
4930 auto tpl_ = cast(AST.TemplateDeclaration) s;
4931 if (tpl_ is null || tpl_.members.length != 1)
4932 {
4933 error("user-defined attributes are not allowed on `alias` declarations");
4934 }
4935 else
4936 {
4937 auto fd = cast(AST.FuncLiteralDeclaration) (*tpl_.members)[0];
4938 auto tf = cast(AST.TypeFunction) fd.type;
4939 assert(tf.parameterList.parameters.length > 0);
4940 auto as = new AST.Dsymbols();
4941 (*tf.parameterList.parameters)[0].userAttribDecl = new AST.UserAttributeDeclaration(udas, as);
4942 }
4943 }
4944
4945 v = new AST.AliasDeclaration(loc, ident, s);
4946 }
4947 else
4948 {
4949 // type
4950 parseAttributes();
4951 if (udas)
4952 error("user-defined attributes not allowed for `alias` declarations");
4953
4954 auto t = parseBasicType();
4955 t = parseTypeSuffixes(t);
4956 if (token.value == TOK.identifier)
4957 {
4958 error("unexpected identifier `%s` after `%s`",
4959 token.ident.toChars(), t.toChars());
4960 nextToken();
4961 }
4962 else if (token.value == TOK.leftParenthesis)
4963 {
4964 // function type:
4965 // StorageClasses Type ( Parameters ) MemberFunctionAttributes
4966 auto parameterList = parseParameterList(null);
4967 udas = null;
4968 parseStorageClasses(storage_class, link, setAlignment, ealign, udas, linkloc);
4969 if (udas)
4970 error("user-defined attributes not allowed for `alias` declarations");
4971
4972 attributesAppended = true;
4973 // Note: method types can have a TypeCtor attribute
4974 storage_class = appendStorageClass(storage_class, funcStc);
4975 t = new AST.TypeFunction(parameterList, t, link, storage_class);
4976 }
4977
4978 // Disallow meaningless storage classes on type aliases
4979 if (storage_class)
4980 {
4981 // Don't raise errors for STC that are part of a function/delegate type, e.g.
4982 // `alias F = ref pure nothrow @nogc @safe int function();`
4983 const remStc = t.isTypeFunction ?
4984 storage_class & ~(STC.FUNCATTR | STC.TYPECTOR) : {
4985 auto tp = t.isTypePointer;
4986 const isFuncType = (tp && tp.next.isTypeFunction) || t.isTypeDelegate;
4987 return isFuncType ? (storage_class & ~STC.FUNCATTR) : storage_class;
4988 }();
4989
4990 if (remStc)
4991 {
4992 OutBuffer buf;
4993 AST.stcToBuffer(buf, remStc);
4994 // @@@DEPRECATED_2.103@@@
4995 // Deprecated in 2020-07, can be made an error in 2.103
4996 eSink.deprecation(token.loc, "storage class `%s` has no effect in type aliases", buf.peekChars());
4997 }
4998 }
4999
5000 v = new AST.AliasDeclaration(loc, ident, t);
5001 }
5002 if (!attributesAppended)
5003 storage_class = appendStorageClass(storage_class, funcStc);
5004 v.storage_class = storage_class;
5005
5006 s = v;
5007 if (tpl)
5008 {
5009 auto a2 = new AST.Dsymbols();
5010 a2.push(s);
5011 auto tempdecl = new AST.TemplateDeclaration(loc, ident, tpl, null, a2);
5012 s = tempdecl;
5013 }
5014 if (link != linkage)
5015 {
5016 auto a2 = new AST.Dsymbols();
5017 a2.push(s);
5018 s = new AST.LinkDeclaration(linkloc, link, a2);
5019 }
5020 a.push(s);
5021
5022 switch (token.value)
5023 {
5024 case TOK.semicolon:
5025 nextToken();
5026 addComment(s, comment);
5027 break;
5028
5029 case TOK.comma:
5030 nextToken();
5031 addComment(s, comment);
5032 if (token.value != TOK.identifier)
5033 {
5034 error("identifier expected following comma, not `%s`", token.toChars());
5035 break;
5036 }
5037 if (peekNext() != TOK.assign && peekNext() != TOK.leftParenthesis)
5038 {
5039 error("`=` expected following identifier");
5040 nextToken();
5041 break;
5042 }
5043 continue;
5044
5045 default:
5046 error("semicolon expected to close `alias` declaration, not `%s`", token.toChars());
5047 nextToken();
5048 break;
5049 }
5050 break;
5051 }
5052 return a;
5053 }
5054
5055 // alias StorageClasses type ident;
5056 return null;
5057 }
5058
5059 private AST.Dsymbol parseFunctionLiteral()
5060 {
5061 const loc = token.loc;
5062 AST.TemplateParameters* tpl = null;
5063 AST.ParameterList parameterList;
5064 AST.Type tret = null;
5065 STC stc = STC.none;
5066 TOK save = TOK.reserved;
5067
5068 switch (token.value)
5069 {
5070 case TOK.function_:
5071 case TOK.delegate_:
5072 save = token.value;
5073 nextToken();
5074 if (token.value == TOK.auto_)
5075 {
5076 nextToken();
5077 if (token.value == TOK.ref_)
5078 {
5079 // function auto ref (parameters) { statements... }
5080 // delegate auto ref (parameters) { statements... }
5081 stc = STC.auto_ | STC.ref_ | STC.autoref;
5082 nextToken();
5083 }
5084 else
5085 error("`auto` can only be used as part of `auto ref` for function literal return values");
5086 }
5087 else if (token.value == TOK.ref_)
5088 {
5089 // function ref (parameters) { statements... }
5090 // delegate ref (parameters) { statements... }
5091 stc = STC.ref_;
5092 nextToken();
5093 }
5094 if (token.value != TOK.leftParenthesis && token.value != TOK.leftCurly &&
5095 token.value != TOK.goesTo)
5096 {
5097 // function type (parameters) { statements... }
5098 // delegate type (parameters) { statements... }
5099 tret = parseBasicType();
5100 tret = parseTypeSuffixes(tret); // function return type
5101 }
5102
5103 if (token.value == TOK.leftParenthesis)
5104 {
5105 // function (parameters) { statements... }
5106 // delegate (parameters) { statements... }
5107 }
5108 else
5109 {
5110 // function { statements... }
5111 // delegate { statements... }
5112 break;
5113 }
5114 goto case TOK.leftParenthesis;
5115
5116 case TOK.auto_:
5117 {
5118 nextToken();
5119 if (token.value == TOK.ref_)
5120 {
5121 // auto ref (parameters) => expression
5122 // auto ref (parameters) { statements... }
5123 stc = STC.auto_ | STC.ref_ | STC.autoref;
5124 nextToken();
5125 }
5126 else
5127 error("`auto` can only be used as part of `auto ref` for function literal return values");
5128 goto case TOK.leftParenthesis;
5129 }
5130 case TOK.ref_:
5131 {
5132 // ref (parameters) => expression
5133 // ref (parameters) { statements... }
5134 stc = STC.ref_;
5135 nextToken();
5136 goto case TOK.leftParenthesis;
5137 }
5138 case TOK.leftParenthesis:
5139 {
5140 // (parameters) => expression
5141 // (parameters) { statements... }
5142 parameterList = parseParameterList(&tpl);
5143 stc = parsePostfix(stc, null);
5144 if (STC modStc = stc & STC.TYPECTOR)
5145 {
5146 if (save == TOK.function_)
5147 {
5148 OutBuffer buf;
5149 AST.stcToBuffer(buf, modStc);
5150 error("function literal cannot be `%s`", buf.peekChars());
5151 }
5152 else
5153 save = TOK.delegate_;
5154 }
5155 break;
5156 }
5157 case TOK.leftCurly:
5158 // { statements... }
5159 break;
5160
5161 case TOK.identifier:
5162 {
5163 // identifier => expression
5164 parameterList.parameters = new AST.Parameters();
5165 Identifier id = Identifier.generateId("__T");
5166 AST.Type t = new AST.TypeIdentifier(loc, id);
5167 parameterList.parameters.push(new AST.Parameter(loc, STC.parameter, t, token.ident, null, null));
5168
5169 tpl = new AST.TemplateParameters();
5170 AST.TemplateParameter tp = new AST.TemplateTypeParameter(loc, id, null, null);
5171 tpl.push(tp);
5172
5173 nextToken();
5174 break;
5175 }
5176 default:
5177 assert(0);
5178 }
5179
5180 auto tf = new AST.TypeFunction(parameterList, tret, linkage, stc);
5181 tf = cast(AST.TypeFunction)tf.addSTC(stc);
5182 auto fd = new AST.FuncLiteralDeclaration(loc, Loc.initial, tf, save, null, null, stc & STC.auto_);
5183
5184 if (token.value == TOK.goesTo)
5185 {
5186 check(TOK.goesTo);
5187 if (token.value == TOK.leftCurly)
5188 {
5189 deprecation("using `(args) => { ... }` to create a delegate that returns a delegate is error-prone.");
5190 deprecationSupplemental("Use `(args) { ... }` for a multi-statement function literal or use `(args) => () { }` if you intended for the lambda to return a delegate.");
5191 }
5192 const returnloc = token.loc;
5193 AST.Expression ae = parseAssignExp();
5194 fd.fbody = new AST.ReturnStatement(returnloc, ae);
5195 fd.endloc = token.loc;
5196 }
5197 else
5198 {
5199 parseContracts(fd);
5200 }
5201
5202 if (tpl)
5203 {
5204 // Wrap a template around function fd
5205 auto decldefs = new AST.Dsymbols();
5206 decldefs.push(fd);
5207 return new AST.TemplateDeclaration(fd.loc, fd.ident, tpl, null, decldefs, false, true);
5208 }
5209 return fd;
5210 }
5211
5212 /*****************************************
5213 * Parse contracts following function declaration.
5214 */
5215 private AST.FuncDeclaration parseContracts(AST.FuncDeclaration f, bool isTemplateFunction = false)
5216 {
5217 LINK linksave = linkage;
5218
5219 bool literal = f.isFuncLiteralDeclaration() !is null;
5220
5221 // The following is irrelevant, as it is overridden by sc.linkage in
5222 // TypeFunction::semantic
5223 linkage = LINK.d; // nested functions have D linkage
5224 bool requireDo = false;
5225 L1:
5226 switch (token.value)
5227 {
5228 case TOK.goesTo:
5229 if (requireDo)
5230 error("missing `do { ... }` after `in` or `out`");
5231 const returnloc = token.loc;
5232 nextToken();
5233 if (f.isCtorDeclaration)
5234 f.fbody = new AST.ExpStatement(returnloc, parseExpression());
5235 else
5236 f.fbody = new AST.ReturnStatement(returnloc, parseExpression());
5237 f.endloc = token.loc;
5238 check(TOK.semicolon);
5239 break;
5240
5241 case TOK.leftCurly:
5242 if (requireDo)
5243 error("missing `do { ... }` after `in` or `out`");
5244 f.fbody = parseStatement(0);
5245 f.endloc = endloc;
5246 break;
5247
5248 case TOK.identifier:
5249 if (token.ident == Id._body)
5250 {
5251 usageOfBodyKeyword();
5252 goto case TOK.do_;
5253 }
5254 goto default;
5255
5256 case TOK.do_:
5257 nextToken();
5258 f.fbody = parseStatement(ParseStatementFlags.curly);
5259 f.endloc = endloc;
5260 break;
5261
5262 version (none)
5263 {
5264 // Do we want this for function declarations, so we can do:
5265 // int x, y, foo(), z;
5266 case TOK.comma:
5267 nextToken();
5268 continue;
5269 }
5270
5271 case TOK.in_:
5272 // in { statements... }
5273 // in (expression)
5274 auto loc = token.loc;
5275 nextToken();
5276 if (!f.frequires)
5277 {
5278 f.frequires = new AST.Statements;
5279 }
5280 if (token.value == TOK.leftParenthesis)
5281 {
5282 nextToken();
5283 AST.Expression e = parseAssignExp(), msg = null;
5284 if (token.value == TOK.comma)
5285 {
5286 nextToken();
5287 if (token.value != TOK.rightParenthesis)
5288 {
5289 msg = parseAssignExp();
5290 if (token.value == TOK.comma)
5291 nextToken();
5292 }
5293 }
5294 check(TOK.rightParenthesis);
5295 e = new AST.AssertExp(loc, e, msg);
5296 f.frequires.push(new AST.ExpStatement(loc, e));
5297 requireDo = false;
5298 }
5299 else
5300 {
5301 auto ret = parseStatement(ParseStatementFlags.curly | ParseStatementFlags.scope_);
5302 assert(ret);
5303 f.frequires.push(ret);
5304 requireDo = true;
5305 }
5306 goto L1;
5307
5308 case TOK.out_:
5309 // out { statements... }
5310 // out (; expression)
5311 // out (identifier) { statements... }
5312 // out (identifier; expression)
5313 auto loc = token.loc;
5314 nextToken();
5315 if (!f.fensures)
5316 {
5317 f.fensures = new AST.Ensures;
5318 }
5319 Identifier id = null;
5320 if (token.value != TOK.leftCurly)
5321 {
5322 check(TOK.leftParenthesis);
5323 if (token.value != TOK.identifier && token.value != TOK.semicolon)
5324 error("`(identifier) { ... }` or `(identifier; expression)` following `out` expected, not `%s`", token.toChars());
5325 if (token.value != TOK.semicolon)
5326 {
5327 id = token.ident;
5328 nextToken();
5329 }
5330 if (token.value == TOK.semicolon)
5331 {
5332 nextToken();
5333 AST.Expression e = parseAssignExp(), msg = null;
5334 if (token.value == TOK.comma)
5335 {
5336 nextToken();
5337 if (token.value != TOK.rightParenthesis)
5338 {
5339 msg = parseAssignExp();
5340 if (token.value == TOK.comma)
5341 nextToken();
5342 }
5343 }
5344 check(TOK.rightParenthesis);
5345 e = new AST.AssertExp(loc, e, msg);
5346 f.fensures.push(AST.Ensure(id, new AST.ExpStatement(loc, e)));
5347 requireDo = false;
5348 goto L1;
5349 }
5350 check(TOK.rightParenthesis);
5351 }
5352 f.fensures.push(AST.Ensure(id, parseStatement(ParseStatementFlags.curly | ParseStatementFlags.scope_)));
5353 requireDo = true;
5354 goto L1;
5355
5356 case TOK.semicolon:
5357 if (!literal)
5358 {
5359 // https://issues.dlang.org/show_bug.cgi?id=15799
5360 // Semicolon becomes a part of function declaration
5361 // only when 'do' is not required
5362 if (!requireDo)
5363 nextToken();
5364 break;
5365 }
5366 goto default;
5367
5368 default:
5369 if (literal)
5370 {
5371 const(char)* sbody = requireDo ? "do " : "";
5372 error("missing `%s{ ... }` for function literal", sbody);
5373 }
5374 else if (!requireDo) // allow contracts even with no body
5375 {
5376 TOK t = token.value;
5377 if (t == TOK.const_ || t == TOK.immutable_ || t == TOK.inout_ || t == TOK.return_ ||
5378 t == TOK.shared_ || t == TOK.nothrow_ || t == TOK.pure_)
5379 error("'%s' cannot be placed after a template constraint", token.toChars);
5380 else if (t == TOK.at)
5381 error("attributes cannot be placed after a template constraint");
5382 else if (t == TOK.if_)
5383 {
5384 if (isTemplateFunction)
5385 error("template constraint must follow parameter lists and attributes");
5386 else
5387 error("cannot use function constraints for non-template functions. Use `static if` instead");
5388
5389 parseConstraint();
5390 }
5391 else
5392 {
5393 error("semicolon expected following function declaration, not `%s`", token.toChars());
5394 nextToken();
5395 }
5396 }
5397 break;
5398 }
5399 if (literal && !f.fbody)
5400 {
5401 // Set empty function body for error recovery
5402 f.fbody = new AST.CompoundStatement(Loc.initial, cast(AST.Statement)null);
5403 }
5404
5405 linkage = linksave;
5406
5407 return f;
5408 }
5409
5410 /*****************************************
5411 */
5412 private void checkDanglingElse(Loc elseloc)
5413 {
5414 if (token.value != TOK.else_ && token.value != TOK.catch_ && token.value != TOK.finally_ && lookingForElse.isValid)
5415 {
5416 eSink.warning(elseloc, "else is dangling, add { } after condition at %s", lookingForElse.toChars());
5417 }
5418 }
5419
5420 /* *************************
5421 * Issue errors if C-style syntax
5422 * Params:
5423 * alt = !=0 for C-style syntax
5424 */
5425 private void checkCstyleTypeSyntax(Loc loc, AST.Type t, int alt, Identifier ident)
5426 {
5427 if (!alt)
5428 return;
5429
5430 const(char)* sp = !ident ? "" : " ";
5431 const(char)* s = !ident ? "" : ident.toChars();
5432 error(loc, "instead of C-style syntax, use D-style `%s%s%s`", t.toChars(), sp, s);
5433 }
5434
5435 /*****************************
5436 * Ad-hoc error message for missing or extra parens that close a condition.
5437 * Params:
5438 * start = "if", "while", etc. Must be 0 terminated.
5439 * param = if the condition is a declaration, this will be non-null
5440 * condition = if param is null, then this is the conditional Expression. If condition is null,
5441 * then an error in the condition was already reported.
5442 */
5443 private void closeCondition(string start, AST.Parameter param, AST.Expression condition)
5444 {
5445 string format;
5446 if (token.value != TOK.rightParenthesis && condition)
5447 {
5448 format = "missing closing `)` after `%s (%s`";
5449 }
5450 else
5451 check(TOK.rightParenthesis);
5452 if (token.value == TOK.rightParenthesis)
5453 {
5454 if (condition) // if not an error in condition
5455 format = "extra `)` after `%s (%s)`";
5456 nextToken();
5457 }
5458 if (format)
5459 error(token.loc, format.ptr, start.ptr, param ? "declaration".ptr : condition.toChars());
5460 }
5461
5462 /*****************************************
5463 * Parses `foreach` statements, `static foreach` statements and
5464 * `static foreach` declarations.
5465 * Params:
5466 * Foreach = one of Statement, StaticForeachStatement, StaticForeachDeclaration
5467 * loc = location of foreach
5468 * pLastDecl = non-null for StaticForeachDeclaration
5469 * Returns:
5470 * the Foreach generated
5471 */
5472 private Foreach parseForeach(alias Foreach)(Loc loc, AST.Dsymbol* pLastDecl)
5473 {
5474 static if (is(Foreach == AST.StaticForeachStatement) || is(Foreach == AST.StaticForeachDeclaration))
5475 {
5476 nextToken();
5477 }
5478
5479 TOK op = token.value;
5480
5481 nextToken();
5482 check(TOK.leftParenthesis);
5483
5484 auto parameters = new AST.Parameters();
5485 Identifier lastai;
5486 while (1)
5487 {
5488 Identifier ai = null;
5489 AST.Type at;
5490 Loc aloc;
5491
5492 STC storageClass = STC.none;
5493 STC stc = STC.none;
5494 Lagain:
5495 if (stc)
5496 {
5497 storageClass = appendStorageClass(storageClass, stc);
5498 nextToken();
5499 }
5500 switch (token.value)
5501 {
5502 case TOK.ref_:
5503 stc = STC.ref_;
5504 goto Lagain;
5505
5506 case TOK.scope_:
5507 stc = STC.scope_;
5508 goto Lagain;
5509
5510 case TOK.out_:
5511 error("cannot declare `out` loop variable, use `ref` instead");
5512 stc = STC.out_;
5513 goto Lagain;
5514
5515 case TOK.auto_:
5516 error("cannot declare `auto` loop variable, omit `auto` to still get type inference");
5517 stc = STC.auto_;
5518 goto Lagain;
5519
5520 case TOK.enum_:
5521 stc = STC.manifest;
5522 goto Lagain;
5523
5524 case TOK.alias_:
5525 storageClass = appendStorageClass(storageClass, STC.alias_);
5526 nextToken();
5527 break;
5528
5529 case TOK.const_:
5530 if (peekNext() != TOK.leftParenthesis)
5531 {
5532 stc = STC.const_;
5533 goto Lagain;
5534 }
5535 break;
5536
5537 case TOK.immutable_:
5538 if (peekNext() != TOK.leftParenthesis)
5539 {
5540 stc = STC.immutable_;
5541 goto Lagain;
5542 }
5543 break;
5544
5545 case TOK.shared_:
5546 if (peekNext() != TOK.leftParenthesis)
5547 {
5548 stc = STC.shared_;
5549 goto Lagain;
5550 }
5551 break;
5552
5553 case TOK.inout_:
5554 if (peekNext() != TOK.leftParenthesis)
5555 {
5556 stc = STC.wild;
5557 goto Lagain;
5558 }
5559 break;
5560
5561 default:
5562 break;
5563 }
5564 if (token.value == TOK.identifier)
5565 {
5566 const tv = peekNext();
5567 if (tv == TOK.comma || tv == TOK.semicolon || tv == TOK.rightParenthesis)
5568 {
5569 lastai = token.ident;
5570 ai = token.ident;
5571 at = null; // infer argument type
5572 aloc = token.loc;
5573 nextToken();
5574 goto Larg;
5575 }
5576 }
5577 at = parseType(&ai);
5578 if (!ai)
5579 noIdentifierForDeclarator(at, token);
5580 Larg:
5581 auto p = new AST.Parameter(aloc, storageClass, at, ai, null, null);
5582 parameters.push(p);
5583 if (token.value == TOK.comma)
5584 {
5585 nextToken();
5586 continue;
5587 }
5588 break;
5589 }
5590 if (token.value != TOK.semicolon)
5591 {
5592 error("missing `; expression` before `)` of `foreach`");
5593 nextToken();
5594 if (lastai && parameters.length >= 2)
5595 {
5596 eSink.errorSupplemental(loc, "perhaps the `;` goes before `%s`", lastai.toChars());
5597 }
5598 return null;
5599 }
5600 nextToken();
5601
5602 AST.Expression aggr = parseExpression();
5603 if (token.value == TOK.slice && parameters.length == 1)
5604 {
5605 AST.Parameter p = (*parameters)[0];
5606 nextToken();
5607 AST.Expression upr = parseExpression();
5608 check(TOK.rightParenthesis);
5609 Loc endloc;
5610 static if (is(Foreach == AST.Statement) || is(Foreach == AST.StaticForeachStatement))
5611 {
5612 AST.Statement _body = parseStatement(0, null, &endloc);
5613 }
5614 else
5615 {
5616 AST.Statement _body = null;
5617 }
5618 auto rangefe = new AST.ForeachRangeStatement(loc, op, p, aggr, upr, _body, endloc);
5619 static if (is(Foreach == AST.Statement))
5620 {
5621 return rangefe;
5622 }
5623 else static if(is(Foreach == AST.StaticForeachDeclaration))
5624 {
5625 return new AST.StaticForeachDeclaration(new AST.StaticForeach(loc, null, rangefe), parseBlock(pLastDecl));
5626 }
5627 else static if (is(Foreach == AST.StaticForeachStatement))
5628 {
5629 return new AST.StaticForeachStatement(loc, new AST.StaticForeach(loc, null, rangefe));
5630 }
5631 }
5632 else
5633 {
5634 check(TOK.rightParenthesis);
5635 Loc endloc;
5636 static if (is(Foreach == AST.Statement) || is(Foreach == AST.StaticForeachStatement))
5637 {
5638 AST.Statement _body = parseStatement(0, null, &endloc);
5639 }
5640 else
5641 {
5642 AST.Statement _body = null;
5643 }
5644 auto aggrfe = new AST.ForeachStatement(loc, op, parameters, aggr, _body, endloc);
5645 static if (is(Foreach == AST.Statement))
5646 {
5647 return aggrfe;
5648 }
5649 else static if(is(Foreach == AST.StaticForeachDeclaration))
5650 {
5651 return new AST.StaticForeachDeclaration(new AST.StaticForeach(loc, aggrfe, null), parseBlock(pLastDecl));
5652 }
5653 else static if (is(Foreach == AST.StaticForeachStatement))
5654 {
5655 return new AST.StaticForeachStatement(loc, new AST.StaticForeach(loc, aggrfe, null));
5656 }
5657 }
5658
5659 }
5660
5661 /***
5662 * Parse an assignment condition for `if`, `switch` or `while` statements.
5663 *
5664 * Returns:
5665 * The variable that is declared inside the condition
5666 */
5667 AST.Parameter parseAssignCondition()
5668 {
5669 AST.Parameter param = null;
5670 STC storageClass = STC.none;
5671 STC stc = STC.none;
5672 Lwhile:
5673 while (1)
5674 {
5675 switch (token.value)
5676 {
5677 // parse ref for better error
5678 case TOK.ref_:
5679 stc = STC.ref_;
5680 break;
5681
5682 case TOK.scope_:
5683 stc = STC.scope_;
5684 break;
5685
5686 case TOK.auto_:
5687 stc = STC.auto_;
5688 if (peekNext() == TOK.ref_)
5689 stc |= STC.autoref;
5690 break;
5691
5692 case TOK.const_:
5693 if (peekNext() != TOK.leftParenthesis)
5694 {
5695 stc = STC.const_;
5696 break;
5697 }
5698 goto default;
5699
5700 case TOK.immutable_:
5701 if (peekNext() != TOK.leftParenthesis)
5702 {
5703 stc = STC.immutable_;
5704 break;
5705 }
5706 goto default;
5707
5708 case TOK.shared_:
5709 if (peekNext() != TOK.leftParenthesis)
5710 {
5711 stc = STC.shared_;
5712 break;
5713 }
5714 goto default;
5715
5716 case TOK.inout_:
5717 if (peekNext() != TOK.leftParenthesis)
5718 {
5719 stc = STC.wild;
5720 break;
5721 }
5722 goto default;
5723
5724 default:
5725 break Lwhile;
5726 }
5727 storageClass = appendStorageClass(storageClass, stc);
5728 nextToken();
5729 }
5730 auto n = peek(&token);
5731 if (storageClass != 0 && token.value == TOK.identifier && n.value == TOK.assign)
5732 {
5733 Identifier ai = token.ident;
5734 AST.Type at = null; // infer parameter type
5735 const aloc = token.loc;
5736 nextToken();
5737 check(TOK.assign);
5738 param = new AST.Parameter(aloc, storageClass, at, ai, null, null);
5739 }
5740 else if (isDeclaration(&token, NeedDeclaratorId.must, TOK.assign, null))
5741 {
5742 Identifier ai;
5743 const aloc = token.loc;
5744 AST.Type at = parseType(&ai);
5745 check(TOK.assign);
5746 param = new AST.Parameter(aloc, storageClass, at, ai, null, null);
5747 }
5748 else if (storageClass != 0)
5749 error("found `%s` while expecting `=` or identifier", n.toChars());
5750
5751 return param;
5752 }
5753
5754 /*****************************************
5755 * Input:
5756 * flags PSxxxx
5757 * Output:
5758 * pEndloc if { ... statements ... }, store location of closing brace, otherwise loc of last token of statement
5759 */
5760 AST.Statement parseStatement(int flags, const(char)** endPtr = null, Loc* pEndloc = null)
5761 {
5762 AST.Statement s;
5763 AST.Condition cond;
5764 AST.Statement ifbody;
5765 AST.Statement elsebody;
5766 bool isfinal;
5767 const loc = token.loc;
5768
5769 //printf("parseStatement()\n");
5770 if (flags & ParseStatementFlags.curly && token.value != TOK.leftCurly)
5771 error("statement expected to be `{ }`, not `%s`", token.toChars());
5772
5773 switch (token.value)
5774 {
5775 case TOK.identifier:
5776 {
5777 /* A leading identifier can be a declaration, label, or expression.
5778 * The easiest case to check first is label:
5779 */
5780 if (peekNext() == TOK.colonColon)
5781 {
5782 // skip ident::
5783 nextToken();
5784 nextToken();
5785 error("use `.` for member lookup, not `::`");
5786 break;
5787 }
5788
5789 if (peekNext() == TOK.colon)
5790 {
5791 // It's a label
5792 Identifier ident = token.ident;
5793 nextToken();
5794 nextToken();
5795 if (token.value == TOK.rightCurly)
5796 s = null;
5797 else if (token.value == TOK.leftCurly)
5798 s = parseStatement(ParseStatementFlags.curly | ParseStatementFlags.scope_);
5799 else if (flags & ParseStatementFlags.curlyScope)
5800 s = parseStatement(ParseStatementFlags.semiOk | ParseStatementFlags.curlyScope);
5801 else
5802 s = parseStatement(ParseStatementFlags.semiOk);
5803 s = new AST.LabelStatement(loc, ident, s);
5804 break;
5805 }
5806 goto case TOK.dot;
5807 }
5808 case TOK.dot:
5809 case TOK.typeof_:
5810 case TOK.vector:
5811 case TOK.traits:
5812 /* https://issues.dlang.org/show_bug.cgi?id=15163
5813 * If tokens can be handled as
5814 * old C-style declaration or D expression, prefer the latter.
5815 */
5816 if (isDeclaration(&token, NeedDeclaratorId.mustIfDstyle, TOK.reserved, null))
5817 goto Ldeclaration;
5818 goto Lexp;
5819
5820 case TOK.assert_:
5821 case TOK.this_:
5822 case TOK.super_:
5823 case TOK.int32Literal:
5824 case TOK.uns32Literal:
5825 case TOK.int64Literal:
5826 case TOK.uns64Literal:
5827 case TOK.int128Literal:
5828 case TOK.uns128Literal:
5829 case TOK.float32Literal:
5830 case TOK.float64Literal:
5831 case TOK.float80Literal:
5832 case TOK.imaginary32Literal:
5833 case TOK.imaginary64Literal:
5834 case TOK.imaginary80Literal:
5835 case TOK.charLiteral:
5836 case TOK.wcharLiteral:
5837 case TOK.dcharLiteral:
5838 case TOK.null_:
5839 case TOK.true_:
5840 case TOK.false_:
5841 case TOK.string_:
5842 case TOK.interpolated:
5843 case TOK.hexadecimalString:
5844 case TOK.leftParenthesis:
5845 case TOK.cast_:
5846 case TOK.mul:
5847 case TOK.min:
5848 case TOK.add:
5849 case TOK.tilde:
5850 case TOK.not:
5851 case TOK.plusPlus:
5852 case TOK.minusMinus:
5853 case TOK.new_:
5854 case TOK.delegate_:
5855 case TOK.function_:
5856 case TOK.typeid_:
5857 case TOK.is_:
5858 case TOK.leftBracket:
5859 case TOK.file:
5860 case TOK.fileFullPath:
5861 case TOK.line:
5862 case TOK.moduleString:
5863 case TOK.functionString:
5864 case TOK.prettyFunction:
5865 case TOK.rvalue:
5866 Lexp:
5867 {
5868 AST.Expression exp = parseExpression();
5869 /* https://issues.dlang.org/show_bug.cgi?id=15103
5870 * Improve declaration / initialization syntax error message
5871 * Error: found 'foo' when expecting ';' following expression
5872 * becomes Error: found `(` when expecting `;` or `=`, did you mean `Foo foo = 42`?
5873 */
5874 if (token.value == TOK.identifier && exp.op == EXP.identifier)
5875 {
5876 error(token.loc, "found `%s` when expecting `;` or `=`, did you mean `%s %s = %s`?", peek(&token).toChars(), exp.toChars(), token.toChars(), peek(peek(&token)).toChars());
5877 nextToken();
5878 }
5879 else
5880 {
5881 /*
5882 * https://issues.dlang.org/show_bug.cgi?id=22529
5883 * Avoid empty declaration error in case of missing semicolon
5884 * followed by another token and another semicolon. E.g.:
5885 *
5886 * foo()
5887 * return;
5888 *
5889 * When the missing `;` error is emitted, token is sitting on return.
5890 * If we simply use `check` to emit the error, the token is advanced
5891 * to `;` and the empty statement error would follow. To avoid that,
5892 * we check if the next token is a semicolon and simply output the error,
5893 * otherwise we fall back on the old path (advancing the token).
5894 */
5895 if (token.value != TOK.semicolon && peek(&token).value == TOK.semicolon)
5896 error("found `%s` when expecting `;` following expression", token.toChars());
5897 else
5898 {
5899 if (token.value != TOK.semicolon)
5900 {
5901 error("found `%s` when expecting `;` following expression", token.toChars());
5902 eSink.errorSupplemental(exp.loc, "expression: `%s`", exp.toChars());
5903 }
5904 nextToken();
5905 }
5906 }
5907 s = new AST.ExpStatement(loc, exp);
5908 break;
5909 }
5910 case TOK.static_:
5911 {
5912 // Look ahead to see if it's static assert() or static if()
5913 const tv = peekNext();
5914 if (tv == TOK.assert_)
5915 {
5916 s = new AST.StaticAssertStatement(parseStaticAssert());
5917 break;
5918 }
5919 if (tv == TOK.if_)
5920 {
5921 cond = parseStaticIfCondition();
5922 goto Lcondition;
5923 }
5924 if (tv == TOK.foreach_ || tv == TOK.foreach_reverse_)
5925 {
5926 s = parseForeach!(AST.StaticForeachStatement)(loc, null);
5927 if (flags & ParseStatementFlags.scope_)
5928 s = new AST.ScopeStatement(loc, s, token.loc);
5929 break;
5930 }
5931 if (tv == TOK.import_)
5932 {
5933 AST.Dsymbols* imports = parseImport();
5934 s = new AST.ImportStatement(loc, imports);
5935 if (flags & ParseStatementFlags.scope_)
5936 s = new AST.ScopeStatement(loc, s, token.loc);
5937 break;
5938 }
5939 goto Ldeclaration;
5940 }
5941 case TOK.final_:
5942 if (peekNext() == TOK.switch_)
5943 {
5944 nextToken();
5945 isfinal = true;
5946 goto Lswitch;
5947 }
5948 goto Ldeclaration;
5949
5950 case TOK.wchar_:
5951 case TOK.dchar_:
5952 case TOK.bool_:
5953 case TOK.char_:
5954 case TOK.int8:
5955 case TOK.uns8:
5956 case TOK.int16:
5957 case TOK.uns16:
5958 case TOK.int32:
5959 case TOK.uns32:
5960 case TOK.int64:
5961 case TOK.uns64:
5962 case TOK.int128:
5963 case TOK.uns128:
5964 case TOK.float32:
5965 case TOK.float64:
5966 case TOK.float80:
5967 case TOK.imaginary32:
5968 case TOK.imaginary64:
5969 case TOK.imaginary80:
5970 case TOK.complex32:
5971 case TOK.complex64:
5972 case TOK.complex80:
5973 case TOK.void_:
5974 // bug 7773: int.max is always a part of expression
5975 if (peekNext() == TOK.dot)
5976 goto Lexp;
5977 if (peekNext() == TOK.leftParenthesis)
5978 goto Lexp;
5979 goto case;
5980
5981 // FunctionLiteral `auto ref (`
5982 case TOK.auto_:
5983 if (peekNext() == TOK.ref_ && peekNext2() == TOK.leftParenthesis)
5984 goto Lexp;
5985 goto Ldeclaration;
5986 case TOK.ref_:
5987 if (peekNext() == TOK.leftParenthesis)
5988 goto Lexp;
5989 goto Ldeclaration;
5990
5991 case TOK.alias_:
5992 case TOK.const_:
5993 case TOK.abstract_:
5994 case TOK.extern_:
5995 case TOK.align_:
5996 case TOK.immutable_:
5997 case TOK.shared_:
5998 case TOK.inout_:
5999 case TOK.deprecated_:
6000 case TOK.nothrow_:
6001 case TOK.pure_:
6002 case TOK.gshared:
6003 case TOK.at:
6004 case TOK.struct_:
6005 case TOK.union_:
6006 case TOK.class_:
6007 case TOK.interface_:
6008 Ldeclaration:
6009 {
6010 AST.Dsymbols* a = parseDeclarations(false, null, null);
6011 if (a.length > 1)
6012 {
6013 auto as = new AST.Statements();
6014 as.reserve(a.length);
6015 foreach (i; 0 .. a.length)
6016 {
6017 AST.Dsymbol d = (*a)[i];
6018 s = new AST.ExpStatement(loc, d);
6019 as.push(s);
6020 }
6021 s = new AST.CompoundDeclarationStatement(loc, as);
6022 }
6023 else if (a.length == 1)
6024 {
6025 AST.Dsymbol d = (*a)[0];
6026 s = new AST.ExpStatement(loc, d);
6027 }
6028 else
6029 s = new AST.ExpStatement(loc, cast(AST.Expression)null);
6030 if (flags & ParseStatementFlags.scope_)
6031 s = new AST.ScopeStatement(loc, s, token.loc);
6032 break;
6033 }
6034 case TOK.enum_:
6035 {
6036 /* Determine if this is a manifest constant declaration,
6037 * or a conventional enum.
6038 */
6039 AST.Dsymbol d;
6040 const tv = peekNext();
6041 if (tv == TOK.leftCurly || tv == TOK.colon)
6042 d = parseEnum();
6043 else if (tv != TOK.identifier)
6044 goto Ldeclaration;
6045 else
6046 {
6047 const nextv = peekNext2();
6048 if (nextv == TOK.leftCurly || nextv == TOK.colon || nextv == TOK.semicolon)
6049 d = parseEnum();
6050 else
6051 goto Ldeclaration;
6052 }
6053 s = new AST.ExpStatement(loc, d);
6054 if (flags & ParseStatementFlags.scope_)
6055 s = new AST.ScopeStatement(loc, s, token.loc);
6056 break;
6057 }
6058 case TOK.mixin_:
6059 {
6060 if (isDeclaration(&token, NeedDeclaratorId.mustIfDstyle, TOK.reserved, null))
6061 goto Ldeclaration;
6062 const tv = peekNext();
6063 if (tv == TOK.leftParenthesis)
6064 {
6065 // mixin(string)
6066 AST.Expression e = parseAssignExp();
6067 check(TOK.semicolon, "mixin");
6068 if (e.op == EXP.mixin_)
6069 {
6070 AST.MixinExp cpe = cast(AST.MixinExp)e;
6071 s = new AST.MixinStatement(loc, cpe.exps);
6072 }
6073 else
6074 {
6075 s = new AST.ExpStatement(loc, e);
6076 }
6077 break;
6078 }
6079 else if (tv == TOK.template_)
6080 {
6081 // mixin template
6082 nextToken();
6083 AST.Dsymbol d = parseTemplateDeclaration(true);
6084 s = new AST.ExpStatement(loc, d);
6085 break;
6086 }
6087 AST.Dsymbol d = parseMixin();
6088 s = new AST.ExpStatement(loc, d);
6089 if (flags & ParseStatementFlags.scope_)
6090 s = new AST.ScopeStatement(loc, s, token.loc);
6091 break;
6092 }
6093 case TOK.leftCurly:
6094 {
6095 const lcLoc = token.loc;
6096 const lookingForElseSave = lookingForElse;
6097 lookingForElse = Loc.initial;
6098
6099 nextToken();
6100 //if (token.value == TOK.semicolon)
6101 // error("use `{ }` for an empty statement, not `;`");
6102 auto statements = new AST.Statements();
6103 while (token.value != TOK.rightCurly && token.value != TOK.endOfFile)
6104 {
6105 statements.push(parseStatement(ParseStatementFlags.curlyScope | ParseStatementFlags.semiOk));
6106 }
6107 if (endPtr)
6108 *endPtr = token.ptr;
6109 endloc = token.loc;
6110 if (pEndloc)
6111 {
6112 *pEndloc = token.loc;
6113 pEndloc = null; // don't set it again
6114 }
6115 s = new AST.CompoundStatement(loc, statements);
6116 if (flags & (ParseStatementFlags.scope_ | ParseStatementFlags.curlyScope))
6117 s = new AST.ScopeStatement(loc, s, token.loc);
6118 if (token.value != TOK.rightCurly)
6119 {
6120 error(token.loc, "matching `}` expected following compound statement, not `%s`",
6121 token.toChars());
6122 eSink.errorSupplemental(lcLoc, "unmatched `{`");
6123 }
6124 else
6125 nextToken();
6126 lookingForElse = lookingForElseSave;
6127 break;
6128 }
6129 case TOK.while_:
6130 {
6131 nextToken();
6132 check(TOK.leftParenthesis);
6133 auto param = parseAssignCondition();
6134 auto condition = parseExpression();
6135 closeCondition("while", param, condition);
6136
6137 Loc endloc;
6138 AST.Statement _body = parseStatement(ParseStatementFlags.scope_, null, &endloc);
6139 s = new AST.WhileStatement(loc, condition, _body, endloc, param);
6140 break;
6141 }
6142 case TOK.semicolon:
6143 if (!(flags & ParseStatementFlags.semiOk))
6144 {
6145 error("use `{ }` for an empty statement, not `;`");
6146 }
6147 nextToken();
6148 s = new AST.ExpStatement(loc, cast(AST.Expression)null);
6149 break;
6150
6151 case TOK.do_:
6152 {
6153 AST.Statement _body;
6154
6155 nextToken();
6156 const lookingForElseSave = lookingForElse;
6157 lookingForElse = Loc.initial;
6158 _body = parseStatement(ParseStatementFlags.scope_);
6159 lookingForElse = lookingForElseSave;
6160 check(TOK.while_);
6161 check(TOK.leftParenthesis);
6162 auto condition = parseExpression();
6163 closeCondition("do .. while", null, condition);
6164 if (token.value == TOK.semicolon)
6165 nextToken();
6166 else
6167 error("terminating `;` required after do-while statement");
6168 s = new AST.DoStatement(loc, _body, condition, token.loc);
6169 break;
6170 }
6171 case TOK.for_:
6172 {
6173 AST.Statement _init;
6174 AST.Expression condition;
6175 AST.Expression increment;
6176
6177 nextToken();
6178 check(TOK.leftParenthesis);
6179 if (token.value == TOK.semicolon)
6180 {
6181 _init = null;
6182 nextToken();
6183 }
6184 else
6185 {
6186 const lookingForElseSave = lookingForElse;
6187 lookingForElse = Loc.initial;
6188 _init = parseStatement(0);
6189 lookingForElse = lookingForElseSave;
6190 }
6191 if (token.value == TOK.semicolon)
6192 {
6193 condition = null;
6194 nextToken();
6195 }
6196 else
6197 {
6198 condition = parseExpression();
6199 check(TOK.semicolon, "`for` condition");
6200 }
6201 if (token.value == TOK.rightParenthesis)
6202 {
6203 increment = null;
6204 nextToken();
6205 }
6206 else
6207 {
6208 increment = parseExpression();
6209 check(TOK.rightParenthesis);
6210 }
6211 Loc endloc;
6212 AST.Statement _body = parseStatement(ParseStatementFlags.scope_, null, &endloc);
6213 s = new AST.ForStatement(loc, _init, condition, increment, _body, endloc);
6214 break;
6215 }
6216 case TOK.foreach_:
6217 case TOK.foreach_reverse_:
6218 {
6219 s = parseForeach!(AST.Statement)(loc, null);
6220 break;
6221 }
6222 case TOK.if_:
6223 {
6224 nextToken();
6225 check(TOK.leftParenthesis);
6226 auto param = parseAssignCondition();
6227 auto condition = parseExpression();
6228 closeCondition("if", param, condition);
6229
6230 {
6231 const lookingForElseSave = lookingForElse;
6232 lookingForElse = loc;
6233 ifbody = parseStatement(ParseStatementFlags.scope_);
6234 lookingForElse = lookingForElseSave;
6235 }
6236 if (token.value == TOK.else_)
6237 {
6238 const elseloc = token.loc;
6239 nextToken();
6240 elsebody = parseStatement(ParseStatementFlags.scope_);
6241 checkDanglingElse(elseloc);
6242 }
6243 else
6244 elsebody = null;
6245 if (condition && ifbody)
6246 s = new AST.IfStatement(loc, param, condition, ifbody, elsebody, token.loc);
6247 else
6248 s = null; // don't propagate parsing errors
6249 break;
6250 }
6251
6252 case TOK.else_:
6253 error("found `else` without a corresponding `if`, `version` or `debug` statement");
6254 goto Lerror;
6255
6256 case TOK.scope_:
6257 if (peekNext() != TOK.leftParenthesis)
6258 goto Ldeclaration; // scope used as storage class
6259 nextToken();
6260 check(TOK.leftParenthesis);
6261 if (token.value != TOK.identifier)
6262 {
6263 error("scope identifier expected");
6264 goto Lerror;
6265 }
6266 else
6267 {
6268 TOK t = TOK.onScopeExit;
6269 Identifier id = token.ident;
6270 if (id == Id.exit)
6271 t = TOK.onScopeExit;
6272 else if (id == Id.failure)
6273 t = TOK.onScopeFailure;
6274 else if (id == Id.success)
6275 t = TOK.onScopeSuccess;
6276 else
6277 error("valid scope identifiers are `exit`, `failure`, or `success`, not `%s`", id.toChars());
6278 nextToken();
6279 check(TOK.rightParenthesis);
6280 AST.Statement st = parseStatement(ParseStatementFlags.scope_);
6281 s = new AST.ScopeGuardStatement(loc, t, st);
6282 break;
6283 }
6284
6285 case TOK.debug_:
6286 nextToken();
6287 if (token.value == TOK.assign)
6288 {
6289 if (auto ds = parseDebugSpecification())
6290 eSink.error(ds.loc, "%s `%s` declaration must be at module level", ds.kind, ds.toPrettyChars);
6291
6292 break;
6293 }
6294 cond = parseDebugCondition();
6295 goto Lcondition;
6296
6297 case TOK.version_:
6298 nextToken();
6299 if (token.value == TOK.assign)
6300 {
6301 if (auto vs = parseVersionSpecification())
6302 eSink.error(vs.loc, "%s `%s` declaration must be at module level", vs.kind, vs.toPrettyChars);
6303
6304 break;
6305 }
6306 cond = parseVersionCondition();
6307 goto Lcondition;
6308
6309 Lcondition:
6310 {
6311 const lookingForElseSave = lookingForElse;
6312 lookingForElse = loc;
6313 ifbody = parseStatement(0);
6314 lookingForElse = lookingForElseSave;
6315 }
6316 elsebody = null;
6317 if (token.value == TOK.else_)
6318 {
6319 const elseloc = token.loc;
6320 nextToken();
6321 elsebody = parseStatement(0);
6322 checkDanglingElse(elseloc);
6323 }
6324 s = new AST.ConditionalStatement(loc, cond, ifbody, elsebody);
6325 if (flags & ParseStatementFlags.scope_)
6326 s = new AST.ScopeStatement(loc, s, token.loc);
6327 break;
6328
6329 case TOK.pragma_:
6330 {
6331 Identifier ident;
6332 AST.Expressions* args = null;
6333 AST.Statement _body;
6334
6335 nextToken();
6336 check(TOK.leftParenthesis);
6337 if (token.value != TOK.identifier)
6338 {
6339 error("`pragma(identifier)` expected");
6340 goto Lerror;
6341 }
6342 ident = token.ident;
6343 nextToken();
6344 if (token.value == TOK.comma && peekNext() != TOK.rightParenthesis)
6345 args = parseArguments(); // pragma(identifier, args...);
6346 else
6347 check(TOK.rightParenthesis); // pragma(identifier);
6348 if (token.value == TOK.semicolon)
6349 {
6350 nextToken();
6351 _body = null;
6352 }
6353 else
6354 _body = parseStatement(0);
6355 s = new AST.PragmaStatement(loc, ident, args, _body);
6356 break;
6357 }
6358 case TOK.switch_:
6359 isfinal = false;
6360 goto Lswitch;
6361
6362 Lswitch:
6363 {
6364 nextToken();
6365 check(TOK.leftParenthesis);
6366 auto param = parseAssignCondition();
6367 AST.Expression condition = parseExpression();
6368 closeCondition("switch", null, condition);
6369 AST.Statement _body = parseStatement(ParseStatementFlags.scope_);
6370 s = new AST.SwitchStatement(loc, param, condition, _body, isfinal, token.loc);
6371 break;
6372 }
6373 case TOK.case_:
6374 {
6375 AST.Expression exp;
6376 AST.Expressions cases; // array of Expression's
6377 AST.Expression last = null;
6378
6379 nextToken();
6380 do
6381 {
6382 exp = parseAssignExp();
6383 cases.push(exp);
6384 if (token.value != TOK.comma)
6385 break;
6386 nextToken(); //comma
6387 }
6388 while (token.value != TOK.colon && token.value != TOK.endOfFile);
6389 check(TOK.colon);
6390
6391 /* case exp: .. case last:
6392 */
6393 if (token.value == TOK.slice)
6394 {
6395 if (cases.length > 1)
6396 error("only one `case` allowed for start of case range");
6397 nextToken();
6398 check(TOK.case_);
6399 last = parseAssignExp();
6400 check(TOK.colon);
6401 }
6402
6403 if (flags & ParseStatementFlags.curlyScope)
6404 {
6405 auto statements = new AST.Statements();
6406 while (token.value != TOK.case_ && token.value != TOK.default_ && token.value != TOK.endOfFile && token.value != TOK.rightCurly)
6407 {
6408 auto cur = parseStatement(ParseStatementFlags.curlyScope);
6409 statements.push(cur);
6410
6411 // https://issues.dlang.org/show_bug.cgi?id=21739
6412 // Stop at the last break s.t. the following non-case statements are
6413 // not merged into the current case. This can happen for
6414 // case 1: ... break;
6415 // debug { case 2: ... }
6416 if (cur && cur.isBreakStatement())
6417 break;
6418 }
6419 s = new AST.CompoundStatement(loc, statements);
6420 }
6421 else
6422 {
6423 s = parseStatement(0);
6424 }
6425 s = new AST.ScopeStatement(loc, s, token.loc);
6426
6427 if (last)
6428 {
6429 s = new AST.CaseRangeStatement(loc, exp, last, s);
6430 }
6431 else
6432 {
6433 // Keep cases in order by building the case statements backwards
6434 for (size_t i = cases.length; i; i--)
6435 {
6436 exp = cases[i - 1];
6437 s = new AST.CaseStatement(loc, exp, s);
6438 }
6439 }
6440 break;
6441 }
6442 case TOK.default_:
6443 {
6444 nextToken();
6445 check(TOK.colon);
6446
6447 if (flags & ParseStatementFlags.curlyScope)
6448 {
6449 auto statements = new AST.Statements();
6450 while (token.value != TOK.case_ && token.value != TOK.default_ && token.value != TOK.endOfFile && token.value != TOK.rightCurly)
6451 {
6452 statements.push(parseStatement(ParseStatementFlags.curlyScope));
6453 }
6454 s = new AST.CompoundStatement(loc, statements);
6455 }
6456 else
6457 s = parseStatement(0);
6458 s = new AST.ScopeStatement(loc, s, token.loc);
6459 s = new AST.DefaultStatement(loc, s);
6460 break;
6461 }
6462 case TOK.return_:
6463 {
6464 AST.Expression exp;
6465 nextToken();
6466 exp = token.value == TOK.semicolon ? null : parseExpression();
6467 check(TOK.semicolon, "`return` statement");
6468 s = new AST.ReturnStatement(loc, exp);
6469 break;
6470 }
6471 case TOK.break_:
6472 {
6473 Identifier ident;
6474 nextToken();
6475 ident = null;
6476 if (token.value == TOK.identifier)
6477 {
6478 ident = token.ident;
6479 nextToken();
6480 }
6481 check(TOK.semicolon, "`break` statement");
6482 s = new AST.BreakStatement(loc, ident);
6483 break;
6484 }
6485 case TOK.continue_:
6486 {
6487 Identifier ident;
6488 nextToken();
6489 ident = null;
6490 if (token.value == TOK.identifier)
6491 {
6492 ident = token.ident;
6493 nextToken();
6494 }
6495 check(TOK.semicolon, "`continue` statement");
6496 s = new AST.ContinueStatement(loc, ident);
6497 break;
6498 }
6499 case TOK.goto_:
6500 {
6501 Identifier ident;
6502 nextToken();
6503 if (token.value == TOK.default_)
6504 {
6505 nextToken();
6506 s = new AST.GotoDefaultStatement(loc);
6507 }
6508 else if (token.value == TOK.case_)
6509 {
6510 AST.Expression exp = null;
6511 nextToken();
6512 if (token.value != TOK.semicolon)
6513 exp = parseExpression();
6514 s = new AST.GotoCaseStatement(loc, exp);
6515 }
6516 else
6517 {
6518 if (token.value != TOK.identifier)
6519 {
6520 error("identifier expected following `goto`");
6521 ident = null;
6522 }
6523 else
6524 {
6525 ident = token.ident;
6526 nextToken();
6527 }
6528 s = new AST.GotoStatement(loc, ident);
6529 }
6530 check(TOK.semicolon, "`goto` statement");
6531 break;
6532 }
6533 case TOK.synchronized_:
6534 {
6535 AST.Expression exp;
6536 AST.Statement _body;
6537
6538 Token* t = peek(&token);
6539 if (skipAttributes(t, &t) && t.value == TOK.class_)
6540 goto Ldeclaration;
6541
6542 nextToken();
6543 if (token.value == TOK.leftParenthesis)
6544 {
6545 nextToken();
6546 exp = parseExpression();
6547 closeCondition("synchronized", null, exp);
6548 }
6549 else
6550 exp = null;
6551 _body = parseStatement(ParseStatementFlags.scope_);
6552 s = new AST.SynchronizedStatement(loc, exp, _body);
6553 break;
6554 }
6555 case TOK.with_:
6556 {
6557 AST.Expression exp;
6558 AST.Statement _body;
6559 Loc endloc = loc;
6560
6561 nextToken();
6562 check(TOK.leftParenthesis);
6563 exp = parseExpression();
6564 closeCondition("with", null, exp);
6565 _body = parseStatement(ParseStatementFlags.scope_, null, &endloc);
6566 s = new AST.WithStatement(loc, exp, _body, endloc);
6567 break;
6568 }
6569 case TOK.try_:
6570 {
6571 AST.Statement _body;
6572 AST.Catches* catches = null;
6573 AST.Statement finalbody = null;
6574
6575 nextToken();
6576 const lookingForElseSave = lookingForElse;
6577 lookingForElse = Loc.initial;
6578 _body = parseStatement(ParseStatementFlags.scope_);
6579 lookingForElse = lookingForElseSave;
6580 while (token.value == TOK.catch_)
6581 {
6582 AST.Statement handler;
6583 AST.Catch c;
6584 AST.Type t;
6585 Identifier id;
6586 const catchloc = token.loc;
6587
6588 nextToken();
6589 if (token.value != TOK.leftParenthesis)
6590 {
6591 deprecation("`catch` statement without an exception specification is deprecated");
6592 deprecationSupplemental("use `catch(Throwable)` for old behavior");
6593 t = null;
6594 id = null;
6595 }
6596 else
6597 {
6598 check(TOK.leftParenthesis);
6599 id = null;
6600 t = parseType(&id);
6601 check(TOK.rightParenthesis);
6602 }
6603 handler = parseStatement(0);
6604 c = new AST.Catch(catchloc, t, id, handler);
6605 if (!catches)
6606 catches = new AST.Catches();
6607 catches.push(c);
6608 }
6609
6610 if (token.value == TOK.finally_)
6611 {
6612 nextToken();
6613 finalbody = parseStatement(ParseStatementFlags.scope_);
6614 }
6615
6616 s = _body;
6617 if (!catches && !finalbody)
6618 error("`catch` or `finally` expected following `try`");
6619 else
6620 {
6621 if (catches)
6622 s = new AST.TryCatchStatement(loc, _body, catches);
6623 if (finalbody)
6624 s = new AST.TryFinallyStatement(loc, s, finalbody);
6625 }
6626 break;
6627 }
6628 case TOK.throw_:
6629 {
6630 AST.Expression exp;
6631 nextToken();
6632 exp = parseExpression();
6633 check(TOK.semicolon, "`throw` statement");
6634 s = new AST.ThrowStatement(loc, exp);
6635 break;
6636 }
6637
6638 case TOK.asm_:
6639 s = parseAsm(false);
6640 break;
6641
6642 case TOK.import_:
6643 {
6644 /* https://issues.dlang.org/show_bug.cgi?id=16088
6645 *
6646 * At this point it can either be an
6647 * https://dlang.org/spec/grammar.html#ImportExpression
6648 * or an
6649 * https://dlang.org/spec/grammar.html#ImportDeclaration.
6650 * See if the next token after `import` is a `(`; if so,
6651 * then it is an import expression.
6652 */
6653 if (peekNext() == TOK.leftParenthesis)
6654 {
6655 AST.Expression e = parseExpression();
6656 check(TOK.semicolon, "`import` Expression");
6657 s = new AST.ExpStatement(loc, e);
6658 }
6659 else
6660 {
6661 AST.Dsymbols* imports = parseImport();
6662 s = new AST.ImportStatement(loc, imports);
6663 if (flags & ParseStatementFlags.scope_)
6664 s = new AST.ScopeStatement(loc, s, token.loc);
6665 }
6666 break;
6667 }
6668 case TOK.template_:
6669 {
6670 AST.Dsymbol d = parseTemplateDeclaration();
6671 s = new AST.ExpStatement(loc, d);
6672 break;
6673 }
6674 default:
6675 error("found `%s` instead of statement", token.toChars());
6676 goto Lerror;
6677
6678 Lerror:
6679 while (token.value != TOK.rightCurly && token.value != TOK.semicolon && token.value != TOK.endOfFile)
6680 nextToken();
6681 if (token.value == TOK.semicolon)
6682 nextToken();
6683 s = new AST.ErrorStatement;
6684 break;
6685 }
6686 if (pEndloc)
6687 *pEndloc = prevloc;
6688 return s;
6689 }
6690
6691
6692 private AST.ExpInitializer parseExpInitializer(Loc loc)
6693 {
6694 auto ae = parseAssignExp();
6695 return new AST.ExpInitializer(loc, ae);
6696 }
6697
6698 private AST.Initializer parseStructInitializer(Loc loc)
6699 {
6700 /* Scan ahead to discern between a struct initializer and
6701 * parameterless function literal.
6702 *
6703 * We'll scan the topmost curly bracket level for statement-related
6704 * tokens, thereby ruling out a struct initializer. (A struct
6705 * initializer which itself contains function literals may have
6706 * statements at nested curly bracket levels.)
6707 *
6708 * It's important that this function literal check not be
6709 * pendantic, otherwise a function having the slightest syntax
6710 * error would emit confusing errors when we proceed to parse it
6711 * as a struct initializer.
6712 *
6713 * The following two ambiguous cases will be treated as a struct
6714 * initializer (best we can do without type info):
6715 * {}
6716 * {{statements...}} - i.e. it could be struct initializer
6717 * with one function literal, or function literal having an
6718 * extra level of curly brackets
6719 * If a function literal is intended in these cases (unlikely),
6720 * source can use a more explicit function literal syntax
6721 * (e.g. prefix with "()" for empty parameter list).
6722 */
6723 int braces = 1;
6724 int parens = 0;
6725 for (auto t = peek(&token); 1; t = peek(t))
6726 {
6727 switch (t.value)
6728 {
6729 case TOK.leftParenthesis:
6730 parens++;
6731 continue;
6732 case TOK.rightParenthesis:
6733 parens--;
6734 continue;
6735 // https://issues.dlang.org/show_bug.cgi?id=21163
6736 // lambda params can have the `scope` storage class, e.g
6737 // `S s = { (scope Type Id){} }`
6738 case TOK.scope_:
6739 if (!parens) goto case;
6740 continue;
6741 /* Look for a semicolon or keyword of statements which don't
6742 * require a semicolon (typically containing BlockStatement).
6743 * Tokens like "else", "catch", etc. are omitted where the
6744 * leading token of the statement is sufficient.
6745 */
6746 case TOK.asm_:
6747 case TOK.class_:
6748 case TOK.debug_:
6749 case TOK.enum_:
6750 case TOK.if_:
6751 case TOK.interface_:
6752 case TOK.pragma_:
6753 case TOK.semicolon:
6754 case TOK.struct_:
6755 case TOK.switch_:
6756 case TOK.synchronized_:
6757 case TOK.try_:
6758 case TOK.union_:
6759 case TOK.version_:
6760 case TOK.while_:
6761 case TOK.with_:
6762 if (braces == 1)
6763 return parseExpInitializer(loc);
6764 continue;
6765
6766 case TOK.leftCurly:
6767 braces++;
6768 continue;
6769
6770 case TOK.rightCurly:
6771 if (--braces == 0)
6772 break;
6773 continue;
6774
6775 case TOK.endOfFile:
6776 break;
6777
6778 default:
6779 continue;
6780 }
6781 break;
6782 }
6783
6784 auto _is = new AST.StructInitializer(loc);
6785 bool commaExpected = false;
6786 nextToken();
6787 while (1)
6788 {
6789 switch (token.value)
6790 {
6791 case TOK.identifier:
6792 {
6793 if (commaExpected)
6794 error("comma expected separating field initializers");
6795 const t = peek(&token);
6796 Identifier id;
6797 if (t.value == TOK.colon)
6798 {
6799 id = token.ident;
6800 nextToken();
6801 nextToken(); // skip over ':'
6802 }
6803 auto value = parseInitializer();
6804 _is.addInit(id, value);
6805 commaExpected = true;
6806 continue;
6807 }
6808 case TOK.comma:
6809 if (!commaExpected)
6810 error("expression expected, not `,`");
6811 nextToken();
6812 commaExpected = false;
6813 continue;
6814
6815 case TOK.rightCurly: // allow trailing comma's
6816 nextToken();
6817 break;
6818
6819 case TOK.endOfFile:
6820 error("found end of file instead of initializer");
6821 break;
6822
6823 default:
6824 if (commaExpected)
6825 error("comma expected separating field initializers");
6826 const t = peek(&token);
6827 if (t.value == TOK.colon)
6828 {
6829 error("incorrect syntax for associative array, expected `[]`, found `{}`");
6830 while (token.value != TOK.rightCurly && token.value != TOK.endOfFile)
6831 {
6832 nextToken();
6833 }
6834 if (token.value == TOK.rightCurly)
6835 {
6836 nextToken();
6837 }
6838 break;
6839 }
6840 auto value = parseInitializer();
6841 _is.addInit(null, value);
6842 commaExpected = true;
6843 continue;
6844 }
6845 break;
6846 }
6847 return _is;
6848
6849 }
6850
6851 /*****************************************
6852 * Parse initializer for variable declaration.
6853 */
6854 private AST.Initializer parseInitializer()
6855 {
6856 const loc = token.loc;
6857
6858 switch (token.value)
6859 {
6860 case TOK.leftCurly:
6861 return parseStructInitializer(loc);
6862
6863 case TOK.leftBracket:
6864 /* Scan ahead to see if it is an array initializer or
6865 * an expression.
6866 * If it ends with a ';' ',' or ']', it is an array initializer.
6867 */
6868 int brackets = 1;
6869 for (auto t = peek(&token); 1; t = peek(t))
6870 {
6871 switch (t.value)
6872 {
6873 case TOK.leftBracket:
6874 brackets++;
6875 continue;
6876
6877 case TOK.rightBracket:
6878 if (--brackets == 0)
6879 {
6880 t = peek(t);
6881 if (t.value != TOK.semicolon && t.value != TOK.comma && t.value != TOK.rightBracket && t.value != TOK.rightCurly)
6882 return parseExpInitializer(loc);
6883 break;
6884 }
6885 continue;
6886
6887 case TOK.endOfFile:
6888 break;
6889
6890 default:
6891 continue;
6892 }
6893 break;
6894 }
6895
6896 auto ia = new AST.ArrayInitializer(loc);
6897 bool commaExpected = false;
6898
6899 nextToken();
6900 while (1)
6901 {
6902 switch (token.value)
6903 {
6904 default:
6905 if (commaExpected)
6906 {
6907 error("comma expected separating array initializers, not `%s`", token.toChars());
6908 nextToken();
6909 break;
6910 }
6911 auto e = parseAssignExp();
6912 if (!e)
6913 break;
6914
6915 AST.Initializer value;
6916 if (token.value == TOK.colon)
6917 {
6918 nextToken();
6919 value = parseInitializer();
6920 }
6921 else
6922 {
6923 value = new AST.ExpInitializer(e.loc, e);
6924 e = null;
6925 }
6926 ia.addInit(e, value);
6927 commaExpected = true;
6928 continue;
6929
6930 case TOK.leftCurly:
6931 case TOK.leftBracket:
6932 if (commaExpected)
6933 error("comma expected separating array initializers, not `%s`", token.toChars());
6934 auto value = parseInitializer();
6935 AST.Expression e;
6936
6937 if (token.value == TOK.colon)
6938 {
6939 nextToken();
6940 if (auto ei = value.isExpInitializer())
6941 {
6942 e = ei.exp;
6943 value = parseInitializer();
6944 }
6945 else
6946 error("initializer expression expected following colon, not `%s`", token.toChars());
6947 }
6948 ia.addInit(e, value);
6949 commaExpected = true;
6950 continue;
6951
6952 case TOK.comma:
6953 if (!commaExpected)
6954 error("expression expected, not `,`");
6955 nextToken();
6956 commaExpected = false;
6957 continue;
6958
6959 case TOK.rightBracket: // allow trailing comma's
6960 nextToken();
6961 break;
6962
6963 case TOK.endOfFile:
6964 error("found `%s` instead of array initializer", token.toChars());
6965 break;
6966 }
6967 break;
6968 }
6969 return ia;
6970
6971 case TOK.void_:
6972 const tv = peekNext();
6973 if (tv == TOK.semicolon || tv == TOK.comma)
6974 {
6975 nextToken();
6976 return new AST.VoidInitializer(loc);
6977 }
6978 return parseExpInitializer(loc);
6979
6980 default:
6981 return parseExpInitializer(loc);
6982 }
6983 }
6984
6985 /********************
6986 * Parse inline assembler block.
6987 * Enters with token on the `asm`.
6988 * https://dlang.org/spec/iasm.html
6989 *
6990 * AsmStatement:
6991 * asm FunctionAttributes(opt) { AsmInstructionListopt }
6992 * AsmInstructionList:
6993 * AsmInstruction ;
6994 * AsmInstruction ; AsmInstruction
6995 *
6996 * Params:
6997 * endOfLine = true if EOL means end of asm statement
6998 * Returns:
6999 * inline assembler block as a Statement
7000 */
7001 AST.Statement parseAsm(bool endOfLine)
7002 {
7003 // Parse the asm block into a sequence of AsmStatements,
7004 // each AsmStatement is one instruction.
7005 // Separate out labels.
7006 // Defer parsing of AsmStatements until semantic processing.
7007
7008 const loc = token.loc;
7009 Loc labelloc;
7010
7011 nextToken();
7012 STC stc = parsePostfix(STC.none, null); // optional FunctionAttributes
7013 if (stc & (STC.const_ | STC.immutable_ | STC.shared_ | STC.wild))
7014 error("`const`/`immutable`/`shared`/`inout` attributes are not allowed on `asm` blocks");
7015
7016 check(TOK.leftCurly);
7017 Token* toklist = null;
7018 Token** ptoklist = &toklist;
7019 Identifier label = null;
7020 auto statements = new AST.Statements();
7021 size_t nestlevel = 0;
7022 while (1)
7023 {
7024 if (endOfLine)
7025 nextDefineLine();
7026 switch (token.value)
7027 {
7028 case TOK.identifier:
7029 if (!toklist)
7030 {
7031 // Look ahead to see if it is a label
7032 if (peekNext() == TOK.colon)
7033 {
7034 // It's a label
7035 label = token.ident;
7036 labelloc = token.loc;
7037 nextToken();
7038 nextToken();
7039 continue;
7040 }
7041 }
7042 goto default;
7043
7044 case TOK.leftCurly:
7045 ++nestlevel;
7046 goto default;
7047
7048 case TOK.rightCurly:
7049 if (nestlevel > 0)
7050 {
7051 --nestlevel;
7052 goto default;
7053 }
7054 if (toklist || label)
7055 {
7056 error("`asm` statements must end in `;`");
7057 }
7058 break;
7059
7060 case TOK.endOfLine:
7061 nextDefineLine();
7062 goto case;
7063
7064 case TOK.semicolon:
7065 if (nestlevel != 0)
7066 error("mismatched number of curly brackets");
7067
7068 if (toklist || label)
7069 {
7070 // Create AsmStatement from list of tokens we've saved
7071 AST.AsmStatement as = new AST.AsmStatement(token.loc, toklist);
7072 as.caseSensitive = !endOfLine;
7073 AST.Statement s = as;
7074 toklist = null;
7075 ptoklist = &toklist;
7076 if (label)
7077 {
7078 s = new AST.LabelStatement(labelloc, label, s);
7079 label = null;
7080 }
7081 statements.push(s);
7082 }
7083 nextToken();
7084 continue;
7085
7086 case TOK.endOfFile:
7087 /* { */
7088 error("matching `}` expected, not end of file");
7089 break;
7090
7091 case TOK.colonColon: // treat as two separate : tokens for iasmgcc
7092 *ptoklist = allocateToken();
7093 memcpy(*ptoklist, &token, Token.sizeof);
7094 (*ptoklist).value = TOK.colon;
7095 ptoklist = &(*ptoklist).next;
7096
7097 *ptoklist = allocateToken();
7098 memcpy(*ptoklist, &token, Token.sizeof);
7099 (*ptoklist).value = TOK.colon;
7100 ptoklist = &(*ptoklist).next;
7101
7102 *ptoklist = null;
7103 nextToken();
7104 continue;
7105
7106 default:
7107 *ptoklist = allocateToken();
7108 memcpy(*ptoklist, &token, Token.sizeof);
7109 ptoklist = &(*ptoklist).next;
7110 *ptoklist = null;
7111 nextToken();
7112 continue;
7113 }
7114 break;
7115 }
7116 nextToken();
7117 if (token.value == TOK.endOfLine)
7118 nextToken();
7119 auto s = new AST.CompoundAsmStatement(loc, statements, stc);
7120 return s;
7121 }
7122
7123 /**********************************
7124 * Issue error if the current token is not `value`,
7125 * advance to next token.
7126 * Params:
7127 * loc = location for error message
7128 * value = token value to compare with
7129 */
7130 void check(Loc loc, TOK value)
7131 {
7132 if (token.value != value)
7133 error(loc, "found `%s` when expecting `%s`", token.toChars(), Token.toChars(value));
7134 nextToken();
7135 }
7136
7137 /**********************************
7138 * Issue error if the current token is not `value`,
7139 * advance to next token.
7140 * Params:
7141 * value = token value to compare with
7142 */
7143 void check(TOK value)
7144 {
7145 check(token.loc, value);
7146 }
7147
7148 /**********************************
7149 * Issue error if the current token is not `value`,
7150 * advance to next token.
7151 * Params:
7152 * value = token value to compare with
7153 * string = for error message
7154 */
7155 void check(TOK value, const(char)* string)
7156 {
7157 if (token.value != value)
7158 error(token.loc, "found `%s` when expecting `%s` following %s", token.toChars(), Token.toChars(value), string);
7159 nextToken();
7160 }
7161
7162 private void checkParens(TOK value, AST.Expression e)
7163 {
7164 if (precedence[e.op] == PREC.rel && !e.parens)
7165 error(e.loc, "`%s` must be surrounded by parentheses when next to operator `%s`", e.toChars(), Token.toChars(value));
7166 }
7167
7168 ///
7169 enum NeedDeclaratorId
7170 {
7171 no, // Declarator part must have no identifier
7172 opt, // Declarator part identifier is optional
7173 must, // Declarator part must have identifier
7174 mustIfDstyle, // Declarator part must have identifier, but don't recognize old C-style syntax
7175 }
7176
7177 /************************************
7178 * Determine if the scanner is sitting on the start of a declaration.
7179 * Params:
7180 * t = current token of the scanner
7181 * needId = flag with additional requirements for a declaration
7182 * endtok = ending token
7183 * pt = will be set ending token (if not null)
7184 * Output:
7185 * true if the token `t` is a declaration, false otherwise
7186 */
7187 private bool isDeclaration(Token* t, NeedDeclaratorId needId, TOK endtok, Token** pt)
7188 {
7189 //printf("isDeclaration(needId = %d)\n", needId);
7190 int haveId = 0;
7191 int haveTpl = 0;
7192
7193 while (1)
7194 {
7195 if ((t.value == TOK.const_ || t.value == TOK.immutable_ || t.value == TOK.inout_ || t.value == TOK.shared_) && peek(t).value != TOK.leftParenthesis)
7196 {
7197 /* const type
7198 * immutable type
7199 * shared type
7200 * wild type
7201 */
7202 t = peek(t);
7203 continue;
7204 }
7205 break;
7206 }
7207
7208 if (!isBasicType(&t))
7209 {
7210 goto Lisnot;
7211 }
7212 if (!isDeclarator(&t, &haveId, &haveTpl, endtok, needId != NeedDeclaratorId.mustIfDstyle))
7213 goto Lisnot;
7214 // needed for `__traits(compiles, arr[0] = 0)`
7215 if (!haveId && t.value == TOK.assign)
7216 goto Lisnot;
7217 if ((needId == NeedDeclaratorId.no && !haveId) ||
7218 (needId == NeedDeclaratorId.opt) ||
7219 (needId == NeedDeclaratorId.must && haveId) ||
7220 (needId == NeedDeclaratorId.mustIfDstyle && haveId))
7221 {
7222 if (pt)
7223 *pt = t;
7224 goto Lis;
7225 }
7226 goto Lisnot;
7227
7228 Lis:
7229 //printf("\tis declaration, t = %s\n", t.toChars());
7230 return true;
7231
7232 Lisnot:
7233 //printf("\tis not declaration\n");
7234 return false;
7235 }
7236
7237 // pt = test token. If found, pt is set to the token after BasicType
7238 private bool isBasicType(Token** pt)
7239 {
7240 // This code parallels parseBasicType()
7241 Token* t = *pt;
7242 switch (t.value)
7243 {
7244 case TOK.wchar_:
7245 case TOK.dchar_:
7246 case TOK.bool_:
7247 case TOK.char_:
7248 case TOK.int8:
7249 case TOK.uns8:
7250 case TOK.int16:
7251 case TOK.uns16:
7252 case TOK.int32:
7253 case TOK.uns32:
7254 case TOK.int64:
7255 case TOK.uns64:
7256 case TOK.int128:
7257 case TOK.uns128:
7258 case TOK.float32:
7259 case TOK.float64:
7260 case TOK.float80:
7261 case TOK.imaginary32:
7262 case TOK.imaginary64:
7263 case TOK.imaginary80:
7264 case TOK.complex32:
7265 case TOK.complex64:
7266 case TOK.complex80:
7267 case TOK.void_:
7268 t = peek(t);
7269 break;
7270
7271 case TOK.identifier:
7272 L5:
7273 t = peek(t);
7274 if (t.value == TOK.not)
7275 {
7276 goto L4;
7277 }
7278 goto L3;
7279 while (1)
7280 {
7281 L2:
7282 t = peek(t);
7283 L3:
7284 if (t.value == TOK.dot)
7285 {
7286 Ldot:
7287 t = peek(t);
7288 if (t.value != TOK.identifier)
7289 goto Lfalse;
7290 t = peek(t);
7291 if (t.value != TOK.not)
7292 goto L3;
7293 L4:
7294 /* Seen a !
7295 * Look for:
7296 * !( args ), !identifier, etc.
7297 */
7298 t = peek(t);
7299 switch (t.value)
7300 {
7301 case TOK.identifier:
7302 goto L5;
7303
7304 case TOK.leftParenthesis:
7305 if (!skipParens(t, &t))
7306 goto Lfalse;
7307 goto L3;
7308
7309 case TOK.wchar_:
7310 case TOK.dchar_:
7311 case TOK.bool_:
7312 case TOK.char_:
7313 case TOK.int8:
7314 case TOK.uns8:
7315 case TOK.int16:
7316 case TOK.uns16:
7317 case TOK.int32:
7318 case TOK.uns32:
7319 case TOK.int64:
7320 case TOK.uns64:
7321 case TOK.int128:
7322 case TOK.uns128:
7323 case TOK.float32:
7324 case TOK.float64:
7325 case TOK.float80:
7326 case TOK.imaginary32:
7327 case TOK.imaginary64:
7328 case TOK.imaginary80:
7329 case TOK.complex32:
7330 case TOK.complex64:
7331 case TOK.complex80:
7332 case TOK.void_:
7333 case TOK.int32Literal:
7334 case TOK.uns32Literal:
7335 case TOK.int64Literal:
7336 case TOK.uns64Literal:
7337 case TOK.int128Literal:
7338 case TOK.uns128Literal:
7339 case TOK.float32Literal:
7340 case TOK.float64Literal:
7341 case TOK.float80Literal:
7342 case TOK.imaginary32Literal:
7343 case TOK.imaginary64Literal:
7344 case TOK.imaginary80Literal:
7345 case TOK.null_:
7346 case TOK.true_:
7347 case TOK.false_:
7348 case TOK.charLiteral:
7349 case TOK.wcharLiteral:
7350 case TOK.dcharLiteral:
7351 case TOK.string_:
7352 case TOK.interpolated:
7353 case TOK.hexadecimalString:
7354 case TOK.file:
7355 case TOK.fileFullPath:
7356 case TOK.line:
7357 case TOK.moduleString:
7358 case TOK.functionString:
7359 case TOK.prettyFunction:
7360 goto L2;
7361
7362 default:
7363 goto Lfalse;
7364 }
7365 }
7366 break;
7367 }
7368 break;
7369
7370 case TOK.dot:
7371 goto Ldot;
7372
7373 case TOK.typeof_:
7374 case TOK.vector:
7375 case TOK.mixin_:
7376 /* typeof(exp).identifier...
7377 */
7378 t = peek(t);
7379 if (!skipParens(t, &t))
7380 goto Lfalse;
7381 goto L3;
7382
7383 case TOK.traits:
7384 // __traits(getMember
7385 t = peek(t);
7386 if (t.value != TOK.leftParenthesis)
7387 goto Lfalse;
7388 auto lp = t;
7389 t = peek(t);
7390 if (t.value != TOK.identifier || t.ident != Id.getMember)
7391 goto Lfalse;
7392 if (!skipParens(lp, &lp))
7393 goto Lfalse;
7394 // we are in a lookup for decl VS statement
7395 // so we expect a declarator following __trait if it's a type.
7396 // other usages wont be ambiguous (alias, template instance, type qual, etc.)
7397 if (lp.value != TOK.identifier)
7398 goto Lfalse;
7399
7400 break;
7401
7402 case TOK.const_:
7403 case TOK.immutable_:
7404 case TOK.shared_:
7405 case TOK.inout_:
7406 // const(type) or immutable(type) or shared(type) or wild(type)
7407 t = peek(t);
7408 if (t.value != TOK.leftParenthesis)
7409 goto Lfalse;
7410 t = peek(t);
7411 if (!isDeclaration(t, NeedDeclaratorId.no, TOK.rightParenthesis, &t))
7412 {
7413 goto Lfalse;
7414 }
7415 t = peek(t);
7416 break;
7417
7418 default:
7419 goto Lfalse;
7420 }
7421 *pt = t;
7422 //printf("is\n");
7423 return true;
7424
7425 Lfalse:
7426 //printf("is not\n");
7427 return false;
7428 }
7429
7430 private bool isDeclarator(Token** pt, int* haveId, int* haveTpl, TOK endtok, bool allowAltSyntax = true)
7431 {
7432 // This code parallels parseDeclarator()
7433 Token* t = *pt;
7434 bool parens;
7435
7436 //printf("Parser::isDeclarator() %s\n", t.toChars());
7437 if (t.value == TOK.assign)
7438 return false;
7439
7440 while (1)
7441 {
7442 parens = false;
7443 switch (t.value)
7444 {
7445 case TOK.mul:
7446 //case TOK.and:
7447 t = peek(t);
7448 continue;
7449
7450 case TOK.leftBracket:
7451 t = peek(t);
7452 if (t.value == TOK.rightBracket)
7453 {
7454 t = peek(t);
7455 }
7456 else if (isDeclaration(t, NeedDeclaratorId.no, TOK.rightBracket, &t))
7457 {
7458 // It's an associative array declaration
7459 t = peek(t);
7460
7461 // ...[type].ident
7462 if (t.value == TOK.dot && peek(t).value == TOK.identifier)
7463 {
7464 t = peek(t);
7465 t = peek(t);
7466 }
7467 }
7468 else
7469 {
7470 // [ expression ]
7471 // [ expression .. expression ]
7472 if (!isExpression(&t))
7473 return false;
7474 if (t.value == TOK.slice)
7475 {
7476 t = peek(t);
7477 if (!isExpression(&t))
7478 return false;
7479 if (t.value != TOK.rightBracket)
7480 return false;
7481 t = peek(t);
7482 }
7483 else
7484 {
7485 if (t.value != TOK.rightBracket)
7486 return false;
7487 t = peek(t);
7488 // ...[index].ident
7489 if (t.value == TOK.dot && peek(t).value == TOK.identifier)
7490 {
7491 t = peek(t);
7492 t = peek(t);
7493 }
7494 }
7495 }
7496 continue;
7497
7498 case TOK.identifier:
7499 if (*haveId)
7500 return false;
7501 *haveId = true;
7502 t = peek(t);
7503 break;
7504
7505 case TOK.leftParenthesis:
7506 if (!allowAltSyntax)
7507 return false; // Do not recognize C-style declarations.
7508
7509 t = peek(t);
7510 if (t.value == TOK.rightParenthesis)
7511 return false; // () is not a declarator
7512
7513 /* Regard ( identifier ) as not a declarator
7514 * BUG: what about ( *identifier ) in
7515 * f(*p)(x);
7516 * where f is a class instance with overloaded () ?
7517 * Should we just disallow C-style function pointer declarations?
7518 */
7519 if (t.value == TOK.identifier)
7520 {
7521 Token* t2 = peek(t);
7522 if (t2.value == TOK.rightParenthesis)
7523 return false;
7524 }
7525
7526 if (!isDeclarator(&t, haveId, null, TOK.rightParenthesis))
7527 return false;
7528 t = peek(t);
7529 parens = true;
7530 break;
7531
7532 case TOK.delegate_:
7533 case TOK.function_:
7534 t = peek(t);
7535 if (!isParameters(&t))
7536 return false;
7537 skipAttributes(t, &t);
7538 continue;
7539
7540 default:
7541 break;
7542 }
7543 break;
7544 }
7545
7546 while (1)
7547 {
7548 switch (t.value)
7549 {
7550 static if (CARRAYDECL)
7551 {
7552 case TOK.leftBracket:
7553 parens = false;
7554 t = peek(t);
7555 if (t.value == TOK.rightBracket)
7556 {
7557 t = peek(t);
7558 }
7559 else if (isDeclaration(t, NeedDeclaratorId.no, TOK.rightBracket, &t))
7560 {
7561 // It's an associative array declaration
7562 t = peek(t);
7563 }
7564 else
7565 {
7566 // [ expression ]
7567 if (!isExpression(&t))
7568 return false;
7569 if (t.value != TOK.rightBracket)
7570 return false;
7571 t = peek(t);
7572 }
7573 continue;
7574 }
7575
7576 case TOK.leftParenthesis:
7577 parens = false;
7578 if (Token* tk = peekPastParen(t))
7579 {
7580 if (tk.value == TOK.leftParenthesis)
7581 {
7582 if (!haveTpl)
7583 return false;
7584 *haveTpl = 1;
7585 t = tk;
7586 }
7587 else if (tk.value == TOK.assign)
7588 {
7589 if (!haveTpl)
7590 return false;
7591 *haveTpl = 1;
7592 *pt = tk;
7593 return true;
7594 }
7595 }
7596 if (!isParameters(&t))
7597 return false;
7598 while (1)
7599 {
7600 switch (t.value)
7601 {
7602 case TOK.const_:
7603 case TOK.immutable_:
7604 case TOK.shared_:
7605 case TOK.inout_:
7606 case TOK.pure_:
7607 case TOK.nothrow_:
7608 case TOK.return_:
7609 case TOK.scope_:
7610 t = peek(t);
7611 continue;
7612
7613 case TOK.at:
7614 t = peek(t); // skip '@'
7615 t = peek(t); // skip identifier
7616 continue;
7617
7618 default:
7619 break;
7620 }
7621 break;
7622 }
7623 continue;
7624
7625 // Valid tokens that follow the start of a declaration
7626 case TOK.rightParenthesis:
7627 case TOK.rightBracket:
7628 case TOK.assign:
7629 case TOK.comma:
7630 case TOK.dotDotDot:
7631 case TOK.semicolon:
7632 case TOK.leftCurly:
7633 case TOK.in_:
7634 case TOK.out_:
7635 case TOK.do_:
7636 // The !parens is to disallow unnecessary parentheses
7637 if (!parens && (endtok == TOK.reserved || endtok == t.value))
7638 {
7639 *pt = t;
7640 return true;
7641 }
7642 return false;
7643
7644 // To recognize the shortened function declaration syntax
7645 case TOK.goesTo:
7646 /*
7647 1. https://issues.dlang.org/show_bug.cgi?id=24088
7648
7649 2. We need to make sure the would-be
7650 declarator has an identifier otherwise function literals
7651 are handled incorrectly. Some special treatment is required
7652 here, it turns out that a lot of code in the compiler relies
7653 on this mess (in the parser), i.e. having isDeclarator be more
7654 precise the parsing of other things go kaboom, so we do it in a
7655 separate case.
7656 */
7657 if (*haveId)
7658 goto case TOK.do_;
7659 goto default;
7660
7661 case TOK.identifier:
7662 if (t.ident == Id._body)
7663 {
7664 usageOfBodyKeyword();
7665 goto case TOK.do_;
7666 }
7667 goto default;
7668
7669 case TOK.if_:
7670 return haveTpl ? true : false;
7671
7672 // Used for mixin type parsing
7673 case TOK.endOfFile:
7674 if (endtok == TOK.endOfFile)
7675 goto case TOK.do_;
7676 return false;
7677
7678 default:
7679 return false;
7680 }
7681 }
7682 assert(0);
7683 }
7684
7685 private bool isParameters(Token** pt)
7686 {
7687 // This code parallels parseParameterList()
7688 Token* t = *pt;
7689
7690 //printf("isParameters()\n");
7691 if (t.value != TOK.leftParenthesis)
7692 return false;
7693
7694 t = peek(t);
7695 for (; 1; t = peek(t))
7696 {
7697 L1:
7698 switch (t.value)
7699 {
7700 case TOK.rightParenthesis:
7701 break;
7702
7703 case TOK.at:
7704 Token* pastAttr;
7705 if (skipAttributes(t, &pastAttr))
7706 {
7707 t = pastAttr;
7708 goto default;
7709 }
7710 break;
7711
7712 case TOK.dotDotDot:
7713 t = peek(t);
7714 break;
7715
7716 case TOK.in_:
7717 case TOK.out_:
7718 case TOK.ref_:
7719 case TOK.lazy_:
7720 case TOK.scope_:
7721 case TOK.final_:
7722 case TOK.auto_:
7723 case TOK.return_:
7724 continue;
7725
7726 case TOK.const_:
7727 case TOK.immutable_:
7728 case TOK.shared_:
7729 case TOK.inout_:
7730 t = peek(t);
7731 if (t.value == TOK.leftParenthesis)
7732 {
7733 t = peek(t);
7734 if (!isDeclaration(t, NeedDeclaratorId.no, TOK.rightParenthesis, &t))
7735 return false;
7736 t = peek(t); // skip past closing ')'
7737 goto L2;
7738 }
7739 goto L1;
7740
7741 default:
7742 {
7743 if (!isBasicType(&t))
7744 return false;
7745 L2:
7746 int tmp = false;
7747 if (t.value != TOK.dotDotDot && !isDeclarator(&t, &tmp, null, TOK.reserved))
7748 return false;
7749 if (t.value == TOK.assign)
7750 {
7751 t = peek(t);
7752 if (!isExpression(&t))
7753 return false;
7754 }
7755 if (t.value == TOK.dotDotDot)
7756 {
7757 t = peek(t);
7758 break;
7759 }
7760 }
7761 if (t.value == TOK.comma)
7762 {
7763 continue;
7764 }
7765 break;
7766 }
7767 break;
7768 }
7769 if (t.value != TOK.rightParenthesis)
7770 return false;
7771 t = peek(t);
7772 *pt = t;
7773 return true;
7774 }
7775
7776 private bool isExpression(Token** pt)
7777 {
7778 // This is supposed to determine if something is an expression.
7779 // What it actually does is scan until a closing right bracket
7780 // is found.
7781
7782 Token* t = *pt;
7783 int brnest = 0;
7784 int panest = 0;
7785 int curlynest = 0;
7786
7787 for (;; t = peek(t))
7788 {
7789 switch (t.value)
7790 {
7791 case TOK.leftBracket:
7792 brnest++;
7793 continue;
7794
7795 case TOK.rightBracket:
7796 if (--brnest >= 0)
7797 continue;
7798 break;
7799
7800 case TOK.leftParenthesis:
7801 panest++;
7802 continue;
7803
7804 case TOK.comma:
7805 if (brnest || panest)
7806 continue;
7807 break;
7808
7809 case TOK.rightParenthesis:
7810 if (--panest >= 0)
7811 continue;
7812 break;
7813
7814 case TOK.leftCurly:
7815 curlynest++;
7816 continue;
7817
7818 case TOK.rightCurly:
7819 if (--curlynest >= 0)
7820 continue;
7821 return false;
7822
7823 case TOK.slice:
7824 if (brnest)
7825 continue;
7826 break;
7827
7828 case TOK.semicolon:
7829 if (curlynest)
7830 continue;
7831 return false;
7832
7833 case TOK.endOfFile:
7834 return false;
7835
7836 default:
7837 continue;
7838 }
7839 break;
7840 }
7841
7842 *pt = t;
7843 return true;
7844 }
7845
7846 /*******************************************
7847 * Skip parentheses.
7848 * Params:
7849 * t = on opening $(LPAREN)
7850 * pt = *pt is set to token past '$(RPAREN)' on true
7851 * Returns:
7852 * true successful
7853 * false some parsing error
7854 */
7855 bool skipParens(Token* t, Token** pt)
7856 {
7857 if (t.value != TOK.leftParenthesis)
7858 return false;
7859
7860 int parens = 0;
7861
7862 while (1)
7863 {
7864 switch (t.value)
7865 {
7866 case TOK.leftParenthesis:
7867 parens++;
7868 break;
7869
7870 case TOK.rightParenthesis:
7871 parens--;
7872 if (parens < 0)
7873 goto Lfalse;
7874 if (parens == 0)
7875 goto Ldone;
7876 break;
7877
7878 case TOK.endOfFile:
7879 goto Lfalse;
7880
7881 default:
7882 break;
7883 }
7884 t = peek(t);
7885 }
7886 Ldone:
7887 if (pt)
7888 *pt = peek(t); // skip found rparen
7889 return true;
7890
7891 Lfalse:
7892 return false;
7893 }
7894
7895 private bool skipParensIf(Token* t, Token** pt)
7896 {
7897 if (t.value != TOK.leftParenthesis)
7898 {
7899 if (pt)
7900 *pt = t;
7901 return true;
7902 }
7903 return skipParens(t, pt);
7904 }
7905
7906 //returns true if the next value (after optional matching parens) is expected
7907 private bool hasOptionalParensThen(Token* t, TOK expected)
7908 {
7909 Token* tk;
7910 if (!skipParensIf(t, &tk))
7911 return false;
7912 return tk.value == expected;
7913 }
7914
7915 /*******************************************
7916 * Skip attributes.
7917 * Input:
7918 * t is on a candidate attribute
7919 * Output:
7920 * *pt is set to first non-attribute token on success
7921 * Returns:
7922 * true successful
7923 * false some parsing error
7924 */
7925 private bool skipAttributes(Token* t, Token** pt)
7926 {
7927 while (1)
7928 {
7929 switch (t.value)
7930 {
7931 case TOK.const_:
7932 case TOK.immutable_:
7933 case TOK.shared_:
7934 case TOK.inout_:
7935 case TOK.final_:
7936 case TOK.auto_:
7937 case TOK.scope_:
7938 case TOK.override_:
7939 case TOK.abstract_:
7940 case TOK.synchronized_:
7941 break;
7942
7943 case TOK.deprecated_:
7944 if (peek(t).value == TOK.leftParenthesis)
7945 {
7946 t = peek(t);
7947 if (!skipParens(t, &t))
7948 goto Lerror;
7949 // t is on the next of closing parenthesis
7950 continue;
7951 }
7952 break;
7953
7954 case TOK.nothrow_:
7955 case TOK.pure_:
7956 case TOK.ref_:
7957 case TOK.gshared:
7958 case TOK.return_:
7959 break;
7960
7961 case TOK.at:
7962 t = peek(t);
7963 if (t.value == TOK.identifier)
7964 {
7965 /* @identifier
7966 * @identifier!arg
7967 * @identifier!(arglist)
7968 * any of the above followed by (arglist)
7969 * @predefined_attribute
7970 */
7971 if (isBuiltinAtAttribute(t.ident))
7972 break;
7973 t = peek(t);
7974 if (t.value == TOK.not)
7975 {
7976 t = peek(t);
7977 if (t.value == TOK.leftParenthesis)
7978 {
7979 // @identifier!(arglist)
7980 if (!skipParens(t, &t))
7981 goto Lerror;
7982 // t is on the next of closing parenthesis
7983 }
7984 else
7985 {
7986 // @identifier!arg
7987 // Do low rent skipTemplateArgument
7988 if (t.value == TOK.vector)
7989 {
7990 // identifier!__vector(type)
7991 t = peek(t);
7992 if (!skipParens(t, &t))
7993 goto Lerror;
7994 }
7995 else
7996 t = peek(t);
7997 }
7998 }
7999 if (t.value == TOK.leftParenthesis)
8000 {
8001 if (!skipParens(t, &t))
8002 goto Lerror;
8003 // t is on the next of closing parenthesis
8004 continue;
8005 }
8006 continue;
8007 }
8008 if (t.value == TOK.leftParenthesis)
8009 {
8010 // @( ArgumentList )
8011 if (!skipParens(t, &t))
8012 goto Lerror;
8013 // t is on the next of closing parenthesis
8014 continue;
8015 }
8016 goto Lerror;
8017
8018 default:
8019 goto Ldone;
8020 }
8021 t = peek(t);
8022 }
8023 Ldone:
8024 if (pt)
8025 *pt = t;
8026 return true;
8027
8028 Lerror:
8029 return false;
8030 }
8031
8032 AST.Expression parseExpression()
8033 {
8034 auto loc = token.loc;
8035
8036 //printf("Parser::parseExpression() loc = %d\n", loc.linnum);
8037 auto e = parseAssignExp();
8038 while (token.value == TOK.comma)
8039 {
8040 nextToken();
8041 auto e2 = parseAssignExp();
8042 e = new AST.CommaExp(loc, e, e2, false);
8043 loc = token.loc;
8044 }
8045 return e;
8046 }
8047
8048 /********************************* Expression Parser ***************************/
8049
8050 AST.Expression parsePrimaryExp()
8051 {
8052 AST.Expression e;
8053 AST.Type t;
8054 Identifier id;
8055 const loc = token.loc;
8056
8057 //printf("parsePrimaryExp(): loc = %d\n", loc.linnum);
8058 switch (token.value)
8059 {
8060 case TOK.identifier:
8061 {
8062 if (peekNext() == TOK.arrow)
8063 {
8064 // skip `identifier ->`
8065 nextToken();
8066 nextToken();
8067 error("use `.` for member lookup, not `->`");
8068 goto Lerr;
8069 }
8070
8071 if (peekNext() == TOK.goesTo)
8072 goto case_delegate;
8073
8074 id = token.ident;
8075 nextToken();
8076 TOK save;
8077 if (token.value == TOK.not && (save = peekNext()) != TOK.is_ && save != TOK.in_)
8078 {
8079 // identifier!(template-argument-list)
8080 auto tempinst = new AST.TemplateInstance(loc, id, parseTemplateArguments());
8081 e = new AST.ScopeExp(loc, tempinst);
8082 }
8083 else
8084 e = new AST.IdentifierExp(loc, id);
8085 break;
8086 }
8087 case TOK.dollar:
8088 if (!inBrackets)
8089 error("`$` is valid only inside [] of index or slice");
8090 e = new AST.DollarExp(loc);
8091 nextToken();
8092 break;
8093
8094 case TOK.dot:
8095 // Signal global scope '.' operator with "" identifier
8096 e = new AST.IdentifierExp(loc, Id.empty);
8097 break;
8098
8099 case TOK.this_:
8100 e = new AST.ThisExp(loc);
8101 nextToken();
8102 break;
8103
8104 case TOK.super_:
8105 e = new AST.SuperExp(loc);
8106 nextToken();
8107 break;
8108
8109 case TOK.int32Literal:
8110 e = new AST.IntegerExp(loc, token.intvalue, AST.Type.tint32);
8111 nextToken();
8112 break;
8113
8114 case TOK.uns32Literal:
8115 e = new AST.IntegerExp(loc, token.unsvalue, AST.Type.tuns32);
8116 nextToken();
8117 break;
8118
8119 case TOK.int64Literal:
8120 e = new AST.IntegerExp(loc, token.intvalue, AST.Type.tint64);
8121 nextToken();
8122 break;
8123
8124 case TOK.uns64Literal:
8125 e = new AST.IntegerExp(loc, token.unsvalue, AST.Type.tuns64);
8126 nextToken();
8127 break;
8128
8129 case TOK.float32Literal:
8130 e = new AST.RealExp(loc, token.floatvalue, AST.Type.tfloat32);
8131 nextToken();
8132 break;
8133
8134 case TOK.float64Literal:
8135 e = new AST.RealExp(loc, token.floatvalue, AST.Type.tfloat64);
8136 nextToken();
8137 break;
8138
8139 case TOK.float80Literal:
8140 e = new AST.RealExp(loc, token.floatvalue, AST.Type.tfloat80);
8141 nextToken();
8142 break;
8143
8144 case TOK.imaginary32Literal:
8145 e = new AST.RealExp(loc, token.floatvalue, AST.Type.timaginary32);
8146 nextToken();
8147 break;
8148
8149 case TOK.imaginary64Literal:
8150 e = new AST.RealExp(loc, token.floatvalue, AST.Type.timaginary64);
8151 nextToken();
8152 break;
8153
8154 case TOK.imaginary80Literal:
8155 e = new AST.RealExp(loc, token.floatvalue, AST.Type.timaginary80);
8156 nextToken();
8157 break;
8158
8159 case TOK.null_:
8160 e = new AST.NullExp(loc);
8161 nextToken();
8162 break;
8163
8164 case TOK.file:
8165 e = new AST.FileInitExp(loc, EXP.file);
8166 nextToken();
8167 break;
8168 case TOK.fileFullPath:
8169 e = new AST.FileInitExp(loc, EXP.fileFullPath);
8170 nextToken();
8171 break;
8172
8173 case TOK.line:
8174 e = new AST.LineInitExp(loc);
8175 nextToken();
8176 break;
8177
8178 case TOK.moduleString:
8179 e = new AST.ModuleInitExp(loc);
8180 nextToken();
8181 break;
8182 case TOK.functionString:
8183 e = new AST.FuncInitExp(loc);
8184 nextToken();
8185 break;
8186
8187 case TOK.prettyFunction:
8188 e = new AST.PrettyFuncInitExp(loc);
8189 nextToken();
8190 break;
8191
8192 case TOK.true_:
8193 e = new AST.IntegerExp(loc, 1, AST.Type.tbool);
8194 nextToken();
8195 break;
8196
8197 case TOK.false_:
8198 e = new AST.IntegerExp(loc, 0, AST.Type.tbool);
8199 nextToken();
8200 break;
8201
8202 case TOK.charLiteral:
8203 e = new AST.IntegerExp(loc, token.unsvalue, AST.Type.tchar);
8204 nextToken();
8205 break;
8206
8207 case TOK.wcharLiteral:
8208 e = new AST.IntegerExp(loc, token.unsvalue, AST.Type.twchar);
8209 nextToken();
8210 break;
8211
8212 case TOK.dcharLiteral:
8213 e = new AST.IntegerExp(loc, token.unsvalue, AST.Type.tdchar);
8214 nextToken();
8215 break;
8216
8217 case TOK.interpolated:
8218 e = new AST.InterpExp(loc, token.interpolatedSet, token.postfix);
8219 nextToken();
8220 break;
8221
8222 case TOK.string_:
8223 case TOK.hexadecimalString:
8224 const bool hexString = token.value == TOK.hexadecimalString;
8225 {
8226 // cat adjacent strings
8227 auto s = token.ustring;
8228 auto len = token.len;
8229 auto postfix = token.postfix;
8230 while (1)
8231 {
8232 const prev = token;
8233 nextToken();
8234 if (token.value == TOK.string_ || token.value == TOK.hexadecimalString)
8235 {
8236 if (token.postfix)
8237 {
8238 if (token.postfix != postfix)
8239 error(token.loc, "mismatched string literal postfixes `'%c'` and `'%c'`", postfix, token.postfix);
8240 postfix = token.postfix;
8241 }
8242
8243 error("implicit string concatenation is error-prone and disallowed in D");
8244 eSink.errorSupplemental(token.loc, "Use the explicit syntax instead " ~
8245 "(concatenating literals is `@nogc`): %s ~ %s",
8246 prev.toChars(), token.toChars());
8247
8248 const len1 = len;
8249 const len2 = token.len;
8250 len = len1 + len2;
8251 auto s2 = cast(char*)mem.xmalloc_noscan(len * char.sizeof);
8252 memcpy(s2, s, len1 * char.sizeof);
8253 memcpy(s2 + len1, token.ustring, len2 * char.sizeof);
8254 s = s2;
8255 }
8256 else
8257 break;
8258 }
8259 e = new AST.StringExp(loc, s[0 .. len], len, 1, postfix);
8260 e.isStringExp().hexString = hexString;
8261 break;
8262 }
8263 case TOK.void_:
8264 t = AST.Type.tvoid;
8265 goto LabelX;
8266
8267 case TOK.int8:
8268 t = AST.Type.tint8;
8269 goto LabelX;
8270
8271 case TOK.uns8:
8272 t = AST.Type.tuns8;
8273 goto LabelX;
8274
8275 case TOK.int16:
8276 t = AST.Type.tint16;
8277 goto LabelX;
8278
8279 case TOK.uns16:
8280 t = AST.Type.tuns16;
8281 goto LabelX;
8282
8283 case TOK.int32:
8284 t = AST.Type.tint32;
8285 goto LabelX;
8286
8287 case TOK.uns32:
8288 t = AST.Type.tuns32;
8289 goto LabelX;
8290
8291 case TOK.int64:
8292 t = AST.Type.tint64;
8293 goto LabelX;
8294
8295 case TOK.uns64:
8296 t = AST.Type.tuns64;
8297 goto LabelX;
8298
8299 case TOK.int128:
8300 t = AST.Type.tint128;
8301 goto LabelX;
8302
8303 case TOK.uns128:
8304 t = AST.Type.tuns128;
8305 goto LabelX;
8306
8307 case TOK.float32:
8308 t = AST.Type.tfloat32;
8309 goto LabelX;
8310
8311 case TOK.float64:
8312 t = AST.Type.tfloat64;
8313 goto LabelX;
8314
8315 case TOK.float80:
8316 t = AST.Type.tfloat80;
8317 goto LabelX;
8318
8319 case TOK.imaginary32:
8320 t = AST.Type.timaginary32;
8321 goto LabelX;
8322
8323 case TOK.imaginary64:
8324 t = AST.Type.timaginary64;
8325 goto LabelX;
8326
8327 case TOK.imaginary80:
8328 t = AST.Type.timaginary80;
8329 goto LabelX;
8330
8331 case TOK.complex32:
8332 t = AST.Type.tcomplex32;
8333 goto LabelX;
8334
8335 case TOK.complex64:
8336 t = AST.Type.tcomplex64;
8337 goto LabelX;
8338
8339 case TOK.complex80:
8340 t = AST.Type.tcomplex80;
8341 goto LabelX;
8342
8343 case TOK.bool_:
8344 t = AST.Type.tbool;
8345 goto LabelX;
8346
8347 case TOK.char_:
8348 t = AST.Type.tchar;
8349 goto LabelX;
8350
8351 case TOK.wchar_:
8352 t = AST.Type.twchar;
8353 goto LabelX;
8354
8355 case TOK.dchar_:
8356 t = AST.Type.tdchar;
8357 goto LabelX;
8358 LabelX:
8359 const next = peekNext();
8360 if (next != TOK.leftParenthesis && next != TOK.dot)
8361 {
8362 // defer error for better diagnostics
8363 e = new AST.TypeExp(loc, parseType);
8364 break;
8365 }
8366 nextToken();
8367 if (token.value == TOK.leftParenthesis)
8368 {
8369 e = new AST.TypeExp(loc, t);
8370 e = new AST.CallExp(loc, e, parseArguments());
8371 break;
8372 }
8373 check(TOK.dot);
8374 if (token.value != TOK.identifier)
8375 {
8376 error(token.loc, "found `%s` when expecting identifier following `%s`.", token.toChars(), t.toChars());
8377 goto Lerr;
8378 }
8379 e = new AST.DotIdExp(loc, new AST.TypeExp(loc, t), token.ident);
8380 nextToken();
8381 break;
8382
8383 case TOK.typeof_:
8384 {
8385 t = parseTypeof();
8386 e = new AST.TypeExp(loc, t);
8387 break;
8388 }
8389 case TOK.vector:
8390 {
8391 t = parseVector();
8392 e = new AST.TypeExp(loc, t);
8393 break;
8394 }
8395 case TOK.typeid_:
8396 {
8397 nextToken();
8398 check(TOK.leftParenthesis, "`typeid`");
8399 RootObject o = parseTypeOrAssignExp();
8400 check(TOK.rightParenthesis);
8401 e = new AST.TypeidExp(loc, o);
8402 break;
8403 }
8404 case TOK.rvalue:
8405 {
8406 nextToken();
8407 check(TOK.leftParenthesis, "`__rvalue`");
8408 e = parseAssignExp();
8409 e.rvalue = true;
8410 check(TOK.rightParenthesis);
8411 break;
8412 }
8413 case TOK.traits:
8414 {
8415 /* __traits(identifier, args...)
8416 */
8417 Identifier ident;
8418 AST.Objects* args = null;
8419
8420 nextToken();
8421 check(TOK.leftParenthesis);
8422 if (token.value != TOK.identifier)
8423 {
8424 error("`__traits(identifier, args...)` expected");
8425 goto Lerr;
8426 }
8427 ident = token.ident;
8428 nextToken();
8429 if (token.value == TOK.comma)
8430 args = parseTemplateArgumentList(); // __traits(identifier, args...)
8431 else
8432 check(TOK.rightParenthesis); // __traits(identifier)
8433
8434 e = new AST.TraitsExp(loc, ident, args);
8435 break;
8436 }
8437 case TOK.is_:
8438 {
8439 AST.Type targ;
8440 Identifier ident = null;
8441 AST.Type tspec = null;
8442 TOK tok = TOK.reserved;
8443 TOK tok2 = TOK.reserved;
8444 AST.TemplateParameters* tpl = null;
8445
8446 nextToken();
8447 if (token.value != TOK.leftParenthesis)
8448 {
8449 error("expected `(` following `is`, not `%s`", token.toChars());
8450 goto Lerr;
8451 }
8452 else
8453 {
8454 nextToken();
8455 if (token.value == TOK.identifier && peekNext() == TOK.leftParenthesis)
8456 {
8457 error(loc, "unexpected `(` after `%s`, inside `is` expression. Try enclosing the contents of `is` with a `typeof` expression", token.toChars());
8458 nextToken();
8459 Token* tempTok = peekPastParen(&token);
8460 memcpy(&token, tempTok, Token.sizeof);
8461 goto Lerr;
8462 }
8463 targ = parseType(&ident);
8464 if (token.value == TOK.colon || token.value == TOK.equal)
8465 {
8466 tok = token.value;
8467 nextToken();
8468 if (tok == TOK.equal && (token.value == TOK.struct_ || token.value == TOK.union_
8469 || token.value == TOK.class_ || token.value == TOK.super_ || token.value == TOK.enum_
8470 || token.value == TOK.interface_ || token.value == TOK.package_ || token.value == TOK.module_
8471 || token.value == TOK.argumentTypes || token.value == TOK.parameters
8472 || token.value == TOK.const_ && peekNext() == TOK.rightParenthesis
8473 || token.value == TOK.immutable_ && peekNext() == TOK.rightParenthesis
8474 || token.value == TOK.shared_ && peekNext() == TOK.rightParenthesis
8475 || token.value == TOK.inout_ && peekNext() == TOK.rightParenthesis || token.value == TOK.function_
8476 || token.value == TOK.delegate_ || token.value == TOK.return_
8477 || (token.value == TOK.vector && peekNext() == TOK.rightParenthesis)))
8478 {
8479 tok2 = token.value;
8480 nextToken();
8481 }
8482 else
8483 {
8484 tspec = parseType();
8485 }
8486 }
8487 if (tspec)
8488 {
8489 if (token.value == TOK.comma)
8490 tpl = parseTemplateParameterList(1);
8491 else
8492 {
8493 tpl = new AST.TemplateParameters();
8494 check(TOK.rightParenthesis);
8495 }
8496 }
8497 else
8498 check(TOK.rightParenthesis);
8499 }
8500 e = new AST.IsExp(loc, targ, ident, tok, tspec, tok2, tpl);
8501 break;
8502 }
8503 case TOK.assert_:
8504 {
8505 // https://dlang.org/spec/expression.html#assert_expressions
8506 AST.Expression msg = null;
8507
8508 nextToken();
8509 check(TOK.leftParenthesis, "`assert`");
8510 e = parseAssignExp();
8511 if (token.value == TOK.comma)
8512 {
8513 nextToken();
8514 if (token.value != TOK.rightParenthesis)
8515 {
8516 msg = parseAssignExp();
8517 if (token.value == TOK.comma)
8518 nextToken();
8519 }
8520 }
8521 check(TOK.rightParenthesis);
8522 e = new AST.AssertExp(loc, e, msg);
8523 break;
8524 }
8525 case TOK.mixin_:
8526 {
8527 // https://dlang.org/spec/expression.html#mixin_expressions
8528 nextToken();
8529 if (token.value != TOK.leftParenthesis)
8530 error(token.loc, "found `%s` when expecting `%s` following `mixin`", token.toChars(), Token.toChars(TOK.leftParenthesis));
8531 auto exps = parseArguments();
8532 e = new AST.MixinExp(loc, exps);
8533 break;
8534 }
8535 case TOK.import_:
8536 {
8537 nextToken();
8538 check(TOK.leftParenthesis, "`import`");
8539 e = parseAssignExp();
8540 check(TOK.rightParenthesis);
8541 e = new AST.ImportExp(loc, e);
8542 break;
8543 }
8544 case TOK.new_:
8545 e = parseNewExp(null);
8546 break;
8547
8548 case TOK.auto_:
8549 {
8550 if (peekNext() == TOK.ref_ && peekNext2() == TOK.leftParenthesis)
8551 {
8552 Token* tk = peekPastParen(peek(peek(&token)));
8553 if (skipAttributes(tk, &tk) && (tk.value == TOK.goesTo || tk.value == TOK.leftCurly))
8554 {
8555 // auto ref (arguments) => expression
8556 // auto ref (arguments) { statements... }
8557 goto case_delegate;
8558 }
8559 }
8560 nextToken();
8561 error("found `%s` when expecting `ref` and function literal following `auto`", token.toChars());
8562 goto Lerr;
8563 }
8564 case TOK.ref_:
8565 {
8566 if (peekNext() == TOK.leftParenthesis)
8567 {
8568 Token* tk = peekPastParen(peek(&token));
8569 if (skipAttributes(tk, &tk) && (tk.value == TOK.goesTo || tk.value == TOK.leftCurly))
8570 {
8571 // ref (arguments) => expression
8572 // ref (arguments) { statements... }
8573 goto case_delegate;
8574 }
8575 }
8576 nextToken();
8577 error("found `%s` when expecting function literal following `ref`", token.toChars());
8578 goto Lerr;
8579 }
8580 case TOK.leftParenthesis:
8581 {
8582 Token* tk = peekPastParen(&token);
8583 if (skipAttributes(tk, &tk) && (tk.value == TOK.goesTo || tk.value == TOK.leftCurly))
8584 {
8585 // (arguments) => expression
8586 // (arguments) { statements... }
8587 goto case_delegate;
8588 }
8589
8590 // ( expression )
8591 nextToken();
8592 e = parseExpression();
8593 e.parens = true;
8594 check(loc, TOK.rightParenthesis);
8595 break;
8596 }
8597 case TOK.leftBracket:
8598 {
8599 /* Parse array literals and associative array literals:
8600 * [ value, value, value ... ]
8601 * [ key:value, key:value, key:value ... ]
8602 */
8603 auto values = new AST.Expressions();
8604 AST.Expressions* keys = null;
8605
8606 nextToken();
8607 while (token.value != TOK.rightBracket && token.value != TOK.endOfFile)
8608 {
8609 e = parseAssignExp();
8610 if (token.value == TOK.colon && (keys || values.length == 0))
8611 {
8612 nextToken();
8613 if (!keys)
8614 keys = new AST.Expressions();
8615 keys.push(e);
8616 e = parseAssignExp();
8617 }
8618 else if (keys)
8619 {
8620 error("`key:value` expected for associative array literal");
8621 keys = null;
8622 }
8623 values.push(e);
8624 if (token.value == TOK.rightBracket)
8625 break;
8626 check(TOK.comma);
8627 }
8628 check(loc, TOK.rightBracket);
8629
8630 if (keys)
8631 e = new AST.AssocArrayLiteralExp(loc, keys, values);
8632 else
8633 e = new AST.ArrayLiteralExp(loc, null, values);
8634 break;
8635 }
8636 case TOK.leftCurly:
8637 case TOK.function_:
8638 case TOK.delegate_:
8639 case_delegate:
8640 {
8641 AST.Dsymbol s = parseFunctionLiteral();
8642 e = new AST.FuncExp(loc, s);
8643 break;
8644 }
8645
8646 default:
8647 error("expression expected, not `%s`", token.toChars());
8648 Lerr:
8649 // Anything for e, as long as it's not NULL
8650 e = AST.ErrorExp.get();
8651 nextToken();
8652 break;
8653 }
8654 return e;
8655 }
8656
8657 private AST.Expression parseUnaryExp()
8658 {
8659 AST.Expression e;
8660 const loc = token.loc;
8661
8662 switch (token.value)
8663 {
8664 case TOK.and:
8665 nextToken();
8666 e = parseUnaryExp();
8667 e = new AST.AddrExp(loc, e);
8668 break;
8669
8670 case TOK.plusPlus:
8671 nextToken();
8672 e = parseUnaryExp();
8673 //e = new AddAssignExp(loc, e, new IntegerExp(loc, 1, Type::tint32));
8674 e = new AST.PreExp(EXP.prePlusPlus, loc, e);
8675 break;
8676
8677 case TOK.minusMinus:
8678 nextToken();
8679 e = parseUnaryExp();
8680 //e = new MinAssignExp(loc, e, new IntegerExp(loc, 1, Type::tint32));
8681 e = new AST.PreExp(EXP.preMinusMinus, loc, e);
8682 break;
8683
8684 case TOK.mul:
8685 nextToken();
8686 e = parseUnaryExp();
8687 e = new AST.PtrExp(loc, e);
8688 break;
8689
8690 case TOK.min:
8691 nextToken();
8692 e = parseUnaryExp();
8693 e = new AST.NegExp(loc, e);
8694 break;
8695
8696 case TOK.add:
8697 nextToken();
8698 e = parseUnaryExp();
8699 e = new AST.UAddExp(loc, e);
8700 break;
8701
8702 case TOK.not:
8703 nextToken();
8704 e = parseUnaryExp();
8705 e = new AST.NotExp(loc, e);
8706 break;
8707
8708 case TOK.tilde:
8709 nextToken();
8710 e = parseUnaryExp();
8711 e = new AST.ComExp(loc, e);
8712 break;
8713
8714 case TOK.cast_: // cast(type) expression
8715 {
8716 nextToken();
8717 check(TOK.leftParenthesis);
8718 /* Look for cast(), cast(const), cast(immutable),
8719 * cast(shared), cast(shared const), cast(wild), cast(shared wild)
8720 */
8721 ubyte m = 0;
8722 while (1)
8723 {
8724 switch (token.value)
8725 {
8726 case TOK.const_:
8727 if (peekNext() == TOK.leftParenthesis)
8728 break; // const as type constructor
8729 m |= MODFlags.const_; // const as storage class
8730 nextToken();
8731 continue;
8732
8733 case TOK.immutable_:
8734 if (peekNext() == TOK.leftParenthesis)
8735 break;
8736 m |= MODFlags.immutable_;
8737 nextToken();
8738 continue;
8739
8740 case TOK.shared_:
8741 if (peekNext() == TOK.leftParenthesis)
8742 break;
8743 m |= MODFlags.shared_;
8744 nextToken();
8745 continue;
8746
8747 case TOK.inout_:
8748 if (peekNext() == TOK.leftParenthesis)
8749 break;
8750 m |= MODFlags.wild;
8751 nextToken();
8752 continue;
8753
8754 default:
8755 break;
8756 }
8757 break;
8758 }
8759 if (token.value == TOK.rightParenthesis)
8760 {
8761 nextToken();
8762 e = parseUnaryExp();
8763 e = new AST.CastExp(loc, e, m);
8764 }
8765 else
8766 {
8767 AST.Type t = parseType(); // cast( type )
8768 t = t.addSTC(AST.ModToStc(m)); // cast( const type )
8769 check(TOK.rightParenthesis);
8770 e = parseUnaryExp();
8771 e = new AST.CastExp(loc, e, t);
8772 }
8773 break;
8774 }
8775 case TOK.inout_:
8776 case TOK.shared_:
8777 case TOK.const_:
8778 case TOK.immutable_: // immutable(type)(arguments) / immutable(type).init
8779 {
8780 STC stc = parseTypeCtor();
8781
8782 AST.Type t = parseBasicType();
8783 t = t.addSTC(stc);
8784
8785 if (stc == 0 && token.value == TOK.dot)
8786 {
8787 nextToken();
8788 if (token.value != TOK.identifier)
8789 {
8790 error("identifier expected following `%s.`, not `%s`",
8791 t.toChars(), token.toChars());
8792 return AST.ErrorExp.get();
8793 }
8794 e = new AST.DotIdExp(loc, new AST.TypeExp(loc, t), token.ident);
8795 nextToken();
8796 e = parsePostExp(e);
8797 }
8798 else
8799 {
8800 e = new AST.TypeExp(loc, t);
8801 if (token.value != TOK.leftParenthesis)
8802 {
8803 error("`(arguments)` expected following `%s`, not `%s`",
8804 t.toChars(), token.toChars());
8805 return e;
8806 }
8807 e = new AST.CallExp(loc, e, parseArguments());
8808 }
8809 break;
8810 }
8811 case TOK.leftParenthesis:
8812 {
8813 auto tk = peek(&token);
8814 static if (CCASTSYNTAX)
8815 {
8816 // If cast
8817 if (isDeclaration(tk, NeedDeclaratorId.no, TOK.rightParenthesis, &tk))
8818 {
8819 tk = peek(tk); // skip over right parenthesis
8820 switch (tk.value)
8821 {
8822 case TOK.not:
8823 tk = peek(tk);
8824 if (tk.value == TOK.is_ || tk.value == TOK.in_) // !is or !in
8825 break;
8826 goto case;
8827
8828 case TOK.dot:
8829 case TOK.plusPlus:
8830 case TOK.minusMinus:
8831 case TOK.new_:
8832 case TOK.leftParenthesis:
8833 case TOK.identifier:
8834 case TOK.this_:
8835 case TOK.super_:
8836 case TOK.int32Literal:
8837 case TOK.uns32Literal:
8838 case TOK.int64Literal:
8839 case TOK.uns64Literal:
8840 case TOK.int128Literal:
8841 case TOK.uns128Literal:
8842 case TOK.float32Literal:
8843 case TOK.float64Literal:
8844 case TOK.float80Literal:
8845 case TOK.imaginary32Literal:
8846 case TOK.imaginary64Literal:
8847 case TOK.imaginary80Literal:
8848 case TOK.null_:
8849 case TOK.true_:
8850 case TOK.false_:
8851 case TOK.charLiteral:
8852 case TOK.wcharLiteral:
8853 case TOK.dcharLiteral:
8854 case TOK.string_:
8855 case TOK.interpolated:
8856 case TOK.function_:
8857 case TOK.delegate_:
8858 case TOK.typeof_:
8859 case TOK.traits:
8860 case TOK.vector:
8861 case TOK.file:
8862 case TOK.fileFullPath:
8863 case TOK.line:
8864 case TOK.moduleString:
8865 case TOK.functionString:
8866 case TOK.prettyFunction:
8867 case TOK.wchar_:
8868 case TOK.dchar_:
8869 case TOK.bool_:
8870 case TOK.char_:
8871 case TOK.int8:
8872 case TOK.uns8:
8873 case TOK.int16:
8874 case TOK.uns16:
8875 case TOK.int32:
8876 case TOK.uns32:
8877 case TOK.int64:
8878 case TOK.uns64:
8879 case TOK.int128:
8880 case TOK.uns128:
8881 case TOK.float32:
8882 case TOK.float64:
8883 case TOK.float80:
8884 case TOK.imaginary32:
8885 case TOK.imaginary64:
8886 case TOK.imaginary80:
8887 case TOK.complex32:
8888 case TOK.complex64:
8889 case TOK.complex80:
8890 case TOK.void_:
8891 {
8892 // (type) una_exp
8893 nextToken();
8894 // Note: `t` may be an expression that looks like a type
8895 auto t = parseType();
8896 check(TOK.rightParenthesis);
8897
8898 // if .identifier
8899 // or .identifier!( ... )
8900 if (token.value == TOK.dot)
8901 {
8902 if (peekNext() != TOK.identifier && peekNext() != TOK.new_)
8903 {
8904 error("identifier or new keyword expected following `(...)`.");
8905 nextToken();
8906 return AST.ErrorExp.get();
8907 }
8908 e = new AST.TypeExp(loc, t);
8909 e.parens = true;
8910 e = parsePostExp(e);
8911 }
8912 else if (token.value == TOK.leftParenthesis ||
8913 token.value == TOK.plusPlus || token.value == TOK.minusMinus)
8914 {
8915 // (type)(expr)
8916 // (callable)(args)
8917 // (expr)++
8918 auto te = new AST.TypeExp(loc, t);
8919 te.parens = true;
8920 e = parsePostExp(te);
8921 }
8922 else
8923 {
8924 e = parseUnaryExp();
8925 e = new AST.CastExp(loc, e, t);
8926 error(loc, "C style cast illegal, use `%s`", e.toChars());
8927 }
8928 return e;
8929 }
8930 default:
8931 break;
8932 }
8933 }
8934 }
8935 e = parsePrimaryExp();
8936 e = parsePostExp(e);
8937 break;
8938 }
8939 case TOK.throw_:
8940 {
8941 nextToken();
8942 // Deviation from the DIP:
8943 // Parse AssignExpression instead of Expression to avoid conflicts for comma
8944 // separated lists, e.g. function arguments
8945 AST.Expression exp = parseAssignExp();
8946 e = new AST.ThrowExp(loc, exp);
8947 break;
8948 }
8949
8950 default:
8951 e = parsePrimaryExp();
8952 e = parsePostExp(e);
8953 break;
8954 }
8955 assert(e);
8956
8957 // ^^ is right associative and has higher precedence than the unary operators
8958 while (token.value == TOK.pow)
8959 {
8960 nextToken();
8961 AST.Expression e2 = parseUnaryExp();
8962 e = new AST.PowExp(loc, e, e2);
8963 }
8964
8965 return e;
8966 }
8967
8968 private AST.Expression parsePostExp(AST.Expression e)
8969 {
8970 while (1)
8971 {
8972 const loc = token.loc;
8973 switch (token.value)
8974 {
8975 case TOK.dot:
8976 nextToken();
8977 if (token.value == TOK.identifier)
8978 {
8979 Identifier id = token.ident;
8980
8981 nextToken();
8982 if (token.value == TOK.not && peekNext() != TOK.is_ && peekNext() != TOK.in_)
8983 {
8984 AST.Objects* tiargs = parseTemplateArguments();
8985 e = new AST.DotTemplateInstanceExp(loc, e, id, tiargs);
8986 }
8987 else
8988 e = new AST.DotIdExp(loc, e, id);
8989 continue;
8990 }
8991 if (token.value == TOK.new_)
8992 {
8993 e = parseNewExp(e);
8994 continue;
8995 }
8996 error("identifier or `new` expected following `.`, not `%s`", token.toChars());
8997 break;
8998
8999 case TOK.plusPlus:
9000 e = new AST.PostExp(EXP.plusPlus, loc, e);
9001 break;
9002
9003 case TOK.minusMinus:
9004 e = new AST.PostExp(EXP.minusMinus, loc, e);
9005 break;
9006
9007 case TOK.leftParenthesis:
9008 AST.Expressions* args = new AST.Expressions();
9009 AST.Identifiers* names = new AST.Identifiers();
9010 parseNamedArguments(args, names);
9011 e = new AST.CallExp(loc, e, args, names);
9012 continue;
9013
9014 case TOK.leftBracket:
9015 {
9016 // array dereferences:
9017 // array[index]
9018 // array[]
9019 // array[lwr .. upr]
9020 AST.Expression index;
9021 AST.Expression upr;
9022 auto arguments = new AST.Expressions();
9023
9024 inBrackets++;
9025 nextToken();
9026 while (token.value != TOK.rightBracket && token.value != TOK.endOfFile)
9027 {
9028 index = parseAssignExp();
9029 if (token.value == TOK.slice)
9030 {
9031 // array[..., lwr..upr, ...]
9032 nextToken();
9033 upr = parseAssignExp();
9034 arguments.push(new AST.IntervalExp(loc, index, upr));
9035 }
9036 else
9037 arguments.push(index);
9038 if (token.value == TOK.rightBracket)
9039 break;
9040 check(TOK.comma);
9041 }
9042 check(TOK.rightBracket);
9043 inBrackets--;
9044 e = new AST.ArrayExp(loc, e, arguments);
9045 continue;
9046 }
9047 default:
9048 return e;
9049 }
9050 nextToken();
9051 }
9052 }
9053
9054 private AST.Expression parseMulExp()
9055 {
9056 const loc = token.loc;
9057 auto e = parseUnaryExp();
9058
9059 while (1)
9060 {
9061 switch (token.value)
9062 {
9063 case TOK.mul:
9064 nextToken();
9065 auto e2 = parseUnaryExp();
9066 e = new AST.MulExp(loc, e, e2);
9067 continue;
9068
9069 case TOK.div:
9070 nextToken();
9071 auto e2 = parseUnaryExp();
9072 e = new AST.DivExp(loc, e, e2);
9073 continue;
9074
9075 case TOK.mod:
9076 nextToken();
9077 auto e2 = parseUnaryExp();
9078 e = new AST.ModExp(loc, e, e2);
9079 continue;
9080
9081 default:
9082 break;
9083 }
9084 break;
9085 }
9086 return e;
9087 }
9088
9089 private AST.Expression parseAddExp()
9090 {
9091 const loc = token.loc;
9092 auto e = parseMulExp();
9093
9094 while (1)
9095 {
9096 switch (token.value)
9097 {
9098 case TOK.add:
9099 nextToken();
9100 auto e2 = parseMulExp();
9101 e = new AST.AddExp(loc, e, e2);
9102 continue;
9103
9104 case TOK.min:
9105 nextToken();
9106 auto e2 = parseMulExp();
9107 e = new AST.MinExp(loc, e, e2);
9108 continue;
9109
9110 case TOK.tilde:
9111 nextToken();
9112 auto e2 = parseMulExp();
9113 e = new AST.CatExp(loc, e, e2);
9114 continue;
9115
9116 default:
9117 break;
9118 }
9119 break;
9120 }
9121 return e;
9122 }
9123
9124 private AST.Expression parseShiftExp()
9125 {
9126 const loc = token.loc;
9127 auto e = parseAddExp();
9128
9129 while (1)
9130 {
9131 switch (token.value)
9132 {
9133 case TOK.leftShift:
9134 nextToken();
9135 auto e2 = parseAddExp();
9136 e = new AST.ShlExp(loc, e, e2);
9137 continue;
9138
9139 case TOK.rightShift:
9140 nextToken();
9141 auto e2 = parseAddExp();
9142 e = new AST.ShrExp(loc, e, e2);
9143 continue;
9144
9145 case TOK.unsignedRightShift:
9146 nextToken();
9147 auto e2 = parseAddExp();
9148 e = new AST.UshrExp(loc, e, e2);
9149 continue;
9150
9151 default:
9152 break;
9153 }
9154 break;
9155 }
9156 return e;
9157 }
9158
9159 private AST.Expression parseCmpExp()
9160 {
9161 const loc = token.loc;
9162
9163 auto e = parseShiftExp();
9164 EXP op = EXP.reserved;
9165
9166 switch (token.value)
9167 {
9168 case TOK.equal: op = EXP.equal; goto Lequal;
9169 case TOK.notEqual: op = EXP.notEqual; goto Lequal;
9170 Lequal:
9171 nextToken();
9172 auto e2 = parseShiftExp();
9173 e = new AST.EqualExp(op, loc, e, e2);
9174 break;
9175
9176 case TOK.not:
9177 {
9178 // Attempt to identify '!is'
9179 const tv = peekNext();
9180 if (tv == TOK.in_)
9181 {
9182 nextToken();
9183 nextToken();
9184 auto e2 = parseShiftExp();
9185 e = new AST.InExp(loc, e, e2);
9186 e = new AST.NotExp(loc, e);
9187 break;
9188 }
9189 if (tv != TOK.is_)
9190 break;
9191 nextToken();
9192 op = EXP.notIdentity;
9193 goto Lidentity;
9194 }
9195 case TOK.is_: op = EXP.identity; goto Lidentity;
9196 Lidentity:
9197 nextToken();
9198 auto e2 = parseShiftExp();
9199 e = new AST.IdentityExp(op, loc, e, e2);
9200 break;
9201
9202 case TOK.lessThan: op = EXP.lessThan; goto Lcmp;
9203 case TOK.lessOrEqual: op = EXP.lessOrEqual; goto Lcmp;
9204 case TOK.greaterThan: op = EXP.greaterThan; goto Lcmp;
9205 case TOK.greaterOrEqual: op = EXP.greaterOrEqual; goto Lcmp;
9206 Lcmp:
9207 nextToken();
9208 auto e2 = parseShiftExp();
9209 e = new AST.CmpExp(op, loc, e, e2);
9210 break;
9211
9212 case TOK.in_:
9213 nextToken();
9214 auto e2 = parseShiftExp();
9215 e = new AST.InExp(loc, e, e2);
9216 break;
9217
9218 default:
9219 break;
9220 }
9221 return e;
9222 }
9223
9224 private AST.Expression parseAndExp()
9225 {
9226 Loc loc = token.loc;
9227 auto e = parseCmpExp();
9228 while (token.value == TOK.and)
9229 {
9230 checkParens(TOK.and, e);
9231 nextToken();
9232 auto e2 = parseCmpExp();
9233 checkParens(TOK.and, e2);
9234 e = new AST.AndExp(loc, e, e2);
9235 loc = token.loc;
9236 }
9237 return e;
9238 }
9239
9240 private AST.Expression parseXorExp()
9241 {
9242 const loc = token.loc;
9243
9244 auto e = parseAndExp();
9245 while (token.value == TOK.xor)
9246 {
9247 checkParens(TOK.xor, e);
9248 nextToken();
9249 auto e2 = parseAndExp();
9250 checkParens(TOK.xor, e2);
9251 e = new AST.XorExp(loc, e, e2);
9252 }
9253 return e;
9254 }
9255
9256 private AST.Expression parseOrExp()
9257 {
9258 const loc = token.loc;
9259
9260 auto e = parseXorExp();
9261 while (token.value == TOK.or)
9262 {
9263 checkParens(TOK.or, e);
9264 nextToken();
9265 auto e2 = parseXorExp();
9266 checkParens(TOK.or, e2);
9267 e = new AST.OrExp(loc, e, e2);
9268 }
9269 return e;
9270 }
9271
9272 private AST.Expression parseAndAndExp()
9273 {
9274 const loc = token.loc;
9275
9276 auto e = parseOrExp();
9277 while (token.value == TOK.andAnd)
9278 {
9279 nextToken();
9280 auto e2 = parseOrExp();
9281 e = new AST.LogicalExp(loc, EXP.andAnd, e, e2);
9282 }
9283 return e;
9284 }
9285
9286 private AST.Expression parseOrOrExp()
9287 {
9288 const loc = token.loc;
9289
9290 auto e = parseAndAndExp();
9291 while (token.value == TOK.orOr)
9292 {
9293 nextToken();
9294 auto e2 = parseAndAndExp();
9295 e = new AST.LogicalExp(loc, EXP.orOr, e, e2);
9296 }
9297 return e;
9298 }
9299
9300 private AST.Expression parseCondExp()
9301 {
9302 const loc = token.loc;
9303
9304 auto e = parseOrOrExp();
9305 if (token.value == TOK.question)
9306 {
9307 nextToken();
9308 auto e1 = parseExpression();
9309 check(TOK.colon);
9310 auto e2 = parseCondExp();
9311 e = new AST.CondExp(loc, e, e1, e2);
9312 }
9313 return e;
9314 }
9315
9316 AST.Expression parseAssignExp()
9317 {
9318 AST.Expression e;
9319 e = parseCondExp();
9320 if (e is null)
9321 return e;
9322
9323 // require parens for e.g. `t ? a = 1 : b = 2`
9324 void checkRequiredParens()
9325 {
9326 if (e.op == EXP.question && !e.parens)
9327 eSink.error(e.loc, "`%s` must be surrounded by parentheses when next to operator `%s`",
9328 e.toChars(), Token.toChars(token.value));
9329 }
9330
9331 const loc = token.loc;
9332 switch (token.value)
9333 {
9334 case TOK.assign:
9335 checkRequiredParens();
9336 nextToken();
9337 auto e2 = parseAssignExp();
9338 e = new AST.AssignExp(loc, e, e2);
9339 break;
9340
9341 case TOK.addAssign:
9342 checkRequiredParens();
9343 nextToken();
9344 auto e2 = parseAssignExp();
9345 e = new AST.AddAssignExp(loc, e, e2);
9346 break;
9347
9348 case TOK.minAssign:
9349 checkRequiredParens();
9350 nextToken();
9351 auto e2 = parseAssignExp();
9352 e = new AST.MinAssignExp(loc, e, e2);
9353 break;
9354
9355 case TOK.mulAssign:
9356 checkRequiredParens();
9357 nextToken();
9358 auto e2 = parseAssignExp();
9359 e = new AST.MulAssignExp(loc, e, e2);
9360 break;
9361
9362 case TOK.divAssign:
9363 checkRequiredParens();
9364 nextToken();
9365 auto e2 = parseAssignExp();
9366 e = new AST.DivAssignExp(loc, e, e2);
9367 break;
9368
9369 case TOK.modAssign:
9370 checkRequiredParens();
9371 nextToken();
9372 auto e2 = parseAssignExp();
9373 e = new AST.ModAssignExp(loc, e, e2);
9374 break;
9375
9376 case TOK.powAssign:
9377 checkRequiredParens();
9378 nextToken();
9379 auto e2 = parseAssignExp();
9380 e = new AST.PowAssignExp(loc, e, e2);
9381 break;
9382
9383 case TOK.andAssign:
9384 checkRequiredParens();
9385 nextToken();
9386 auto e2 = parseAssignExp();
9387 e = new AST.AndAssignExp(loc, e, e2);
9388 break;
9389
9390 case TOK.orAssign:
9391 checkRequiredParens();
9392 nextToken();
9393 auto e2 = parseAssignExp();
9394 e = new AST.OrAssignExp(loc, e, e2);
9395 break;
9396
9397 case TOK.xorAssign:
9398 checkRequiredParens();
9399 nextToken();
9400 auto e2 = parseAssignExp();
9401 e = new AST.XorAssignExp(loc, e, e2);
9402 break;
9403
9404 case TOK.leftShiftAssign:
9405 checkRequiredParens();
9406 nextToken();
9407 auto e2 = parseAssignExp();
9408 e = new AST.ShlAssignExp(loc, e, e2);
9409 break;
9410
9411 case TOK.rightShiftAssign:
9412 checkRequiredParens();
9413 nextToken();
9414 auto e2 = parseAssignExp();
9415 e = new AST.ShrAssignExp(loc, e, e2);
9416 break;
9417
9418 case TOK.unsignedRightShiftAssign:
9419 checkRequiredParens();
9420 nextToken();
9421 auto e2 = parseAssignExp();
9422 e = new AST.UshrAssignExp(loc, e, e2);
9423 break;
9424
9425 case TOK.concatenateAssign:
9426 checkRequiredParens();
9427 nextToken();
9428 auto e2 = parseAssignExp();
9429 e = new AST.CatAssignExp(loc, e, e2);
9430 break;
9431
9432 default:
9433 break;
9434 }
9435
9436 return e;
9437 }
9438
9439 /*************************
9440 * Collect argument list.
9441 * Assume current token is ',', '$(LPAREN)' or '['.
9442 */
9443 private AST.Expressions* parseArguments()
9444 {
9445 // function call
9446 AST.Expressions* arguments = new AST.Expressions();
9447 parseNamedArguments(arguments, null);
9448 return arguments;
9449 }
9450
9451 /*************************
9452 * Collect argument list.
9453 * Assume current token is ',', '$(LPAREN)' or '['.
9454 */
9455 private void parseNamedArguments(AST.Expressions* arguments, AST.Identifiers* names)
9456 {
9457 assert(arguments);
9458
9459 const endtok = token.value == TOK.leftBracket ? TOK.rightBracket : TOK.rightParenthesis;
9460
9461 nextToken();
9462
9463 while (token.value != endtok && token.value != TOK.endOfFile)
9464 {
9465 if (peekNext() == TOK.colon)
9466 {
9467 // Named argument `name: exp`
9468 auto loc = token.loc;
9469 auto ident = token.ident;
9470 check(TOK.identifier);
9471 check(TOK.colon);
9472 if (names)
9473 names.push(ident);
9474 else
9475 error(loc, "named arguments not allowed here");
9476 }
9477 else
9478 {
9479 if (names)
9480 names.push(null);
9481 }
9482
9483 auto arg = parseAssignExp();
9484 arguments.push(arg);
9485
9486 if (token.value != TOK.comma)
9487 break;
9488
9489 nextToken(); //comma
9490 }
9491 check(endtok);
9492 }
9493
9494 /*******************************************
9495 * Params:
9496 * thisexp = If not null, it is the `this` reference for the creation
9497 * of an inner class.
9498 * https://dlang.org/spec/class.html#nested-explicit
9499 * https://dlang.org/spec/expression.html#postfix_expressions
9500 * If null, then it is a NewExpression.
9501 * https://dlang.org/spec/expression.html#NewExpression
9502 * Returns:
9503 * NewExpression
9504 */
9505 private AST.Expression parseNewExp(AST.Expression thisexp)
9506 {
9507 const loc = token.loc;
9508
9509 nextToken(); // skip past `new`
9510
9511 // parse PlacementExpression if any
9512 AST.Expression placement;
9513 if (token.value == TOK.leftParenthesis)
9514 {
9515 nextToken();
9516 placement = parseAssignExp();
9517 check(TOK.rightParenthesis);
9518 }
9519
9520 AST.Expressions* arguments = null;
9521 AST.Identifiers* names = null;
9522
9523 // An anonymous nested class starts with "class"
9524 if (token.value == TOK.class_)
9525 {
9526 nextToken();
9527 if (token.value == TOK.leftParenthesis)
9528 {
9529 arguments = new AST.Expressions();
9530 names = new AST.Identifiers();
9531 parseNamedArguments(arguments, names);
9532 }
9533
9534 AST.BaseClasses* baseclasses = null;
9535 if (token.value != TOK.leftCurly)
9536 baseclasses = parseBaseClasses();
9537
9538 Identifier id = null;
9539 AST.Dsymbols* members = null;
9540
9541 if (token.value != TOK.leftCurly)
9542 {
9543 error("`{ members }` expected for anonymous class");
9544 }
9545 else
9546 {
9547 nextToken();
9548 members = parseDeclDefs(0);
9549 if (token.value != TOK.rightCurly)
9550 error("class member expected");
9551 nextToken();
9552 }
9553
9554 auto cd = new AST.ClassDeclaration(loc, id, baseclasses, members, false);
9555 auto e = new AST.NewAnonClassExp(loc, placement, thisexp, cd, arguments);
9556 return e;
9557 }
9558
9559 const stc = parseTypeCtor();
9560 auto t = parseBasicType(true);
9561 t = parseTypeSuffixes(t);
9562 t = t.addSTC(stc);
9563 if (t.ty == Taarray)
9564 {
9565 AST.TypeAArray taa = cast(AST.TypeAArray)t;
9566 AST.Type index = taa.index;
9567 // `new Type[expr]` is a static array
9568 auto edim = AST.typeToExpression(index);
9569 if (edim)
9570 t = new AST.TypeSArray(taa.next, edim);
9571 }
9572 else if (token.value == TOK.leftParenthesis && t.ty != Tsarray)
9573 {
9574 arguments = new AST.Expressions();
9575 names = new AST.Identifiers();
9576 parseNamedArguments(arguments, names);
9577 }
9578
9579 auto e = new AST.NewExp(loc, placement, thisexp, t, arguments, names);
9580 return e;
9581 }
9582
9583 /**********************************************
9584 */
9585 private void addComment(AST.Dsymbol s, const(char)* blockComment)
9586 {
9587 if (s !is null)
9588 this.addComment(s, blockComment.toDString());
9589 }
9590
9591 private void addComment(AST.Dsymbol s, const(char)[] blockComment)
9592 {
9593 if (s !is null)
9594 {
9595 s.addComment(combineComments(blockComment, token.lineComment, true));
9596 token.lineComment = null;
9597 }
9598 }
9599
9600 /**********************************************
9601 * Recognize builtin @ attributes
9602 * Params:
9603 * ident = identifier
9604 * Returns:
9605 * storage class for attribute, 0 if not
9606 */
9607 static STC isBuiltinAtAttribute(Identifier ident)
9608 {
9609 return (ident == Id.property) ? STC.property :
9610 (ident == Id.nogc) ? STC.nogc :
9611 (ident == Id.safe) ? STC.safe :
9612 (ident == Id.trusted) ? STC.trusted :
9613 (ident == Id.system) ? STC.system :
9614 (ident == Id.live) ? STC.live :
9615 (ident == Id.future) ? STC.future :
9616 (ident == Id.disable) ? STC.disable :
9617 STC.none;
9618 }
9619
9620 enum STC atAttrGroup =
9621 STC.property |
9622 STC.nogc |
9623 STC.safe |
9624 STC.trusted |
9625 STC.system |
9626 STC.live |
9627 /*STC.future |*/ // probably should be included
9628 STC.disable;
9629
9630 void usageOfBodyKeyword()
9631 {
9632 if (mod.edition >= Edition.v2024)
9633 {
9634 eSink.error(token.loc, "usage of identifer `body` as a keyword is obsolete. Use `do` instead.");
9635 }
9636 }
9637 }
9638
9639 enum PREC : int
9640 {
9641 zero,
9642 expr,
9643 assign,
9644 cond,
9645 oror,
9646 andand,
9647 or,
9648 xor,
9649 and,
9650 equal,
9651 rel,
9652 shift,
9653 add,
9654 mul,
9655 pow,
9656 unary,
9657 primary,
9658 }
9659
9660 /**********************************
9661 * Set operator precedence for each operator.
9662 *
9663 * Used by hdrgen
9664 */
9665 immutable PREC[EXP.max + 1] precedence =
9666 [
9667 EXP.type : PREC.expr,
9668 EXP.error : PREC.expr,
9669 EXP.objcClassReference : PREC.expr, // Objective-C class reference, same as EXP.type
9670
9671 EXP.mixin_ : PREC.primary,
9672
9673 EXP.import_ : PREC.primary,
9674 EXP.dotVariable : PREC.primary,
9675 EXP.scope_ : PREC.primary,
9676 EXP.identifier : PREC.primary,
9677 EXP.this_ : PREC.primary,
9678 EXP.super_ : PREC.primary,
9679 EXP.int64 : PREC.primary,
9680 EXP.float64 : PREC.primary,
9681 EXP.complex80 : PREC.primary,
9682 EXP.null_ : PREC.primary,
9683 EXP.string_ : PREC.primary,
9684 EXP.arrayLiteral : PREC.primary,
9685 EXP.assocArrayLiteral : PREC.primary,
9686 EXP.classReference : PREC.primary,
9687 EXP.file : PREC.primary,
9688 EXP.fileFullPath : PREC.primary,
9689 EXP.line : PREC.primary,
9690 EXP.moduleString : PREC.primary,
9691 EXP.functionString : PREC.primary,
9692 EXP.prettyFunction : PREC.primary,
9693 EXP.typeid_ : PREC.primary,
9694 EXP.is_ : PREC.primary,
9695 EXP.assert_ : PREC.primary,
9696 EXP.halt : PREC.primary,
9697 EXP.template_ : PREC.primary,
9698 EXP.dSymbol : PREC.primary,
9699 EXP.function_ : PREC.primary,
9700 EXP.variable : PREC.primary,
9701 EXP.symbolOffset : PREC.primary,
9702 EXP.structLiteral : PREC.primary,
9703 EXP.compoundLiteral : PREC.primary,
9704 EXP.arrayLength : PREC.primary,
9705 EXP.delegatePointer : PREC.primary,
9706 EXP.delegateFunctionPointer : PREC.primary,
9707 EXP.remove : PREC.primary,
9708 EXP.tuple : PREC.primary,
9709 EXP.traits : PREC.primary,
9710 EXP.overloadSet : PREC.primary,
9711 EXP.void_ : PREC.primary,
9712 EXP.vectorArray : PREC.primary,
9713 EXP._Generic : PREC.primary,
9714
9715 // post
9716 EXP.dotTemplateInstance : PREC.primary,
9717 EXP.dotIdentifier : PREC.primary,
9718 EXP.dotTemplateDeclaration : PREC.primary,
9719 EXP.dot : PREC.primary,
9720 EXP.dotType : PREC.primary,
9721 EXP.plusPlus : PREC.primary,
9722 EXP.minusMinus : PREC.primary,
9723 EXP.prePlusPlus : PREC.primary,
9724 EXP.preMinusMinus : PREC.primary,
9725 EXP.call : PREC.primary,
9726 EXP.slice : PREC.primary,
9727 EXP.array : PREC.primary,
9728 EXP.index : PREC.primary,
9729
9730 EXP.delegate_ : PREC.unary,
9731 EXP.address : PREC.unary,
9732 EXP.star : PREC.unary,
9733 EXP.negate : PREC.unary,
9734 EXP.uadd : PREC.unary,
9735 EXP.not : PREC.unary,
9736 EXP.tilde : PREC.unary,
9737 EXP.delete_ : PREC.unary,
9738 EXP.new_ : PREC.unary,
9739 EXP.newAnonymousClass : PREC.unary,
9740 EXP.cast_ : PREC.unary,
9741 EXP.throw_ : PREC.unary,
9742
9743 EXP.vector : PREC.unary,
9744 EXP.pow : PREC.pow,
9745
9746 EXP.mul : PREC.mul,
9747 EXP.div : PREC.mul,
9748 EXP.mod : PREC.mul,
9749
9750 EXP.add : PREC.add,
9751 EXP.min : PREC.add,
9752 EXP.concatenate : PREC.add,
9753
9754 EXP.leftShift : PREC.shift,
9755 EXP.rightShift : PREC.shift,
9756 EXP.unsignedRightShift : PREC.shift,
9757
9758 EXP.lessThan : PREC.rel,
9759 EXP.lessOrEqual : PREC.rel,
9760 EXP.greaterThan : PREC.rel,
9761 EXP.greaterOrEqual : PREC.rel,
9762 EXP.in_ : PREC.rel,
9763
9764 /* Note that we changed precedence, so that < and != have the same
9765 * precedence. This change is in the parser, too.
9766 */
9767 EXP.equal : PREC.rel,
9768 EXP.notEqual : PREC.rel,
9769 EXP.identity : PREC.rel,
9770 EXP.notIdentity : PREC.rel,
9771
9772 EXP.and : PREC.and,
9773 EXP.xor : PREC.xor,
9774 EXP.or : PREC.or,
9775
9776 EXP.andAnd : PREC.andand,
9777 EXP.orOr : PREC.oror,
9778
9779 EXP.question : PREC.cond,
9780
9781 EXP.assign : PREC.assign,
9782 EXP.construct : PREC.assign,
9783 EXP.blit : PREC.assign,
9784 EXP.loweredAssignExp : PREC.assign,
9785 EXP.addAssign : PREC.assign,
9786 EXP.minAssign : PREC.assign,
9787 EXP.concatenateAssign : PREC.assign,
9788 EXP.concatenateElemAssign : PREC.assign,
9789 EXP.concatenateDcharAssign : PREC.assign,
9790 EXP.mulAssign : PREC.assign,
9791 EXP.divAssign : PREC.assign,
9792 EXP.modAssign : PREC.assign,
9793 EXP.powAssign : PREC.assign,
9794 EXP.leftShiftAssign : PREC.assign,
9795 EXP.rightShiftAssign : PREC.assign,
9796 EXP.unsignedRightShiftAssign : PREC.assign,
9797 EXP.andAssign : PREC.assign,
9798 EXP.orAssign : PREC.assign,
9799 EXP.xorAssign : PREC.assign,
9800
9801 EXP.comma : PREC.expr,
9802 EXP.declaration : PREC.expr,
9803
9804 EXP.interval : PREC.assign,
9805 ];
9806
9807 enum ParseStatementFlags : int
9808 {
9809 scope_ = 2, // start a new scope
9810 curly = 4, // { } statement is required
9811 curlyScope = 8, // { } starts a new scope
9812 semiOk = 0x10, // empty ';' are really ok
9813 }
9814
9815 struct PrefixAttributes(AST)
9816 {
9817 STC storageClass;
9818 AST.Expression depmsg;
9819 LINK link;
9820 AST.Visibility visibility;
9821 bool setAlignment;
9822 AST.Expression ealign;
9823 AST.Expressions* udas;
9824 const(char)* comment;
9825 }
9826
9827 /// The result of the `ParseLinkage` function
9828 struct ParsedLinkage(AST)
9829 {
9830 /// What linkage was specified
9831 LINK link;
9832 /// If `extern(C++, class|struct)`, contains the `class|struct`
9833 CPPMANGLE cppmangle;
9834 /// If `extern(C++, some.identifier)`, will be the identifiers
9835 AST.Identifiers* idents;
9836 /// If `extern(C++, (some_tuple_expression)|"string"), will be the expressions
9837 AST.Expressions* identExps;
9838 }
9839
9840
9841 /*********************************** Private *************************************/
9842
9843 /***********************
9844 * How multiple declarations are parsed.
9845 * If 1, treat as C.
9846 * If 0, treat:
9847 * int *p, i;
9848 * as:
9849 * int* p;
9850 * int* i;
9851 */
9852 private enum CDECLSYNTAX = 0;
9853
9854 /*****
9855 * Support C cast syntax:
9856 * (type)(expression)
9857 */
9858 private enum CCASTSYNTAX = 1;
9859
9860 /*****
9861 * Support postfix C array declarations, such as
9862 * int a[3][4];
9863 */
9864 private enum CARRAYDECL = 1;
9865
9866 /*****************************
9867 * Destructively extract storage class from pAttrs.
9868 */
9869 private STC getStorageClass(AST)(PrefixAttributes!(AST)* pAttrs)
9870 {
9871 STC stc = STC.none;
9872 if (pAttrs)
9873 {
9874 stc = pAttrs.storageClass;
9875 pAttrs.storageClass = STC.none;
9876 }
9877 return stc;
9878 }