Debian Codegraph @

gcc/rust/parse/rust-parse-impl.h

raw
1 // Copyright (C) 2020-2025 Free Software Foundation, Inc.
2
3 // This file is part of GCC.
4
5 // GCC is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free
7 // Software Foundation; either version 3, or (at your option) any later
8 // version.
9
10 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 // for more details.
14
15 // You should have received a copy of the GNU General Public License
16 // along with GCC; see the file COPYING3. If not see
17 // <http://www.gnu.org/licenses/>.
18
19 /* Template implementation for Rust::Parser. Previously in rust-parse.cc (before
20 * Parser was template). Separated from rust-parse.h for readability. */
21
22 /* DO NOT INCLUDE ANYWHERE - this is automatically included with rust-parse.h
23 * This is also the reason why there are no include guards. */
24
25 #include "rust-common.h"
26 #include "rust-expr.h"
27 #include "rust-item.h"
28 #include "rust-common.h"
29 #include "rust-token.h"
30 #define INCLUDE_ALGORITHM
31 #include "rust-diagnostics.h"
32 #include "rust-dir-owner.h"
33 #include "rust-attribute-values.h"
34 #include "rust-keyword-values.h"
35 #include "rust-edition.h"
36
37 #include "optional.h"
38
39 namespace Rust {
40 // Left binding powers of operations.
41 enum binding_powers
42 {
43 // Highest priority
44 LBP_HIGHEST = 100,
45
46 LBP_PATH = 95,
47
48 LBP_METHOD_CALL = 90,
49
50 LBP_FIELD_EXPR = 85,
51
52 LBP_FUNCTION_CALL = 80,
53 LBP_ARRAY_REF = LBP_FUNCTION_CALL,
54
55 LBP_QUESTION_MARK = 75, // unary postfix - counts as left
56
57 LBP_UNARY_PLUS = 70, // Used only when the null denotation is +
58 LBP_UNARY_MINUS = LBP_UNARY_PLUS, // Used only when the null denotation is -
59 LBP_UNARY_ASTERISK = LBP_UNARY_PLUS, // deref operator - unary prefix
60 LBP_UNARY_EXCLAM = LBP_UNARY_PLUS,
61 LBP_UNARY_AMP = LBP_UNARY_PLUS,
62 LBP_UNARY_AMP_MUT = LBP_UNARY_PLUS,
63
64 LBP_AS = 65,
65
66 LBP_MUL = 60,
67 LBP_DIV = LBP_MUL,
68 LBP_MOD = LBP_MUL,
69
70 LBP_PLUS = 55,
71 LBP_MINUS = LBP_PLUS,
72
73 LBP_L_SHIFT = 50,
74 LBP_R_SHIFT = LBP_L_SHIFT,
75
76 LBP_AMP = 45,
77
78 LBP_CARET = 40,
79
80 LBP_PIPE = 35,
81
82 LBP_EQUAL = 30,
83 LBP_NOT_EQUAL = LBP_EQUAL,
84 LBP_SMALLER_THAN = LBP_EQUAL,
85 LBP_SMALLER_EQUAL = LBP_EQUAL,
86 LBP_GREATER_THAN = LBP_EQUAL,
87 LBP_GREATER_EQUAL = LBP_EQUAL,
88
89 LBP_LOGICAL_AND = 25,
90
91 LBP_LOGICAL_OR = 20,
92
93 LBP_DOT_DOT = 15,
94 LBP_DOT_DOT_EQ = LBP_DOT_DOT,
95
96 // TODO: note all these assig operators are RIGHT associative!
97 LBP_ASSIG = 10,
98 LBP_PLUS_ASSIG = LBP_ASSIG,
99 LBP_MINUS_ASSIG = LBP_ASSIG,
100 LBP_MULT_ASSIG = LBP_ASSIG,
101 LBP_DIV_ASSIG = LBP_ASSIG,
102 LBP_MOD_ASSIG = LBP_ASSIG,
103 LBP_AMP_ASSIG = LBP_ASSIG,
104 LBP_PIPE_ASSIG = LBP_ASSIG,
105 LBP_CARET_ASSIG = LBP_ASSIG,
106 LBP_L_SHIFT_ASSIG = LBP_ASSIG,
107 LBP_R_SHIFT_ASSIG = LBP_ASSIG,
108
109 // return, break, and closures as lowest priority?
110 LBP_RETURN = 5,
111 LBP_BREAK = LBP_RETURN,
112 LBP_CLOSURE = LBP_RETURN, // unary prefix operators
113
114 #if 0
115 // rust precedences
116 // used for closures
117 PREC_CLOSURE = -40,
118 // used for break, continue, return, and yield
119 PREC_JUMP = -30,
120 // used for range (although weird comment in rustc about this)
121 PREC_RANGE = -10,
122 // used for binary operators mentioned below - also cast, colon (type),
123 // assign, assign_op
124 PREC_BINOP = FROM_ASSOC_OP,
125 // used for box, address_of, let, unary (again, weird comment on let)
126 PREC_PREFIX = 50,
127 // used for await, call, method call, field, index, try,
128 // inline asm, macro invocation
129 PREC_POSTFIX = 60,
130 // used for array, repeat, tuple, literal, path, paren, if,
131 // while, for, 'loop', match, block, try block, async, struct
132 PREC_PAREN = 99,
133 PREC_FORCE_PAREN = 100,
134 #endif
135
136 // lowest priority
137 LBP_LOWEST = 0
138 };
139
140 /* Returns whether the token can start a type (i.e. there is a valid type
141 * beginning with the token). */
142 inline bool
143 can_tok_start_type (TokenId id)
144 {
145 switch (id)
146 {
147 case EXCLAM:
148 case LEFT_SQUARE:
149 case LEFT_ANGLE:
150 case UNDERSCORE:
151 case ASTERISK:
152 case AMP:
153 case LIFETIME:
154 case IDENTIFIER:
155 case SUPER:
156 case SELF:
157 case SELF_ALIAS:
158 case CRATE:
159 case DOLLAR_SIGN:
160 case SCOPE_RESOLUTION:
161 case LEFT_PAREN:
162 case FOR:
163 case ASYNC:
164 case CONST:
165 case UNSAFE:
166 case EXTERN_KW:
167 case FN_KW:
168 case IMPL:
169 case DYN:
170 case QUESTION_MARK:
171 return true;
172 default:
173 return false;
174 }
175 }
176
177 /* Returns whether the token id is (or is likely to be) a right angle bracket.
178 * i.e. '>', '>>', '>=' and '>>=' tokens. */
179 inline bool
180 is_right_angle_tok (TokenId id)
181 {
182 switch (id)
183 {
184 case RIGHT_ANGLE:
185 case RIGHT_SHIFT:
186 case GREATER_OR_EQUAL:
187 case RIGHT_SHIFT_EQ:
188 return true;
189 default:
190 return false;
191 }
192 }
193
194 /* HACK-y special handling for skipping a right angle token at the end of
195 * generic arguments.
196 * Currently, this replaces the "current token" with one that is identical
197 * except has the leading '>' removed (e.g. '>>' becomes '>'). This is bad
198 * for several reasons - it modifies the token stream to something that
199 * actually doesn't make syntactic sense, it may not worked if the token
200 * has already been skipped, etc. It was done because it would not
201 * actually require inserting new items into the token stream (which I
202 * thought would take more work to not mess up) and because I wasn't sure
203 * if the "already seen right angle" flag in the parser would work
204 * correctly.
205 * Those two other approaches listed are in my opinion actually better
206 * long-term - insertion is probably best as it reflects syntactically
207 * what occurs. On the other hand, I need to do a code audit to make sure
208 * that insertion doesn't mess anything up. So that's a FIXME. */
209 template <typename ManagedTokenSource>
210 bool
211 Parser<ManagedTokenSource>::skip_generics_right_angle ()
212 {
213 /* OK, new great idea. Have a lexer method called
214 * "split_current_token(TokenType newLeft, TokenType newRight)", which is
215 * called here with whatever arguments are appropriate. That lexer method
216 * handles "replacing" the current token with the "newLeft" and "inserting"
217 * the next token with the "newRight" (and creating a location, etc. for it)
218 */
219
220 /* HACK: special handling for right shift '>>', greater or equal '>=', and
221 * right shift assig */
222 // '>>='
223 const_TokenPtr tok = lexer.peek_token ();
224 switch (tok->get_id ())
225 {
226 case RIGHT_ANGLE:
227 // this is good - skip token
228 lexer.skip_token ();
229 return true;
230 case RIGHT_SHIFT: {
231 // new implementation that should be better
232 lexer.split_current_token (RIGHT_ANGLE, RIGHT_ANGLE);
233 lexer.skip_token ();
234 return true;
235 }
236 case GREATER_OR_EQUAL: {
237 // new implementation that should be better
238 lexer.split_current_token (RIGHT_ANGLE, EQUAL);
239 lexer.skip_token ();
240 return true;
241 }
242 case RIGHT_SHIFT_EQ: {
243 // new implementation that should be better
244 lexer.split_current_token (RIGHT_ANGLE, GREATER_OR_EQUAL);
245 lexer.skip_token ();
246 return true;
247 }
248 default:
249 add_error (Error (tok->get_locus (),
250 "expected %<>%> at end of generic argument - found %qs",
251 tok->get_token_description ()));
252 return false;
253 }
254 }
255
256 /* Gets left binding power for specified token.
257 * Not suitable for use at the moment or possibly ever because binding power
258 * cannot be purely determined from operator token with Rust grammar - e.g.
259 * method call and field access have
260 * different left binding powers but the same operator token. */
261 template <typename ManagedTokenSource>
262 int
263 Parser<ManagedTokenSource>::left_binding_power (const_TokenPtr token)
264 {
265 // HACK: called with "peek_token()", so lookahead is "peek_token(1)"
266 switch (token->get_id ())
267 {
268 /* TODO: issue here - distinguish between method calls and field access
269 * somehow? Also would have to distinguish between paths and function
270 * calls (:: operator), maybe more stuff. */
271 /* Current plan for tackling LBP - don't do it based on token, use
272 * lookahead. Or alternatively, only use Pratt parsing for OperatorExpr
273 * and handle other expressions without it. rustc only considers
274 * arithmetic, logical/relational, 'as',
275 * '?=', ranges, colons, and assignment to have operator precedence and
276 * associativity rules applicable. It then has
277 * a separate "ExprPrecedence" that also includes binary operators. */
278
279 // TODO: handle operator overloading - have a function replace the
280 // operator?
281
282 /*case DOT:
283 return LBP_DOT;*/
284
285 case SCOPE_RESOLUTION:
286 rust_debug (
287 "possible error - looked up LBP of scope resolution operator. should "
288 "be handled elsewhere.");
289 return LBP_PATH;
290
291 /* Resolved by lookahead HACK that should work with current code. If next
292 * token is identifier and token after that isn't parenthesised expression
293 * list, it is a field reference. */
294 case DOT:
295 if (lexer.peek_token (1)->get_id () == IDENTIFIER
296 && lexer.peek_token (2)->get_id () != LEFT_PAREN)
297 {
298 return LBP_FIELD_EXPR;
299 }
300 return LBP_METHOD_CALL;
301
302 case LEFT_PAREN:
303 return LBP_FUNCTION_CALL;
304
305 case LEFT_SQUARE:
306 return LBP_ARRAY_REF;
307
308 // postfix question mark (i.e. error propagation expression)
309 case QUESTION_MARK:
310 return LBP_QUESTION_MARK;
311
312 case AS:
313 return LBP_AS;
314
315 case ASTERISK:
316 return LBP_MUL;
317 case DIV:
318 return LBP_DIV;
319 case PERCENT:
320 return LBP_MOD;
321
322 case PLUS:
323 return LBP_PLUS;
324 case MINUS:
325 return LBP_MINUS;
326
327 case LEFT_SHIFT:
328 return LBP_L_SHIFT;
329 case RIGHT_SHIFT:
330 return LBP_R_SHIFT;
331
332 // binary & operator
333 case AMP:
334 return LBP_AMP;
335
336 // binary ^ operator
337 case CARET:
338 return LBP_CARET;
339
340 // binary | operator
341 case PIPE:
342 return LBP_PIPE;
343
344 case EQUAL_EQUAL:
345 return LBP_EQUAL;
346 case NOT_EQUAL:
347 return LBP_NOT_EQUAL;
348 case RIGHT_ANGLE:
349 return LBP_GREATER_THAN;
350 case GREATER_OR_EQUAL:
351 return LBP_GREATER_EQUAL;
352 case LEFT_ANGLE:
353 return LBP_SMALLER_THAN;
354 case LESS_OR_EQUAL:
355 return LBP_SMALLER_EQUAL;
356
357 case LOGICAL_AND:
358 return LBP_LOGICAL_AND;
359
360 case OR:
361 return LBP_LOGICAL_OR;
362
363 case DOT_DOT:
364 return LBP_DOT_DOT;
365
366 case DOT_DOT_EQ:
367 return LBP_DOT_DOT_EQ;
368
369 case EQUAL:
370 return LBP_ASSIG;
371 case PLUS_EQ:
372 return LBP_PLUS_ASSIG;
373 case MINUS_EQ:
374 return LBP_MINUS_ASSIG;
375 case ASTERISK_EQ:
376 return LBP_MULT_ASSIG;
377 case DIV_EQ:
378 return LBP_DIV_ASSIG;
379 case PERCENT_EQ:
380 return LBP_MOD_ASSIG;
381 case AMP_EQ:
382 return LBP_AMP_ASSIG;
383 case PIPE_EQ:
384 return LBP_PIPE_ASSIG;
385 case CARET_EQ:
386 return LBP_CARET_ASSIG;
387 case LEFT_SHIFT_EQ:
388 return LBP_L_SHIFT_ASSIG;
389 case RIGHT_SHIFT_EQ:
390 return LBP_R_SHIFT_ASSIG;
391
392 /* HACK: float literal due to lexer misidentifying a dot then an integer as
393 * a float */
394 case FLOAT_LITERAL:
395 return LBP_FIELD_EXPR;
396 // field expr is same as tuple expr in precedence, i imagine
397 // TODO: is this needed anymore? lexer shouldn't do that anymore
398
399 // anything that can't appear in an infix position is given lowest priority
400 default:
401 return LBP_LOWEST;
402 }
403 }
404
405 // Returns true when current token is EOF.
406 template <typename ManagedTokenSource>
407 bool
408 Parser<ManagedTokenSource>::done_end_of_file ()
409 {
410 return lexer.peek_token ()->get_id () == END_OF_FILE;
411 }
412
413 // Parses a sequence of items within a module or the implicit top-level module
414 // in a crate
415 template <typename ManagedTokenSource>
416 std::vector<std::unique_ptr<AST::Item>>
417 Parser<ManagedTokenSource>::parse_items ()
418 {
419 std::vector<std::unique_ptr<AST::Item>> items;
420
421 const_TokenPtr t = lexer.peek_token ();
422 while (t->get_id () != END_OF_FILE)
423 {
424 std::unique_ptr<AST::Item> item = parse_item (false);
425 if (item == nullptr)
426 {
427 Error error (lexer.peek_token ()->get_locus (),
428 "failed to parse item in crate");
429 add_error (std::move (error));
430
431 // TODO: should all items be cleared?
432 items = std::vector<std::unique_ptr<AST::Item>> ();
433 break;
434 }
435
436 items.push_back (std::move (item));
437
438 t = lexer.peek_token ();
439 }
440
441 return items;
442 }
443
444 // Parses a crate (compilation unit) - entry point
445 template <typename ManagedTokenSource>
446 std::unique_ptr<AST::Crate>
447 Parser<ManagedTokenSource>::parse_crate ()
448 {
449 // parse inner attributes
450 AST::AttrVec inner_attrs = parse_inner_attributes ();
451
452 // parse items
453 std::vector<std::unique_ptr<AST::Item>> items = parse_items ();
454
455 // emit all errors
456 for (const auto &error : error_table)
457 error.emit ();
458
459 return std::unique_ptr<AST::Crate> (
460 new AST::Crate (std::move (items), std::move (inner_attrs)));
461 }
462
463 // Parse a contiguous block of inner attributes.
464 template <typename ManagedTokenSource>
465 AST::AttrVec
466 Parser<ManagedTokenSource>::parse_inner_attributes ()
467 {
468 AST::AttrVec inner_attributes;
469
470 // only try to parse it if it starts with "#!" not only "#"
471 while ((lexer.peek_token ()->get_id () == HASH
472 && lexer.peek_token (1)->get_id () == EXCLAM)
473 || lexer.peek_token ()->get_id () == INNER_DOC_COMMENT)
474 {
475 AST::Attribute inner_attr = parse_inner_attribute ();
476
477 /* Ensure only valid inner attributes are added to the inner_attributes
478 * list */
479 if (!inner_attr.is_empty ())
480 {
481 inner_attributes.push_back (std::move (inner_attr));
482 }
483 else
484 {
485 /* If no more valid inner attributes, break out of loop (only
486 * contiguous inner attributes parsed). */
487 break;
488 }
489 }
490
491 inner_attributes.shrink_to_fit ();
492 return inner_attributes;
493 }
494
495 // Parse a inner or outer doc comment into an doc attribute
496 template <typename ManagedTokenSource>
497 std::tuple<AST::SimplePath, std::unique_ptr<AST::AttrInput>, location_t>
498 Parser<ManagedTokenSource>::parse_doc_comment ()
499 {
500 const_TokenPtr token = lexer.peek_token ();
501 location_t locus = token->get_locus ();
502 AST::SimplePathSegment segment (Values::Attributes::DOC, locus);
503 std::vector<AST::SimplePathSegment> segments;
504 segments.push_back (std::move (segment));
505 AST::SimplePath attr_path (std::move (segments), false, locus);
506 AST::LiteralExpr lit_expr (token->get_str (), AST::Literal::STRING,
507 PrimitiveCoreType::CORETYPE_STR, {}, locus);
508 std::unique_ptr<AST::AttrInput> attr_input (
509 new AST::AttrInputLiteral (std::move (lit_expr)));
510 lexer.skip_token ();
511 return std::make_tuple (std::move (attr_path), std::move (attr_input), locus);
512 }
513
514 // Parse a single inner attribute.
515 template <typename ManagedTokenSource>
516 AST::Attribute
517 Parser<ManagedTokenSource>::parse_inner_attribute ()
518 {
519 if (lexer.peek_token ()->get_id () == INNER_DOC_COMMENT)
520 {
521 auto values = parse_doc_comment ();
522 auto path = std::move (std::get<0> (values));
523 auto input = std::move (std::get<1> (values));
524 auto loc = std::get<2> (values);
525 return AST::Attribute (std::move (path), std::move (input), loc, true);
526 }
527
528 if (lexer.peek_token ()->get_id () != HASH)
529 {
530 Error error (lexer.peek_token ()->get_locus (),
531 "BUG: token %<#%> is missing, but %<parse_inner_attribute%> "
532 "was invoked");
533 add_error (std::move (error));
534
535 return AST::Attribute::create_empty ();
536 }
537 lexer.skip_token ();
538
539 if (lexer.peek_token ()->get_id () != EXCLAM)
540 {
541 Error error (lexer.peek_token ()->get_locus (),
542 "expected %<!%> or %<[%> for inner attribute");
543 add_error (std::move (error));
544
545 return AST::Attribute::create_empty ();
546 }
547 lexer.skip_token ();
548
549 if (!skip_token (LEFT_SQUARE))
550 return AST::Attribute::create_empty ();
551
552 auto values = parse_attribute_body ();
553
554 auto path = std::move (std::get<0> (values));
555 auto input = std::move (std::get<1> (values));
556 auto loc = std::get<2> (values);
557 auto actual_attribute
558 = AST::Attribute (std::move (path), std::move (input), loc, true);
559
560 if (!skip_token (RIGHT_SQUARE))
561 return AST::Attribute::create_empty ();
562
563 return actual_attribute;
564 }
565
566 // Parses the body of an attribute (inner or outer).
567 template <typename ManagedTokenSource>
568 std::tuple<AST::SimplePath, std::unique_ptr<AST::AttrInput>, location_t>
569 Parser<ManagedTokenSource>::parse_attribute_body ()
570 {
571 location_t locus = lexer.peek_token ()->get_locus ();
572
573 AST::SimplePath attr_path = parse_simple_path ();
574 // ensure path is valid to parse attribute input
575 if (attr_path.is_empty ())
576 {
577 Error error (lexer.peek_token ()->get_locus (),
578 "empty simple path in attribute");
579 add_error (std::move (error));
580
581 // Skip past potential further info in attribute (i.e. attr_input)
582 skip_after_end_attribute ();
583 return std::make_tuple (std::move (attr_path), nullptr, UNDEF_LOCATION);
584 }
585
586 std::unique_ptr<AST::AttrInput> attr_input = parse_attr_input ();
587 // AttrInput is allowed to be null, so no checks here
588
589 return std::make_tuple (std::move (attr_path), std::move (attr_input), locus);
590 }
591
592 /* Determines whether token is a valid simple path segment. This does not
593 * include scope resolution operators. */
594 inline bool
595 is_simple_path_segment (TokenId id)
596 {
597 switch (id)
598 {
599 case IDENTIFIER:
600 case SUPER:
601 case SELF:
602 case CRATE:
603 return true;
604 case DOLLAR_SIGN:
605 // assume that dollar sign leads to $crate
606 return true;
607 default:
608 return false;
609 }
610 }
611
612 // Parses a SimplePath AST node, if it exists. Does nothing otherwise.
613 template <typename ManagedTokenSource>
614 AST::SimplePath
615 Parser<ManagedTokenSource>::parse_simple_path ()
616 {
617 bool has_opening_scope_resolution = false;
618 location_t locus = UNKNOWN_LOCATION;
619
620 // don't parse anything if not a path upfront
621 if (!is_simple_path_segment (lexer.peek_token ()->get_id ())
622 && !is_simple_path_segment (lexer.peek_token (1)->get_id ()))
623 return AST::SimplePath::create_empty ();
624
625 /* Checks for opening scope resolution (i.e. global scope fully-qualified
626 * path) */
627 if (lexer.peek_token ()->get_id () == SCOPE_RESOLUTION)
628 {
629 has_opening_scope_resolution = true;
630
631 locus = lexer.peek_token ()->get_locus ();
632
633 lexer.skip_token ();
634 }
635
636 // Parse single required simple path segment
637 AST::SimplePathSegment segment = parse_simple_path_segment ();
638
639 // get location if not gotten already
640 if (locus == UNKNOWN_LOCATION)
641 locus = segment.get_locus ();
642
643 std::vector<AST::SimplePathSegment> segments;
644
645 // Return empty vector if first, actually required segment is an error
646 if (segment.is_error ())
647 return AST::SimplePath::create_empty ();
648
649 segments.push_back (std::move (segment));
650
651 // Parse all other simple path segments
652 while (lexer.peek_token ()->get_id () == SCOPE_RESOLUTION)
653 {
654 // Skip scope resolution operator
655 lexer.skip_token ();
656
657 AST::SimplePathSegment new_segment = parse_simple_path_segment ();
658
659 // Return path as currently constructed if segment in error state.
660 if (new_segment.is_error ())
661 break;
662
663 segments.push_back (std::move (new_segment));
664 }
665
666 // DEBUG: check for any empty segments
667 for (const auto &seg : segments)
668 {
669 if (seg.is_error ())
670 {
671 rust_debug (
672 "when parsing simple path, somehow empty path segment was "
673 "not filtered out. Path begins with '%s'",
674 segments.at (0).as_string ().c_str ());
675 }
676 }
677
678 return AST::SimplePath (std::move (segments), has_opening_scope_resolution,
679 locus);
680 /* TODO: now that is_simple_path_segment exists, could probably start
681 * actually making errors upon parse failure of segments and whatever */
682 }
683
684 /* Parses a single SimplePathSegment (does not handle the scope resolution
685 * operators) */
686 template <typename ManagedTokenSource>
687 AST::SimplePathSegment
688 Parser<ManagedTokenSource>::parse_simple_path_segment ()
689 {
690 using namespace Values;
691 const_TokenPtr t = lexer.peek_token ();
692 switch (t->get_id ())
693 {
694 case IDENTIFIER:
695 lexer.skip_token ();
696
697 return AST::SimplePathSegment (t->get_str (), t->get_locus ());
698 case SUPER:
699 lexer.skip_token ();
700
701 return AST::SimplePathSegment (Keywords::SUPER, t->get_locus ());
702 case SELF:
703 lexer.skip_token ();
704
705 return AST::SimplePathSegment (Keywords::SELF, t->get_locus ());
706 case CRATE:
707 lexer.skip_token ();
708
709 return AST::SimplePathSegment (Keywords::CRATE, t->get_locus ());
710 case DOLLAR_SIGN:
711 if (lexer.peek_token (1)->get_id () == CRATE)
712 {
713 lexer.skip_token (1);
714
715 return AST::SimplePathSegment ("$crate", t->get_locus ());
716 }
717 gcc_fallthrough ();
718 default:
719 // do nothing but inactivates warning from gcc when compiling
720 /* could put the rust_error_at thing here but fallthrough (from failing
721 * $crate condition) isn't completely obvious if it is. */
722
723 // test prevent error
724 return AST::SimplePathSegment::create_error ();
725 }
726 rust_unreachable ();
727 /*rust_error_at(
728 t->get_locus(), "invalid token '%s' in simple path segment",
729 t->get_token_description());*/
730 // this is not necessarily an error, e.g. end of path
731 // return AST::SimplePathSegment::create_error();
732 }
733
734 // Parses a PathIdentSegment - an identifier segment of a non-SimplePath path.
735 template <typename ManagedTokenSource>
736 AST::PathIdentSegment
737 Parser<ManagedTokenSource>::parse_path_ident_segment ()
738 {
739 const_TokenPtr t = lexer.peek_token ();
740 switch (t->get_id ())
741 {
742 case IDENTIFIER:
743 lexer.skip_token ();
744
745 return AST::PathIdentSegment (t->get_str (), t->get_locus ());
746 case SUPER:
747 lexer.skip_token ();
748
749 return AST::PathIdentSegment (Values::Keywords::SUPER, t->get_locus ());
750 case SELF:
751 lexer.skip_token ();
752
753 return AST::PathIdentSegment (Values::Keywords::SELF, t->get_locus ());
754 case SELF_ALIAS:
755 lexer.skip_token ();
756
757 return AST::PathIdentSegment (Values::Keywords::SELF_ALIAS,
758 t->get_locus ());
759 case CRATE:
760 lexer.skip_token ();
761
762 return AST::PathIdentSegment (Values::Keywords::CRATE, t->get_locus ());
763 case DOLLAR_SIGN:
764 if (lexer.peek_token (1)->get_id () == CRATE)
765 {
766 lexer.skip_token (1);
767
768 return AST::PathIdentSegment ("$crate", t->get_locus ());
769 }
770 gcc_fallthrough ();
771 default:
772 /* do nothing but inactivates warning from gcc when compiling
773 * could put the error_at thing here but fallthrough (from failing $crate
774 * condition) isn't completely obvious if it is. */
775
776 // test prevent error
777 return AST::PathIdentSegment::create_error ();
778 }
779 rust_unreachable ();
780 // not necessarily an error
781 }
782
783 // Parses an AttrInput AST node (polymorphic, as AttrInput is abstract)
784 template <typename ManagedTokenSource>
785 std::unique_ptr<AST::AttrInput>
786 Parser<ManagedTokenSource>::parse_attr_input ()
787 {
788 const_TokenPtr t = lexer.peek_token ();
789 switch (t->get_id ())
790 {
791 case LEFT_PAREN:
792 case LEFT_SQUARE:
793 case LEFT_CURLY: {
794 // must be a delimited token tree, so parse that
795 std::unique_ptr<AST::AttrInput> input_tree (
796 new AST::DelimTokenTree (parse_delim_token_tree ()));
797
798 // TODO: potential checks on DelimTokenTree before returning
799
800 return input_tree;
801 }
802 case EQUAL: {
803 // = LiteralExpr
804 lexer.skip_token ();
805
806 t = lexer.peek_token ();
807
808 // attempt to parse macro
809 // TODO: macros may/may not be allowed in attributes
810 // this is needed for "#[doc = include_str!(...)]"
811 if (is_simple_path_segment (t->get_id ()))
812 {
813 std::unique_ptr<AST::MacroInvocation> invoke
814 = parse_macro_invocation ({});
815
816 if (!invoke)
817 return nullptr;
818
819 return std::unique_ptr<AST::AttrInput> (
820 new AST::AttrInputMacro (std::move (invoke)));
821 }
822
823 /* Ensure token is a "literal expression" (literally only a literal
824 * token of any type) */
825 if (!t->is_literal ())
826 {
827 Error error (
828 t->get_locus (),
829 "unknown token %qs in attribute body - literal expected",
830 t->get_token_description ());
831 add_error (std::move (error));
832
833 skip_after_end_attribute ();
834 return nullptr;
835 }
836
837 AST::Literal::LitType lit_type = AST::Literal::STRING;
838 // Crappy mapping of token type to literal type
839 switch (t->get_id ())
840 {
841 case INT_LITERAL:
842 lit_type = AST::Literal::INT;
843 break;
844 case FLOAT_LITERAL:
845 lit_type = AST::Literal::FLOAT;
846 break;
847 case CHAR_LITERAL:
848 lit_type = AST::Literal::CHAR;
849 break;
850 case BYTE_CHAR_LITERAL:
851 lit_type = AST::Literal::BYTE;
852 break;
853 case BYTE_STRING_LITERAL:
854 lit_type = AST::Literal::BYTE_STRING;
855 break;
856 case RAW_STRING_LITERAL:
857 lit_type = AST::Literal::RAW_STRING;
858 break;
859 case STRING_LITERAL:
860 default:
861 lit_type = AST::Literal::STRING;
862 break; // TODO: raw string? don't eliminate it from lexer?
863 }
864
865 // create actual LiteralExpr
866 AST::LiteralExpr lit_expr (t->get_str (), lit_type, t->get_type_hint (),
867 {}, t->get_locus ());
868 lexer.skip_token ();
869
870 std::unique_ptr<AST::AttrInput> attr_input_lit (
871 new AST::AttrInputLiteral (std::move (lit_expr)));
872
873 // do checks or whatever? none required, really
874
875 // FIXME: shouldn't a skip token be required here?
876
877 return attr_input_lit;
878 }
879 break;
880 case RIGHT_SQUARE:
881 // means AttrInput is missing, which is allowed
882 return nullptr;
883 default:
884 add_error (
885 Error (t->get_locus (),
886 "unknown token %qs in attribute body - attribute input or "
887 "none expected",
888 t->get_token_description ()));
889
890 skip_after_end_attribute ();
891 return nullptr;
892 }
893 rust_unreachable ();
894 // TODO: find out how to stop gcc error on "no return value"
895 }
896
897 /* Returns true if the token id matches the delimiter type. Note that this only
898 * operates for END delimiter tokens. */
899 inline bool
900 token_id_matches_delims (TokenId token_id, AST::DelimType delim_type)
901 {
902 return ((token_id == RIGHT_PAREN && delim_type == AST::PARENS)
903 || (token_id == RIGHT_SQUARE && delim_type == AST::SQUARE)
904 || (token_id == RIGHT_CURLY && delim_type == AST::CURLY));
905 }
906
907 /* Returns true if the likely result of parsing the next few tokens is a path.
908 * Not guaranteed, though, especially in the case of syntax errors. */
909 inline bool
910 is_likely_path_next (TokenId next_token_id)
911 {
912 switch (next_token_id)
913 {
914 case IDENTIFIER:
915 case SUPER:
916 case SELF:
917 case SELF_ALIAS:
918 case CRATE:
919 // maybe - maybe do extra check. But then requires another TokenId.
920 case DOLLAR_SIGN:
921 case SCOPE_RESOLUTION:
922 return true;
923 default:
924 return false;
925 }
926 }
927
928 // Parses a delimited token tree
929 template <typename ManagedTokenSource>
930 AST::DelimTokenTree
931 Parser<ManagedTokenSource>::parse_delim_token_tree ()
932 {
933 const_TokenPtr t = lexer.peek_token ();
934 lexer.skip_token ();
935 location_t initial_loc = t->get_locus ();
936
937 // save delim type to ensure it is reused later
938 AST::DelimType delim_type = AST::PARENS;
939
940 // Map tokens to DelimType
941 switch (t->get_id ())
942 {
943 case LEFT_PAREN:
944 delim_type = AST::PARENS;
945 break;
946 case LEFT_SQUARE:
947 delim_type = AST::SQUARE;
948 break;
949 case LEFT_CURLY:
950 delim_type = AST::CURLY;
951 break;
952 default:
953 add_error (Error (t->get_locus (),
954 "unexpected token %qs - expecting delimiters (for a "
955 "delimited token tree)",
956 t->get_token_description ()));
957
958 return AST::DelimTokenTree::create_empty ();
959 }
960
961 // parse actual token tree vector - 0 or more
962 std::vector<std::unique_ptr<AST::TokenTree>> token_trees_in_tree;
963 auto delim_open
964 = std::unique_ptr<AST::Token> (new AST::Token (std::move (t)));
965 token_trees_in_tree.push_back (std::move (delim_open));
966
967 // repeat loop until finding the matching delimiter
968 t = lexer.peek_token ();
969 while (!token_id_matches_delims (t->get_id (), delim_type)
970 && t->get_id () != END_OF_FILE)
971 {
972 std::unique_ptr<AST::TokenTree> tok_tree = parse_token_tree ();
973
974 if (tok_tree == nullptr)
975 {
976 // TODO: is this error handling appropriate?
977 Error error (
978 t->get_locus (),
979 "failed to parse token tree in delimited token tree - found %qs",
980 t->get_token_description ());
981 add_error (std::move (error));
982
983 return AST::DelimTokenTree::create_empty ();
984 }
985
986 token_trees_in_tree.push_back (std::move (tok_tree));
987
988 // lexer.skip_token();
989 t = lexer.peek_token ();
990 }
991 auto delim_close
992 = std::unique_ptr<AST::Token> (new AST::Token (std::move (t)));
993 token_trees_in_tree.push_back (std::move (delim_close));
994
995 AST::DelimTokenTree token_tree (delim_type, std::move (token_trees_in_tree),
996 initial_loc);
997
998 // parse end delimiters
999 t = lexer.peek_token ();
1000
1001 if (token_id_matches_delims (t->get_id (), delim_type))
1002 {
1003 // tokens match opening delimiter, so skip.
1004 lexer.skip_token ();
1005
1006 // DEBUG
1007 rust_debug ("finished parsing new delim token tree - peeked token is now "
1008 "'%s' while t is '%s'",
1009 lexer.peek_token ()->get_token_description (),
1010 t->get_token_description ());
1011
1012 return token_tree;
1013 }
1014 else
1015 {
1016 // tokens don't match opening delimiters, so produce error
1017 Error error (t->get_locus (),
1018 "unexpected token %qs - expecting closing delimiter %qs "
1019 "(for a delimited token tree)",
1020 t->get_token_description (),
1021 (delim_type == AST::PARENS
1022 ? ")"
1023 : (delim_type == AST::SQUARE ? "]" : "}")));
1024 add_error (std::move (error));
1025
1026 /* return empty token tree despite possibly parsing valid token tree -
1027 * TODO is this a good idea? */
1028 return AST::DelimTokenTree::create_empty ();
1029 }
1030 }
1031
1032 // Parses an identifier/keyword as a Token
1033 template <typename ManagedTokenSource>
1034 std::unique_ptr<AST::Token>
1035 Parser<ManagedTokenSource>::parse_identifier_or_keyword_token ()
1036 {
1037 const_TokenPtr t = lexer.peek_token ();
1038
1039 if (t->get_id () == IDENTIFIER || token_id_is_keyword (t->get_id ()))
1040 {
1041 lexer.skip_token ();
1042 return std::unique_ptr<AST::Token> (new AST::Token (std::move (t)));
1043 }
1044 else
1045 {
1046 return nullptr;
1047 }
1048 }
1049
1050 /* Parses a TokenTree syntactical production. This is either a delimited token
1051 * tree or a non-delimiter token. */
1052 template <typename ManagedTokenSource>
1053 std::unique_ptr<AST::TokenTree>
1054 Parser<ManagedTokenSource>::parse_token_tree ()
1055 {
1056 const_TokenPtr t = lexer.peek_token ();
1057
1058 switch (t->get_id ())
1059 {
1060 case LEFT_PAREN:
1061 case LEFT_SQUARE:
1062 case LEFT_CURLY:
1063 // Parse delimited token tree
1064 // TODO: use move rather than copy constructor
1065 return std::unique_ptr<AST::DelimTokenTree> (
1066 new AST::DelimTokenTree (parse_delim_token_tree ()));
1067 case RIGHT_PAREN:
1068 case RIGHT_SQUARE:
1069 case RIGHT_CURLY:
1070 // error - should not be called when this a token
1071 add_error (
1072 Error (t->get_locus (),
1073 "unexpected closing delimiter %qs - token tree requires "
1074 "either paired delimiters or non-delimiter tokens",
1075 t->get_token_description ()));
1076
1077 lexer.skip_token ();
1078 return nullptr;
1079 default:
1080 // parse token itself as TokenTree
1081 lexer.skip_token ();
1082 return std::unique_ptr<AST::Token> (new AST::Token (std::move (t)));
1083 }
1084 }
1085
1086 template <typename ManagedTokenSource>
1087 bool
1088 Parser<ManagedTokenSource>::is_macro_rules_def (const_TokenPtr t)
1089 {
1090 auto macro_name = lexer.peek_token (2)->get_id ();
1091
1092 bool allowed_macro_name = (macro_name == IDENTIFIER || macro_name == TRY);
1093
1094 return t->get_str () == Values::WeakKeywords::MACRO_RULES
1095 && lexer.peek_token (1)->get_id () == EXCLAM && allowed_macro_name;
1096 }
1097
1098 // Parses a single item
1099 template <typename ManagedTokenSource>
1100 std::unique_ptr<AST::Item>
1101 Parser<ManagedTokenSource>::parse_item (bool called_from_statement)
1102 {
1103 // has a "called_from_statement" parameter for better error message handling
1104
1105 // parse outer attributes for item
1106 AST::AttrVec outer_attrs = parse_outer_attributes ();
1107 const_TokenPtr t = lexer.peek_token ();
1108
1109 switch (t->get_id ())
1110 {
1111 case END_OF_FILE:
1112 // not necessarily an error, unless we just read outer
1113 // attributes which needs to be attached
1114 if (!outer_attrs.empty ())
1115 {
1116 Rust::AST::Attribute attr = outer_attrs.back ();
1117 Error error (attr.get_locus (),
1118 "expected item after outer attribute or doc comment");
1119 add_error (std::move (error));
1120 }
1121 return nullptr;
1122
1123 case ASYNC:
1124 case PUB:
1125 case MOD:
1126 case EXTERN_KW:
1127 case USE:
1128 case FN_KW:
1129 case TYPE:
1130 case STRUCT_KW:
1131 case ENUM_KW:
1132 case CONST:
1133 case STATIC_KW:
1134 case AUTO:
1135 case TRAIT:
1136 case IMPL:
1137 case MACRO:
1138 /* TODO: implement union keyword but not really because of
1139 * context-dependence crappy hack way to parse a union written below to
1140 * separate it from the good code. */
1141 // case UNION:
1142 case UNSAFE: // maybe - unsafe traits are a thing
1143 // if any of these (should be all possible VisItem prefixes), parse a
1144 // VisItem
1145 return parse_vis_item (std::move (outer_attrs));
1146 break;
1147 case SUPER:
1148 case SELF:
1149 case CRATE:
1150 case DOLLAR_SIGN:
1151 // almost certainly macro invocation semi
1152 return parse_macro_invocation_semi (std::move (outer_attrs));
1153 break;
1154 // crappy hack to do union "keyword"
1155 case IDENTIFIER:
1156 // TODO: ensure std::string and literal comparison works
1157 if (t->get_str () == Values::WeakKeywords::UNION
1158 && lexer.peek_token (1)->get_id () == IDENTIFIER)
1159 {
1160 return parse_vis_item (std::move (outer_attrs));
1161 // or should this go straight to parsing union?
1162 }
1163 else if (t->get_str () == Values::WeakKeywords::DEFAULT
1164 && lexer.peek_token (1)->get_id () != EXCLAM)
1165 {
1166 add_error (Error (t->get_locus (),
1167 "%qs is only allowed on items within %qs blocks",
1168 "default", "impl"));
1169 return nullptr;
1170 }
1171 else if (is_macro_rules_def (t))
1172 {
1173 // macro_rules! macro item
1174 return parse_macro_rules_def (std::move (outer_attrs));
1175 }
1176 else if (lexer.peek_token (1)->get_id () == SCOPE_RESOLUTION
1177 || lexer.peek_token (1)->get_id () == EXCLAM)
1178 {
1179 /* path (probably) or macro invocation, so probably a macro invocation
1180 * semi */
1181 return parse_macro_invocation_semi (std::move (outer_attrs));
1182 }
1183 gcc_fallthrough ();
1184 default:
1185 // otherwise unrecognised
1186 add_error (Error (t->get_locus (),
1187 "unrecognised token %qs for start of %s",
1188 t->get_token_description (),
1189 called_from_statement ? "statement" : "item"));
1190
1191 // skip somewhere?
1192 return nullptr;
1193 break;
1194 }
1195 }
1196
1197 // Parses a contiguous block of outer attributes.
1198 template <typename ManagedTokenSource>
1199 AST::AttrVec
1200 Parser<ManagedTokenSource>::parse_outer_attributes ()
1201 {
1202 AST::AttrVec outer_attributes;
1203
1204 while (lexer.peek_token ()->get_id ()
1205 == HASH /* Can also be #!, which catches errors. */
1206 || lexer.peek_token ()->get_id () == OUTER_DOC_COMMENT
1207 || lexer.peek_token ()->get_id ()
1208 == INNER_DOC_COMMENT) /* For error handling. */
1209 {
1210 AST::Attribute outer_attr = parse_outer_attribute ();
1211
1212 /* Ensure only valid outer attributes are added to the outer_attributes
1213 * list */
1214 if (!outer_attr.is_empty ())
1215 {
1216 outer_attributes.push_back (std::move (outer_attr));
1217 }
1218 else
1219 {
1220 /* If no more valid outer attributes, break out of loop (only
1221 * contiguous outer attributes parsed). */
1222 break;
1223 }
1224 }
1225
1226 outer_attributes.shrink_to_fit ();
1227 return outer_attributes;
1228
1229 /* TODO: this shares basically all code with parse_inner_attributes except
1230 * function call - find way of making it more modular? function pointer? */
1231 }
1232
1233 // Parse a single outer attribute.
1234 template <typename ManagedTokenSource>
1235 AST::Attribute
1236 Parser<ManagedTokenSource>::parse_outer_attribute ()
1237 {
1238 if (lexer.peek_token ()->get_id () == OUTER_DOC_COMMENT)
1239 {
1240 auto values = parse_doc_comment ();
1241 auto path = std::move (std::get<0> (values));
1242 auto input = std::move (std::get<1> (values));
1243 auto loc = std::get<2> (values);
1244 return AST::Attribute (std::move (path), std::move (input), loc, false);
1245 }
1246
1247 if (lexer.peek_token ()->get_id () == INNER_DOC_COMMENT)
1248 {
1249 Error error (
1250 lexer.peek_token ()->get_locus (), ErrorCode::E0753,
1251 "expected outer doc comment, inner doc (%<//!%> or %</*!%>) only "
1252 "allowed at start of item "
1253 "and before any outer attribute or doc (%<#[%>, %<///%> or %</**%>)");
1254 add_error (std::move (error));
1255 lexer.skip_token ();
1256 return AST::Attribute::create_empty ();
1257 }
1258
1259 /* OuterAttribute -> '#' '[' Attr ']' */
1260
1261 if (lexer.peek_token ()->get_id () != HASH)
1262 return AST::Attribute::create_empty ();
1263
1264 lexer.skip_token ();
1265
1266 TokenId id = lexer.peek_token ()->get_id ();
1267 if (id != LEFT_SQUARE)
1268 {
1269 if (id == EXCLAM)
1270 {
1271 // this is inner attribute syntax, so throw error
1272 // inner attributes were either already parsed or not allowed here.
1273 Error error (
1274 lexer.peek_token ()->get_locus (),
1275 "token %<!%> found, indicating inner attribute definition. Inner "
1276 "attributes are not possible at this location");
1277 add_error (std::move (error));
1278 }
1279 return AST::Attribute::create_empty ();
1280 }
1281
1282 lexer.skip_token ();
1283
1284 auto values = parse_attribute_body ();
1285 auto path = std::move (std::get<0> (values));
1286 auto input = std::move (std::get<1> (values));
1287 auto loc = std::get<2> (values);
1288 auto actual_attribute
1289 = AST::Attribute (std::move (path), std::move (input), loc, false);
1290
1291 if (lexer.peek_token ()->get_id () != RIGHT_SQUARE)
1292 return AST::Attribute::create_empty ();
1293
1294 lexer.skip_token ();
1295
1296 return actual_attribute;
1297 }
1298
1299 // Parses a VisItem (item that can have non-default visibility).
1300 template <typename ManagedTokenSource>
1301 std::unique_ptr<AST::VisItem>
1302 Parser<ManagedTokenSource>::parse_vis_item (AST::AttrVec outer_attrs)
1303 {
1304 // parse visibility, which may or may not exist
1305 AST::Visibility vis = parse_visibility ();
1306
1307 // select VisItem to create depending on keyword
1308 const_TokenPtr t = lexer.peek_token ();
1309
1310 switch (t->get_id ())
1311 {
1312 case MOD:
1313 return parse_module (std::move (vis), std::move (outer_attrs));
1314 case EXTERN_KW:
1315 // lookahead to resolve syntactical production
1316 t = lexer.peek_token (1);
1317
1318 switch (t->get_id ())
1319 {
1320 case CRATE:
1321 return parse_extern_crate (std::move (vis), std::move (outer_attrs));
1322 case FN_KW: // extern function
1323 return parse_function (std::move (vis), std::move (outer_attrs));
1324 case LEFT_CURLY: // extern block
1325 return parse_extern_block (std::move (vis), std::move (outer_attrs));
1326 case STRING_LITERAL: // for specifying extern ABI
1327 // could be extern block or extern function, so more lookahead
1328 t = lexer.peek_token (2);
1329
1330 switch (t->get_id ())
1331 {
1332 case FN_KW:
1333 return parse_function (std::move (vis), std::move (outer_attrs));
1334 case LEFT_CURLY:
1335 return parse_extern_block (std::move (vis),
1336 std::move (outer_attrs));
1337 default:
1338 add_error (
1339 Error (t->get_locus (),
1340 "unexpected token %qs in some sort of extern production",
1341 t->get_token_description ()));
1342
1343 lexer.skip_token (2); // TODO: is this right thing to do?
1344 return nullptr;
1345 }
1346 default:
1347 add_error (
1348 Error (t->get_locus (),
1349 "unexpected token %qs in some sort of extern production",
1350 t->get_token_description ()));
1351
1352 lexer.skip_token (1); // TODO: is this right thing to do?
1353 return nullptr;
1354 }
1355 case USE:
1356 return parse_use_decl (std::move (vis), std::move (outer_attrs));
1357 case FN_KW:
1358 return parse_function (std::move (vis), std::move (outer_attrs));
1359 case TYPE:
1360 return parse_type_alias (std::move (vis), std::move (outer_attrs));
1361 case STRUCT_KW:
1362 return parse_struct (std::move (vis), std::move (outer_attrs));
1363 case ENUM_KW:
1364 return parse_enum (std::move (vis), std::move (outer_attrs));
1365 // TODO: implement union keyword but not really because of
1366 // context-dependence case UNION: crappy hack to do union "keyword"
1367 case IDENTIFIER:
1368 if (t->get_str () == Values::WeakKeywords::UNION
1369 && lexer.peek_token (1)->get_id () == IDENTIFIER)
1370 {
1371 return parse_union (std::move (vis), std::move (outer_attrs));
1372 // or should item switch go straight to parsing union?
1373 }
1374 else
1375 {
1376 break;
1377 }
1378 case CONST:
1379 // lookahead to resolve syntactical production
1380 t = lexer.peek_token (1);
1381
1382 switch (t->get_id ())
1383 {
1384 case IDENTIFIER:
1385 case UNDERSCORE:
1386 return parse_const_item (std::move (vis), std::move (outer_attrs));
1387 case ASYNC:
1388 return parse_async_item (std::move (vis), std::move (outer_attrs));
1389 case UNSAFE:
1390 case EXTERN_KW:
1391 case FN_KW:
1392 return parse_function (std::move (vis), std::move (outer_attrs));
1393 default:
1394 add_error (
1395 Error (t->get_locus (),
1396 "unexpected token %qs in some sort of const production",
1397 t->get_token_description ()));
1398
1399 lexer.skip_token (1); // TODO: is this right thing to do?
1400 return nullptr;
1401 }
1402 // for async functions
1403 case ASYNC:
1404 return parse_async_item (std::move (vis), std::move (outer_attrs));
1405
1406 case STATIC_KW:
1407 return parse_static_item (std::move (vis), std::move (outer_attrs));
1408 case AUTO:
1409 case TRAIT:
1410 return parse_trait (std::move (vis), std::move (outer_attrs));
1411 case IMPL:
1412 return parse_impl (std::move (vis), std::move (outer_attrs));
1413 case UNSAFE: // unsafe traits, unsafe functions, unsafe impls (trait impls),
1414 // lookahead to resolve syntactical production
1415 t = lexer.peek_token (1);
1416
1417 switch (t->get_id ())
1418 {
1419 case AUTO:
1420 case TRAIT:
1421 return parse_trait (std::move (vis), std::move (outer_attrs));
1422 case EXTERN_KW:
1423 case FN_KW:
1424 return parse_function (std::move (vis), std::move (outer_attrs));
1425 case IMPL:
1426 return parse_impl (std::move (vis), std::move (outer_attrs));
1427 case MOD:
1428 return parse_module (std::move (vis), std::move (outer_attrs));
1429 default:
1430 add_error (
1431 Error (t->get_locus (),
1432 "unexpected token %qs in some sort of unsafe production",
1433 t->get_token_description ()));
1434
1435 lexer.skip_token (1); // TODO: is this right thing to do?
1436 return nullptr;
1437 }
1438 case MACRO:
1439 return parse_decl_macro_def (std::move (vis), std::move (outer_attrs));
1440 default:
1441 // otherwise vis item clearly doesn't exist, which is not an error
1442 // has a catch-all post-switch return to allow other breaks to occur
1443 break;
1444 }
1445 return nullptr;
1446 }
1447
1448 template <typename ManagedTokenSource>
1449 std::unique_ptr<AST::Function>
1450 Parser<ManagedTokenSource>::parse_async_item (AST::Visibility vis,
1451 AST::AttrVec outer_attrs)
1452 {
1453 auto offset = (lexer.peek_token ()->get_id () == CONST) ? 1 : 0;
1454 const_TokenPtr t = lexer.peek_token (offset);
1455
1456 if (get_rust_edition () == Edition::E2015)
1457 {
1458 add_error (Error (t->get_locus (), ErrorCode::E0670,
1459 "%<async fn%> is not permitted in Rust 2015"));
1460 add_error (
1461 Error::Hint (t->get_locus (),
1462 "to use %<async fn%>, switch to Rust 2018 or later"));
1463 }
1464
1465 t = lexer.peek_token (offset + 1);
1466
1467 switch (t->get_id ())
1468 {
1469 case UNSAFE:
1470 case FN_KW:
1471 return parse_function (std::move (vis), std::move (outer_attrs));
1472
1473 default:
1474 add_error (
1475 Error (t->get_locus (), "expected item, found keyword %<async%>"));
1476
1477 lexer.skip_token (1);
1478 return nullptr;
1479 }
1480 }
1481
1482 // Parses a macro rules definition syntax extension whatever thing.
1483 template <typename ManagedTokenSource>
1484 std::unique_ptr<AST::MacroRulesDefinition>
1485 Parser<ManagedTokenSource>::parse_macro_rules_def (AST::AttrVec outer_attrs)
1486 {
1487 // ensure that first token is identifier saying "macro_rules"
1488 const_TokenPtr t = lexer.peek_token ();
1489 if (t->get_id () != IDENTIFIER
1490 || t->get_str () != Values::WeakKeywords::MACRO_RULES)
1491 {
1492 Error error (
1493 t->get_locus (),
1494 "macro rules definition does not start with %<macro_rules%>");
1495 add_error (std::move (error));
1496
1497 // skip after somewhere?
1498 return nullptr;
1499 }
1500 lexer.skip_token ();
1501 location_t macro_locus = t->get_locus ();
1502
1503 if (!skip_token (EXCLAM))
1504 {
1505 // skip after somewhere?
1506 return nullptr;
1507 }
1508
1509 // parse macro name
1510 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
1511 if (ident_tok == nullptr)
1512 {
1513 return nullptr;
1514 }
1515 Identifier rule_name{ident_tok};
1516
1517 // DEBUG
1518 rust_debug ("in macro rules def, about to parse parens.");
1519
1520 // save delim type to ensure it is reused later
1521 AST::DelimType delim_type = AST::PARENS;
1522
1523 // Map tokens to DelimType
1524 t = lexer.peek_token ();
1525 switch (t->get_id ())
1526 {
1527 case LEFT_PAREN:
1528 delim_type = AST::PARENS;
1529 break;
1530 case LEFT_SQUARE:
1531 delim_type = AST::SQUARE;
1532 break;
1533 case LEFT_CURLY:
1534 delim_type = AST::CURLY;
1535 break;
1536 default:
1537 add_error (Error (t->get_locus (),
1538 "unexpected token %qs - expecting delimiters (for a "
1539 "macro rules definition)",
1540 t->get_token_description ()));
1541
1542 return nullptr;
1543 }
1544 lexer.skip_token ();
1545
1546 // parse actual macro rules
1547 std::vector<AST::MacroRule> macro_rules;
1548
1549 // must be at least one macro rule, so parse it
1550 AST::MacroRule initial_rule = parse_macro_rule ();
1551 if (initial_rule.is_error ())
1552 {
1553 Error error (lexer.peek_token ()->get_locus (),
1554 "required first macro rule in macro rules definition "
1555 "could not be parsed");
1556 add_error (std::move (error));
1557
1558 // skip after somewhere?
1559 return nullptr;
1560 }
1561 macro_rules.push_back (std::move (initial_rule));
1562
1563 // DEBUG
1564 rust_debug ("successfully pushed back initial macro rule");
1565
1566 t = lexer.peek_token ();
1567 // parse macro rules
1568 while (t->get_id () == SEMICOLON)
1569 {
1570 // skip semicolon
1571 lexer.skip_token ();
1572
1573 // don't parse if end of macro rules
1574 if (token_id_matches_delims (lexer.peek_token ()->get_id (), delim_type))
1575 {
1576 // DEBUG
1577 rust_debug (
1578 "broke out of parsing macro rules loop due to finding delim");
1579
1580 break;
1581 }
1582
1583 // try to parse next rule
1584 AST::MacroRule rule = parse_macro_rule ();
1585 if (rule.is_error ())
1586 {
1587 Error error (lexer.peek_token ()->get_locus (),
1588 "failed to parse macro rule in macro rules definition");
1589 add_error (std::move (error));
1590
1591 return nullptr;
1592 }
1593
1594 macro_rules.push_back (std::move (rule));
1595
1596 // DEBUG
1597 rust_debug ("successfully pushed back another macro rule");
1598
1599 t = lexer.peek_token ();
1600 }
1601
1602 // parse end delimiters
1603 t = lexer.peek_token ();
1604 if (token_id_matches_delims (t->get_id (), delim_type))
1605 {
1606 // tokens match opening delimiter, so skip.
1607 lexer.skip_token ();
1608
1609 if (delim_type != AST::CURLY)
1610 {
1611 // skip semicolon at end of non-curly macro definitions
1612 if (!skip_token (SEMICOLON))
1613 {
1614 // as this is the end, allow recovery (probably) - may change
1615 return std::unique_ptr<AST::MacroRulesDefinition> (
1616 AST::MacroRulesDefinition::mbe (
1617 std::move (rule_name), delim_type, std::move (macro_rules),
1618 std::move (outer_attrs), macro_locus));
1619 }
1620 }
1621
1622 return std::unique_ptr<AST::MacroRulesDefinition> (
1623 AST::MacroRulesDefinition::mbe (std::move (rule_name), delim_type,
1624 std::move (macro_rules),
1625 std::move (outer_attrs), macro_locus));
1626 }
1627 else
1628 {
1629 // tokens don't match opening delimiters, so produce error
1630 Error error (t->get_locus (),
1631 "unexpected token %qs - expecting closing delimiter %qs "
1632 "(for a macro rules definition)",
1633 t->get_token_description (),
1634 (delim_type == AST::PARENS
1635 ? ")"
1636 : (delim_type == AST::SQUARE ? "]" : "}")));
1637 add_error (std::move (error));
1638
1639 /* return empty macro definiton despite possibly parsing mostly valid one
1640 * - TODO is this a good idea? */
1641 return nullptr;
1642 }
1643 }
1644
1645 // Parses a declarative macro 2.0 definition.
1646 template <typename ManagedTokenSource>
1647 std::unique_ptr<AST::MacroRulesDefinition>
1648 Parser<ManagedTokenSource>::parse_decl_macro_def (AST::Visibility vis,
1649 AST::AttrVec outer_attrs)
1650 {
1651 // ensure that first token is identifier saying "macro"
1652 const_TokenPtr t = lexer.peek_token ();
1653 if (t->get_id () != MACRO)
1654 {
1655 Error error (
1656 t->get_locus (),
1657 "declarative macro definition does not start with %<macro%>");
1658 add_error (std::move (error));
1659
1660 // skip after somewhere?
1661 return nullptr;
1662 }
1663 lexer.skip_token ();
1664 location_t macro_locus = t->get_locus ();
1665
1666 // parse macro name
1667 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
1668 if (ident_tok == nullptr)
1669 {
1670 return nullptr;
1671 }
1672 Identifier rule_name{ident_tok};
1673
1674 t = lexer.peek_token ();
1675 if (t->get_id () == LEFT_PAREN)
1676 {
1677 // single definiton of macro rule
1678 // e.g. `macro foo($e:expr) {}`
1679
1680 // parse macro matcher
1681 location_t locus = lexer.peek_token ()->get_locus ();
1682 AST::MacroMatcher matcher = parse_macro_matcher ();
1683 if (matcher.is_error ())
1684 return nullptr;
1685
1686 // check delimiter of macro matcher
1687 if (matcher.get_delim_type () != AST::DelimType::PARENS)
1688 {
1689 Error error (locus, "only parenthesis can be used for a macro "
1690 "matcher in declarative macro definition");
1691 add_error (std::move (error));
1692 return nullptr;
1693 }
1694
1695 location_t transcriber_loc = lexer.peek_token ()->get_locus ();
1696 AST::DelimTokenTree delim_tok_tree = parse_delim_token_tree ();
1697 AST::MacroTranscriber transcriber (delim_tok_tree, transcriber_loc);
1698
1699 if (transcriber.get_token_tree ().get_delim_type ()
1700 != AST::DelimType::CURLY)
1701 {
1702 Error error (transcriber_loc,
1703 "only braces can be used for a macro transcriber "
1704 "in declarative macro definition");
1705 add_error (std::move (error));
1706 return nullptr;
1707 }
1708
1709 AST::MacroRule macro_rule
1710 = AST::MacroRule (std::move (matcher), std::move (transcriber), locus);
1711 std::vector<AST::MacroRule> macro_rules;
1712 macro_rules.push_back (macro_rule);
1713
1714 return std::unique_ptr<AST::MacroRulesDefinition> (
1715 AST::MacroRulesDefinition::decl_macro (std::move (rule_name),
1716 macro_rules,
1717 std::move (outer_attrs),
1718 macro_locus, vis));
1719 }
1720 else if (t->get_id () == LEFT_CURLY)
1721 {
1722 // multiple definitions of macro rule separated by comma
1723 // e.g. `macro foo { () => {}, ($e:expr) => {}, }`
1724
1725 // parse left curly
1726 const_TokenPtr left_curly = expect_token (LEFT_CURLY);
1727 if (left_curly == nullptr)
1728 {
1729 return nullptr;
1730 }
1731
1732 // parse actual macro rules
1733 std::vector<AST::MacroRule> macro_rules;
1734
1735 // must be at least one macro rule, so parse it
1736 AST::MacroRule initial_rule = parse_macro_rule ();
1737 if (initial_rule.is_error ())
1738 {
1739 Error error (
1740 lexer.peek_token ()->get_locus (),
1741 "required first macro rule in declarative macro definition "
1742 "could not be parsed");
1743 add_error (std::move (error));
1744
1745 // skip after somewhere?
1746 return nullptr;
1747 }
1748 macro_rules.push_back (std::move (initial_rule));
1749
1750 t = lexer.peek_token ();
1751 // parse macro rules
1752 while (t->get_id () == COMMA)
1753 {
1754 // skip comma
1755 lexer.skip_token ();
1756
1757 // don't parse if end of macro rules
1758 if (token_id_matches_delims (lexer.peek_token ()->get_id (),
1759 AST::CURLY))
1760 {
1761 break;
1762 }
1763
1764 // try to parse next rule
1765 AST::MacroRule rule = parse_macro_rule ();
1766 if (rule.is_error ())
1767 {
1768 Error error (
1769 lexer.peek_token ()->get_locus (),
1770 "failed to parse macro rule in declarative macro definition");
1771 add_error (std::move (error));
1772
1773 return nullptr;
1774 }
1775
1776 macro_rules.push_back (std::move (rule));
1777
1778 t = lexer.peek_token ();
1779 }
1780
1781 // parse right curly
1782 const_TokenPtr right_curly = expect_token (RIGHT_CURLY);
1783 if (right_curly == nullptr)
1784 {
1785 return nullptr;
1786 }
1787
1788 return std::unique_ptr<AST::MacroRulesDefinition> (
1789 AST::MacroRulesDefinition::decl_macro (std::move (rule_name),
1790 std::move (macro_rules),
1791 std::move (outer_attrs),
1792 macro_locus, vis));
1793 }
1794 else
1795 {
1796 add_error (Error (t->get_locus (),
1797 "unexpected token %qs - expecting delimiters "
1798 "(for a declarative macro definiton)",
1799 t->get_token_description ()));
1800 return nullptr;
1801 }
1802 }
1803
1804 // Parses a semi-coloned (except for full block) macro invocation item.
1805 template <typename ManagedTokenSource>
1806 std::unique_ptr<AST::MacroInvocation>
1807 Parser<ManagedTokenSource>::parse_macro_invocation_semi (
1808 AST::AttrVec outer_attrs)
1809 {
1810 location_t macro_locus = lexer.peek_token ()->get_locus ();
1811 AST::SimplePath path = parse_simple_path ();
1812
1813 if (!skip_token (EXCLAM))
1814 {
1815 // skip after somewhere?
1816 return nullptr;
1817 }
1818
1819 // save delim type to ensure it is reused later
1820 AST::DelimType delim_type = AST::PARENS;
1821
1822 // Map tokens to DelimType
1823 const_TokenPtr t = lexer.peek_token ();
1824 switch (t->get_id ())
1825 {
1826 case LEFT_PAREN:
1827 delim_type = AST::PARENS;
1828 break;
1829 case LEFT_SQUARE:
1830 delim_type = AST::SQUARE;
1831 break;
1832 case LEFT_CURLY:
1833 delim_type = AST::CURLY;
1834 break;
1835 default:
1836 add_error (Error (t->get_locus (),
1837 "unexpected token %qs - expecting delimiters (for a "
1838 "macro invocation semi body)",
1839 t->get_token_description ()));
1840
1841 return nullptr;
1842 }
1843 location_t tok_tree_locus = t->get_locus ();
1844 lexer.skip_token ();
1845
1846 // parse actual token trees
1847 std::vector<std::unique_ptr<AST::TokenTree>> token_trees;
1848 auto delim_open
1849 = std::unique_ptr<AST::Token> (new AST::Token (std::move (t)));
1850 token_trees.push_back (std::move (delim_open));
1851
1852 t = lexer.peek_token ();
1853 // parse token trees until the initial delimiter token is found again
1854 while (!token_id_matches_delims (t->get_id (), delim_type))
1855 {
1856 std::unique_ptr<AST::TokenTree> tree = parse_token_tree ();
1857
1858 if (tree == nullptr)
1859 {
1860 Error error (t->get_locus (),
1861 "failed to parse token tree for macro invocation semi "
1862 "- found %qs",
1863 t->get_token_description ());
1864 add_error (std::move (error));
1865
1866 return nullptr;
1867 }
1868
1869 token_trees.push_back (std::move (tree));
1870
1871 t = lexer.peek_token ();
1872 }
1873 auto delim_close
1874 = std::unique_ptr<AST::Token> (new AST::Token (std::move (t)));
1875 token_trees.push_back (std::move (delim_close));
1876
1877 AST::DelimTokenTree delim_tok_tree (delim_type, std::move (token_trees),
1878 tok_tree_locus);
1879 AST::MacroInvocData invoc_data (std::move (path), std::move (delim_tok_tree));
1880
1881 // parse end delimiters
1882 t = lexer.peek_token ();
1883 if (token_id_matches_delims (t->get_id (), delim_type))
1884 {
1885 // tokens match opening delimiter, so skip.
1886 lexer.skip_token ();
1887
1888 if (delim_type != AST::CURLY)
1889 {
1890 // skip semicolon at end of non-curly macro invocation semis
1891 if (!skip_token (SEMICOLON))
1892 {
1893 // as this is the end, allow recovery (probably) - may change
1894
1895 return AST::MacroInvocation::Regular (std::move (invoc_data),
1896 std::move (outer_attrs),
1897 macro_locus, true);
1898 }
1899 }
1900
1901 // DEBUG:
1902 rust_debug ("skipped token is '%s', next token (current peek) is '%s'",
1903 t->get_token_description (),
1904 lexer.peek_token ()->get_token_description ());
1905
1906 return AST::MacroInvocation::Regular (std::move (invoc_data),
1907 std::move (outer_attrs),
1908 macro_locus, true);
1909 }
1910 else
1911 {
1912 // tokens don't match opening delimiters, so produce error
1913 Error error (t->get_locus (),
1914 "unexpected token %qs - expecting closing delimiter %qs "
1915 "(for a macro invocation semi)",
1916 t->get_token_description (),
1917 (delim_type == AST::PARENS
1918 ? ")"
1919 : (delim_type == AST::SQUARE ? "]" : "}")));
1920 add_error (std::move (error));
1921
1922 /* return empty macro invocation despite possibly parsing mostly valid one
1923 * - TODO is this a good idea? */
1924 return nullptr;
1925 }
1926 }
1927
1928 // Parses a non-semicoloned macro invocation (i.e. as pattern or expression).
1929 template <typename ManagedTokenSource>
1930 std::unique_ptr<AST::MacroInvocation>
1931 Parser<ManagedTokenSource>::parse_macro_invocation (AST::AttrVec outer_attrs)
1932 {
1933 // parse macro path
1934 AST::SimplePath macro_path = parse_simple_path ();
1935 if (macro_path.is_empty ())
1936 {
1937 Error error (lexer.peek_token ()->get_locus (),
1938 "failed to parse macro invocation path");
1939 add_error (std::move (error));
1940
1941 // skip?
1942 return nullptr;
1943 }
1944
1945 if (!skip_token (EXCLAM))
1946 {
1947 // skip after somewhere?
1948 return nullptr;
1949 }
1950
1951 // parse internal delim token tree
1952 AST::DelimTokenTree delim_tok_tree = parse_delim_token_tree ();
1953
1954 location_t macro_locus = macro_path.get_locus ();
1955
1956 return AST::MacroInvocation::Regular (
1957 AST::MacroInvocData (std::move (macro_path), std::move (delim_tok_tree)),
1958 std::move (outer_attrs), macro_locus);
1959 }
1960
1961 // Parses a macro rule definition - does not parse semicolons.
1962 template <typename ManagedTokenSource>
1963 AST::MacroRule
1964 Parser<ManagedTokenSource>::parse_macro_rule ()
1965 {
1966 location_t locus = lexer.peek_token ()->get_locus ();
1967
1968 // parse macro matcher
1969 AST::MacroMatcher matcher = parse_macro_matcher ();
1970
1971 if (matcher.is_error ())
1972 return AST::MacroRule::create_error (locus);
1973
1974 if (!skip_token (MATCH_ARROW))
1975 {
1976 // skip after somewhere?
1977 return AST::MacroRule::create_error (locus);
1978 }
1979
1980 // parse transcriber (this is just a delim token tree)
1981 location_t token_tree_loc = lexer.peek_token ()->get_locus ();
1982 AST::MacroTranscriber transcriber (parse_delim_token_tree (), token_tree_loc);
1983
1984 return AST::MacroRule (std::move (matcher), std::move (transcriber), locus);
1985 }
1986
1987 // Parses a macro matcher (part of a macro rule definition).
1988 template <typename ManagedTokenSource>
1989 AST::MacroMatcher
1990 Parser<ManagedTokenSource>::parse_macro_matcher ()
1991 {
1992 // save delim type to ensure it is reused later
1993 AST::DelimType delim_type = AST::PARENS;
1994
1995 // DEBUG
1996 rust_debug ("begun parsing macro matcher");
1997
1998 // Map tokens to DelimType
1999 const_TokenPtr t = lexer.peek_token ();
2000 location_t locus = t->get_locus ();
2001 switch (t->get_id ())
2002 {
2003 case LEFT_PAREN:
2004 delim_type = AST::PARENS;
2005 break;
2006 case LEFT_SQUARE:
2007 delim_type = AST::SQUARE;
2008 break;
2009 case LEFT_CURLY:
2010 delim_type = AST::CURLY;
2011 break;
2012 default:
2013 add_error (Error (
2014 t->get_locus (),
2015 "unexpected token %qs - expecting delimiters (for a macro matcher)",
2016 t->get_token_description ()));
2017
2018 return AST::MacroMatcher::create_error (t->get_locus ());
2019 }
2020 lexer.skip_token ();
2021
2022 // parse actual macro matches
2023 std::vector<std::unique_ptr<AST::MacroMatch>> matches;
2024 // Set of possible preceding macro matches to make sure follow-set
2025 // restrictions are respected.
2026 // TODO: Consider using std::reference_wrapper instead of raw pointers?
2027 std::vector<const AST::MacroMatch *> last_matches;
2028
2029 t = lexer.peek_token ();
2030 // parse token trees until the initial delimiter token is found again
2031 while (!token_id_matches_delims (t->get_id (), delim_type))
2032 {
2033 std::unique_ptr<AST::MacroMatch> match = parse_macro_match ();
2034
2035 if (match == nullptr)
2036 {
2037 Error error (
2038 t->get_locus (),
2039 "failed to parse macro match for macro matcher - found %qs",
2040 t->get_token_description ());
2041 add_error (std::move (error));
2042
2043 return AST::MacroMatcher::create_error (t->get_locus ());
2044 }
2045
2046 if (matches.size () > 0)
2047 {
2048 const auto *last_match = matches.back ().get ();
2049
2050 // We want to check if we are dealing with a zeroable repetition
2051 bool zeroable = false;
2052 if (last_match->get_macro_match_type ()
2053 == AST::MacroMatch::MacroMatchType::Repetition)
2054 {
2055 auto repetition
2056 = static_cast<const AST::MacroMatchRepetition *> (last_match);
2057
2058 if (repetition->get_op ()
2059 != AST::MacroMatchRepetition::MacroRepOp::ONE_OR_MORE)
2060 zeroable = true;
2061 }
2062
2063 if (!zeroable)
2064 last_matches.clear ();
2065
2066 last_matches.emplace_back (last_match);
2067
2068 for (auto last : last_matches)
2069 if (!is_match_compatible (*last, *match))
2070 return AST::MacroMatcher::create_error (
2071 match->get_match_locus ());
2072 }
2073
2074 matches.push_back (std::move (match));
2075
2076 // DEBUG
2077 rust_debug ("pushed back a match in macro matcher");
2078
2079 t = lexer.peek_token ();
2080 }
2081
2082 // parse end delimiters
2083 t = lexer.peek_token ();
2084 if (token_id_matches_delims (t->get_id (), delim_type))
2085 {
2086 // tokens match opening delimiter, so skip.
2087 lexer.skip_token ();
2088
2089 return AST::MacroMatcher (delim_type, std::move (matches), locus);
2090 }
2091 else
2092 {
2093 // tokens don't match opening delimiters, so produce error
2094 Error error (t->get_locus (),
2095 "unexpected token %qs - expecting closing delimiter %qs "
2096 "(for a macro matcher)",
2097 t->get_token_description (),
2098 (delim_type == AST::PARENS
2099 ? ")"
2100 : (delim_type == AST::SQUARE ? "]" : "}")));
2101 add_error (std::move (error));
2102
2103 /* return error macro matcher despite possibly parsing mostly correct one?
2104 * TODO is this the best idea? */
2105 return AST::MacroMatcher::create_error (t->get_locus ());
2106 }
2107 }
2108
2109 // Parses a macro match (syntax match inside a matcher in a macro rule).
2110 template <typename ManagedTokenSource>
2111 std::unique_ptr<AST::MacroMatch>
2112 Parser<ManagedTokenSource>::parse_macro_match ()
2113 {
2114 // branch based on token available
2115 const_TokenPtr t = lexer.peek_token ();
2116 switch (t->get_id ())
2117 {
2118 case LEFT_PAREN:
2119 case LEFT_SQUARE:
2120 case LEFT_CURLY: {
2121 // must be macro matcher as delimited
2122 AST::MacroMatcher matcher = parse_macro_matcher ();
2123 if (matcher.is_error ())
2124 {
2125 Error error (lexer.peek_token ()->get_locus (),
2126 "failed to parse macro matcher in macro match");
2127 add_error (std::move (error));
2128
2129 return nullptr;
2130 }
2131 return std::unique_ptr<AST::MacroMatcher> (
2132 new AST::MacroMatcher (std::move (matcher)));
2133 }
2134 case DOLLAR_SIGN: {
2135 // have to do more lookahead to determine if fragment or repetition
2136 const_TokenPtr t2 = lexer.peek_token (1);
2137 switch (t2->get_id ())
2138 {
2139 case IDENTIFIER:
2140 case UNDERSCORE:
2141 // macro fragment
2142 return parse_macro_match_fragment ();
2143 case LEFT_PAREN:
2144 // macro repetition
2145 return parse_macro_match_repetition ();
2146 default:
2147 if (token_id_is_keyword (t2->get_id ()) && t2->get_id () != CRATE)
2148 {
2149 // keyword as macro fragment
2150 return parse_macro_match_fragment ();
2151 }
2152 else
2153 {
2154 // error: unrecognised
2155 add_error (Error (
2156 t2->get_locus (),
2157 "unrecognised token combination %<$%s%> at start of "
2158 "macro match - did you mean %<$identifier%> or %<$(%>?",
2159 t2->get_token_description ()));
2160
2161 // skip somewhere?
2162 return nullptr;
2163 }
2164 }
2165 }
2166 case RIGHT_PAREN:
2167 case RIGHT_SQUARE:
2168 case RIGHT_CURLY:
2169 // not allowed
2170 add_error (Error (
2171 t->get_locus (),
2172 "closing delimiters like %qs are not allowed at the start of a macro "
2173 "match",
2174 t->get_token_description ()));
2175
2176 // skip somewhere?
2177 return nullptr;
2178 default:
2179 // just the token
2180 lexer.skip_token ();
2181 return std::unique_ptr<AST::Token> (new AST::Token (std::move (t)));
2182 }
2183 }
2184
2185 // Parses a fragment macro match.
2186 template <typename ManagedTokenSource>
2187 std::unique_ptr<AST::MacroMatchFragment>
2188 Parser<ManagedTokenSource>::parse_macro_match_fragment ()
2189 {
2190 location_t fragment_locus = lexer.peek_token ()->get_locus ();
2191 skip_token (DOLLAR_SIGN);
2192
2193 Identifier ident;
2194 auto identifier = lexer.peek_token ();
2195 if (identifier->get_id () == UNDERSCORE)
2196 ident = {Values::Keywords::UNDERSCORE, identifier->get_locus ()};
2197 else
2198 ident = {identifier};
2199
2200 if (ident.empty ())
2201 {
2202 Error error (lexer.peek_token ()->get_locus (),
2203 "missing identifier in macro match fragment");
2204 add_error (std::move (error));
2205
2206 return nullptr;
2207 }
2208 skip_token (identifier->get_id ());
2209
2210 if (!skip_token (COLON))
2211 {
2212 // skip after somewhere?
2213 return nullptr;
2214 }
2215
2216 // get MacroFragSpec for macro
2217 const_TokenPtr t = expect_token (IDENTIFIER);
2218 if (t == nullptr)
2219 return nullptr;
2220
2221 AST::MacroFragSpec frag
2222 = AST::MacroFragSpec::get_frag_spec_from_str (t->get_str ());
2223 if (frag.is_error ())
2224 {
2225 Error error (t->get_locus (),
2226 "invalid fragment specifier %qs in fragment macro match",
2227 t->get_str ().c_str ());
2228 add_error (std::move (error));
2229
2230 return nullptr;
2231 }
2232
2233 return std::unique_ptr<AST::MacroMatchFragment> (
2234 new AST::MacroMatchFragment (std::move (ident), frag, fragment_locus));
2235 }
2236
2237 // Parses a repetition macro match.
2238 template <typename ManagedTokenSource>
2239 std::unique_ptr<AST::MacroMatchRepetition>
2240 Parser<ManagedTokenSource>::parse_macro_match_repetition ()
2241 {
2242 skip_token (DOLLAR_SIGN);
2243 skip_token (LEFT_PAREN);
2244
2245 std::vector<std::unique_ptr<AST::MacroMatch>> matches;
2246
2247 // parse required first macro match
2248 std::unique_ptr<AST::MacroMatch> initial_match = parse_macro_match ();
2249 if (initial_match == nullptr)
2250 {
2251 Error error (
2252 lexer.peek_token ()->get_locus (),
2253 "could not parse required first macro match in macro match repetition");
2254 add_error (std::move (error));
2255
2256 // skip after somewhere?
2257 return nullptr;
2258 }
2259 matches.push_back (std::move (initial_match));
2260
2261 // parse optional later macro matches
2262 const_TokenPtr t = lexer.peek_token ();
2263 while (t->get_id () != RIGHT_PAREN)
2264 {
2265 std::unique_ptr<AST::MacroMatch> match = parse_macro_match ();
2266
2267 if (match == nullptr)
2268 {
2269 Error error (lexer.peek_token ()->get_locus (),
2270 "failed to parse macro match in macro match repetition");
2271 add_error (std::move (error));
2272
2273 return nullptr;
2274 }
2275
2276 matches.push_back (std::move (match));
2277
2278 t = lexer.peek_token ();
2279 }
2280
2281 if (!skip_token (RIGHT_PAREN))
2282 {
2283 // skip after somewhere?
2284 return nullptr;
2285 }
2286
2287 t = lexer.peek_token ();
2288 // see if separator token exists
2289 std::unique_ptr<AST::Token> separator = nullptr;
2290 switch (t->get_id ())
2291 {
2292 // repetition operators
2293 case ASTERISK:
2294 case PLUS:
2295 case QUESTION_MARK:
2296 // delimiters
2297 case LEFT_PAREN:
2298 case LEFT_CURLY:
2299 case LEFT_SQUARE:
2300 case RIGHT_PAREN:
2301 case RIGHT_CURLY:
2302 case RIGHT_SQUARE:
2303 // separator does not exist, so still null and don't skip token
2304 break;
2305 default:
2306 // separator does exist
2307 separator = std::unique_ptr<AST::Token> (new AST::Token (std::move (t)));
2308 lexer.skip_token ();
2309 break;
2310 }
2311
2312 // parse repetition operator
2313 t = lexer.peek_token ();
2314 AST::MacroMatchRepetition::MacroRepOp op = AST::MacroMatchRepetition::NONE;
2315 switch (t->get_id ())
2316 {
2317 case ASTERISK:
2318 op = AST::MacroMatchRepetition::ANY;
2319 lexer.skip_token ();
2320 break;
2321 case PLUS:
2322 op = AST::MacroMatchRepetition::ONE_OR_MORE;
2323 lexer.skip_token ();
2324 break;
2325 case QUESTION_MARK:
2326 op = AST::MacroMatchRepetition::ZERO_OR_ONE;
2327 lexer.skip_token ();
2328
2329 if (separator != nullptr)
2330 {
2331 add_error (
2332 Error (separator->get_locus (),
2333 "the %<?%> macro repetition operator does not take a "
2334 "separator"));
2335 separator = nullptr;
2336 }
2337
2338 break;
2339 default:
2340 add_error (
2341 Error (t->get_locus (),
2342 "expected macro repetition operator (%<*%>, %<+%>, or %<?%>) in "
2343 "macro match - found %qs",
2344 t->get_token_description ()));
2345
2346 // skip after somewhere?
2347 return nullptr;
2348 }
2349
2350 return std::unique_ptr<AST::MacroMatchRepetition> (
2351 new AST::MacroMatchRepetition (std::move (matches), op,
2352 std::move (separator), t->get_locus ()));
2353 }
2354
2355 /* Parses a visibility syntactical production (i.e. creating a non-default
2356 * visibility) */
2357 template <typename ManagedTokenSource>
2358 AST::Visibility
2359 Parser<ManagedTokenSource>::parse_visibility ()
2360 {
2361 // check for no visibility
2362 if (lexer.peek_token ()->get_id () != PUB)
2363 {
2364 return AST::Visibility::create_private ();
2365 }
2366
2367 auto vis_loc = lexer.peek_token ()->get_locus ();
2368 lexer.skip_token ();
2369
2370 // create simple pub visibility if
2371 // - found no parentheses
2372 // - found unit type `()`
2373 if (lexer.peek_token ()->get_id () != LEFT_PAREN
2374 || lexer.peek_token (1)->get_id () == RIGHT_PAREN)
2375 {
2376 return AST::Visibility::create_public (vis_loc);
2377 // or whatever
2378 }
2379
2380 lexer.skip_token ();
2381
2382 const_TokenPtr t = lexer.peek_token ();
2383 auto path_loc = t->get_locus ();
2384
2385 switch (t->get_id ())
2386 {
2387 case CRATE:
2388 lexer.skip_token ();
2389
2390 skip_token (RIGHT_PAREN);
2391
2392 return AST::Visibility::create_crate (path_loc, vis_loc);
2393 case SELF:
2394 lexer.skip_token ();
2395
2396 skip_token (RIGHT_PAREN);
2397
2398 return AST::Visibility::create_self (path_loc, vis_loc);
2399 case SUPER:
2400 lexer.skip_token ();
2401
2402 skip_token (RIGHT_PAREN);
2403
2404 return AST::Visibility::create_super (path_loc, vis_loc);
2405 case IN: {
2406 lexer.skip_token ();
2407
2408 // parse the "in" path as well
2409 AST::SimplePath path = parse_simple_path ();
2410 if (path.is_empty ())
2411 {
2412 Error error (lexer.peek_token ()->get_locus (),
2413 "missing path in pub(in path) visibility");
2414 add_error (std::move (error));
2415
2416 // skip after somewhere?
2417 return AST::Visibility::create_error ();
2418 }
2419
2420 skip_token (RIGHT_PAREN);
2421
2422 return AST::Visibility::create_in_path (std::move (path), vis_loc);
2423 }
2424 default:
2425 add_error (Error (t->get_locus (), "unexpected token %qs in visibility",
2426 t->get_token_description ()));
2427
2428 lexer.skip_token ();
2429 return AST::Visibility::create_error ();
2430 }
2431 }
2432
2433 // Parses a module - either a bodied module or a module defined in another file.
2434 template <typename ManagedTokenSource>
2435 std::unique_ptr<AST::Module>
2436 Parser<ManagedTokenSource>::parse_module (AST::Visibility vis,
2437 AST::AttrVec outer_attrs)
2438 {
2439 location_t locus = lexer.peek_token ()->get_locus ();
2440
2441 Unsafety safety = Unsafety::Normal;
2442 if (lexer.peek_token ()->get_id () == UNSAFE)
2443 {
2444 safety = Unsafety::Unsafe;
2445 skip_token (UNSAFE);
2446 }
2447
2448 skip_token (MOD);
2449
2450 const_TokenPtr module_name = expect_token (IDENTIFIER);
2451 if (module_name == nullptr)
2452 {
2453 return nullptr;
2454 }
2455 Identifier name{module_name};
2456
2457 const_TokenPtr t = lexer.peek_token ();
2458
2459 switch (t->get_id ())
2460 {
2461 case SEMICOLON:
2462 lexer.skip_token ();
2463
2464 // Construct an external module
2465 return std::unique_ptr<AST::Module> (
2466 new AST::Module (std::move (name), std::move (vis),
2467 std::move (outer_attrs), locus, safety,
2468 lexer.get_filename (), inline_module_stack));
2469 case LEFT_CURLY: {
2470 lexer.skip_token ();
2471
2472 // parse inner attributes
2473 AST::AttrVec inner_attrs = parse_inner_attributes ();
2474
2475 std::string default_path = name.as_string ();
2476
2477 if (inline_module_stack.empty ())
2478 {
2479 std::string filename = lexer.get_filename ();
2480 auto slash_idx = filename.rfind (file_separator);
2481 if (slash_idx == std::string::npos)
2482 slash_idx = 0;
2483 else
2484 slash_idx++;
2485 filename = filename.substr (slash_idx);
2486
2487 std::string subdir;
2488 if (get_file_subdir (filename, subdir))
2489 default_path = subdir + file_separator + name.as_string ();
2490 }
2491
2492 std::string module_path_name
2493 = extract_module_path (inner_attrs, outer_attrs, default_path);
2494 InlineModuleStackScope scope (*this, std::move (module_path_name));
2495
2496 // parse items
2497 std::vector<std::unique_ptr<AST::Item>> items;
2498 const_TokenPtr tok = lexer.peek_token ();
2499 while (tok->get_id () != RIGHT_CURLY)
2500 {
2501 std::unique_ptr<AST::Item> item = parse_item (false);
2502 if (item == nullptr)
2503 {
2504 Error error (tok->get_locus (),
2505 "failed to parse item in module");
2506 add_error (std::move (error));
2507
2508 return nullptr;
2509 }
2510
2511 items.push_back (std::move (item));
2512
2513 tok = lexer.peek_token ();
2514 }
2515
2516 if (!skip_token (RIGHT_CURLY))
2517 {
2518 // skip somewhere?
2519 return nullptr;
2520 }
2521
2522 return std::unique_ptr<AST::Module> (
2523 new AST::Module (std::move (name), locus, std::move (items),
2524 std::move (vis), safety, std::move (inner_attrs),
2525 std::move (outer_attrs))); // module name?
2526 }
2527 default:
2528 add_error (
2529 Error (t->get_locus (),
2530 "unexpected token %qs in module declaration/definition item",
2531 t->get_token_description ()));
2532
2533 lexer.skip_token ();
2534 return nullptr;
2535 }
2536 }
2537
2538 // Parses an extern crate declaration (dependency on external crate)
2539 template <typename ManagedTokenSource>
2540 std::unique_ptr<AST::ExternCrate>
2541 Parser<ManagedTokenSource>::parse_extern_crate (AST::Visibility vis,
2542 AST::AttrVec outer_attrs)
2543 {
2544 location_t locus = lexer.peek_token ()->get_locus ();
2545 if (!skip_token (EXTERN_KW))
2546 {
2547 skip_after_semicolon ();
2548 return nullptr;
2549 }
2550
2551 if (!skip_token (CRATE))
2552 {
2553 skip_after_semicolon ();
2554 return nullptr;
2555 }
2556
2557 /* parse crate reference name - this has its own syntactical rule in reference
2558 * but seems to not be used elsewhere, so i'm putting it here */
2559 const_TokenPtr crate_name_tok = lexer.peek_token ();
2560 std::string crate_name;
2561
2562 switch (crate_name_tok->get_id ())
2563 {
2564 case IDENTIFIER:
2565 crate_name = crate_name_tok->get_str ();
2566 lexer.skip_token ();
2567 break;
2568 case SELF:
2569 crate_name = Values::Keywords::SELF;
2570 lexer.skip_token ();
2571 break;
2572 default:
2573 add_error (
2574 Error (crate_name_tok->get_locus (),
2575 "expecting crate name (identifier or %<self%>), found %qs",
2576 crate_name_tok->get_token_description ()));
2577
2578 skip_after_semicolon ();
2579 return nullptr;
2580 }
2581
2582 // don't parse as clause if it doesn't exist
2583 if (lexer.peek_token ()->get_id () == SEMICOLON)
2584 {
2585 lexer.skip_token ();
2586
2587 return std::unique_ptr<AST::ExternCrate> (
2588 new AST::ExternCrate (std::move (crate_name), std::move (vis),
2589 std::move (outer_attrs), locus));
2590 }
2591
2592 /* parse as clause - this also has its own syntactical rule in reference and
2593 * also seems to not be used elsewhere, so including here again. */
2594 if (!skip_token (AS))
2595 {
2596 skip_after_semicolon ();
2597 return nullptr;
2598 }
2599
2600 const_TokenPtr as_name_tok = lexer.peek_token ();
2601 std::string as_name;
2602
2603 switch (as_name_tok->get_id ())
2604 {
2605 case IDENTIFIER:
2606 as_name = as_name_tok->get_str ();
2607 lexer.skip_token ();
2608 break;
2609 case UNDERSCORE:
2610 as_name = Values::Keywords::UNDERSCORE;
2611 lexer.skip_token ();
2612 break;
2613 default:
2614 add_error (
2615 Error (as_name_tok->get_locus (),
2616 "expecting as clause name (identifier or %<_%>), found %qs",
2617 as_name_tok->get_token_description ()));
2618
2619 skip_after_semicolon ();
2620 return nullptr;
2621 }
2622
2623 if (!skip_token (SEMICOLON))
2624 {
2625 skip_after_semicolon ();
2626 return nullptr;
2627 }
2628
2629 return std::unique_ptr<AST::ExternCrate> (
2630 new AST::ExternCrate (std::move (crate_name), std::move (vis),
2631 std::move (outer_attrs), locus, std::move (as_name)));
2632 }
2633
2634 // Parses a use declaration.
2635 template <typename ManagedTokenSource>
2636 std::unique_ptr<AST::UseDeclaration>
2637 Parser<ManagedTokenSource>::parse_use_decl (AST::Visibility vis,
2638 AST::AttrVec outer_attrs)
2639 {
2640 location_t locus = lexer.peek_token ()->get_locus ();
2641 if (!skip_token (USE))
2642 {
2643 skip_after_semicolon ();
2644 return nullptr;
2645 }
2646
2647 // parse use tree, which is required
2648 std::unique_ptr<AST::UseTree> use_tree = parse_use_tree ();
2649 if (use_tree == nullptr)
2650 {
2651 Error error (lexer.peek_token ()->get_locus (),
2652 "could not parse use tree in use declaration");
2653 add_error (std::move (error));
2654
2655 skip_after_semicolon ();
2656 return nullptr;
2657 }
2658
2659 if (!skip_token (SEMICOLON))
2660 {
2661 skip_after_semicolon ();
2662 return nullptr;
2663 }
2664
2665 return std::unique_ptr<AST::UseDeclaration> (
2666 new AST::UseDeclaration (std::move (use_tree), std::move (vis),
2667 std::move (outer_attrs), locus));
2668 }
2669
2670 // Parses a use tree (which can be recursive and is actually a base class).
2671 template <typename ManagedTokenSource>
2672 std::unique_ptr<AST::UseTree>
2673 Parser<ManagedTokenSource>::parse_use_tree ()
2674 {
2675 /* potential syntax definitions in attempt to get algorithm:
2676 * Glob:
2677 * <- SimplePath :: *
2678 * <- :: *
2679 * <- *
2680 * Nested tree thing:
2681 * <- SimplePath :: { COMPLICATED_INNER_TREE_THING }
2682 * <- :: COMPLICATED_INNER_TREE_THING }
2683 * <- { COMPLICATED_INNER_TREE_THING }
2684 * Rebind thing:
2685 * <- SimplePath as IDENTIFIER
2686 * <- SimplePath as _
2687 * <- SimplePath
2688 */
2689
2690 /* current plan of attack: try to parse SimplePath first - if fails, one of
2691 * top two then try parse :: - if fails, one of top two. Next is deciding
2692 * character for top two. */
2693
2694 /* Thus, parsing smaller parts of use tree may require feeding into function
2695 * via parameters (or could handle all in this single function because other
2696 * use tree types aren't recognised as separate in the spec) */
2697
2698 // TODO: I think this function is too complex, probably should split it
2699
2700 location_t locus = lexer.peek_token ()->get_locus ();
2701
2702 // bool has_path = false;
2703 AST::SimplePath path = parse_simple_path ();
2704
2705 if (path.is_empty ())
2706 {
2707 // has no path, so must be glob or nested tree UseTree type
2708
2709 bool is_global = false;
2710
2711 // check for global scope resolution operator
2712 if (lexer.peek_token ()->get_id () == SCOPE_RESOLUTION)
2713 {
2714 lexer.skip_token ();
2715 is_global = true;
2716 }
2717
2718 const_TokenPtr t = lexer.peek_token ();
2719 switch (t->get_id ())
2720 {
2721 case ASTERISK:
2722 // glob UseTree type
2723 lexer.skip_token ();
2724
2725 if (is_global)
2726 return std::unique_ptr<AST::UseTreeGlob> (
2727 new AST::UseTreeGlob (AST::UseTreeGlob::GLOBAL,
2728 AST::SimplePath::create_empty (), locus));
2729 else
2730 return std::unique_ptr<AST::UseTreeGlob> (
2731 new AST::UseTreeGlob (AST::UseTreeGlob::NO_PATH,
2732 AST::SimplePath::create_empty (), locus));
2733 case LEFT_CURLY: {
2734 // nested tree UseTree type
2735 lexer.skip_token ();
2736
2737 std::vector<std::unique_ptr<AST::UseTree>> use_trees;
2738
2739 const_TokenPtr t = lexer.peek_token ();
2740 while (t->get_id () != RIGHT_CURLY)
2741 {
2742 std::unique_ptr<AST::UseTree> use_tree = parse_use_tree ();
2743 if (use_tree == nullptr)
2744 {
2745 break;
2746 }
2747
2748 use_trees.push_back (std::move (use_tree));
2749
2750 if (lexer.peek_token ()->get_id () != COMMA)
2751 break;
2752
2753 lexer.skip_token ();
2754 t = lexer.peek_token ();
2755 }
2756
2757 // skip end curly delimiter
2758 if (!skip_token (RIGHT_CURLY))
2759 {
2760 // skip after somewhere?
2761 return nullptr;
2762 }
2763
2764 if (is_global)
2765 return std::unique_ptr<AST::UseTreeList> (
2766 new AST::UseTreeList (AST::UseTreeList::GLOBAL,
2767 AST::SimplePath::create_empty (),
2768 std::move (use_trees), locus));
2769 else
2770 return std::unique_ptr<AST::UseTreeList> (
2771 new AST::UseTreeList (AST::UseTreeList::NO_PATH,
2772 AST::SimplePath::create_empty (),
2773 std::move (use_trees), locus));
2774 }
2775 case AS:
2776 // this is not allowed
2777 add_error (Error (
2778 t->get_locus (),
2779 "use declaration with rebind %<as%> requires a valid simple path - "
2780 "none found"));
2781
2782 skip_after_semicolon ();
2783 return nullptr;
2784 default:
2785 add_error (Error (t->get_locus (),
2786 "unexpected token %qs in use tree with "
2787 "no valid simple path (i.e. list"
2788 " or glob use tree)",
2789 t->get_token_description ()));
2790
2791 skip_after_semicolon ();
2792 return nullptr;
2793 }
2794 }
2795 else
2796 {
2797 /* Due to aforementioned implementation issues, the trailing :: token is
2798 * consumed by the path, so it can not be used as a disambiguator.
2799 * NOPE, not true anymore - TODO what are the consequences of this? */
2800
2801 const_TokenPtr t = lexer.peek_token ();
2802 switch (t->get_id ())
2803 {
2804 case ASTERISK:
2805 // glob UseTree type
2806 lexer.skip_token ();
2807
2808 return std::unique_ptr<AST::UseTreeGlob> (
2809 new AST::UseTreeGlob (AST::UseTreeGlob::PATH_PREFIXED,
2810 std::move (path), locus));
2811 case LEFT_CURLY: {
2812 // nested tree UseTree type
2813 lexer.skip_token ();
2814
2815 std::vector<std::unique_ptr<AST::UseTree>> use_trees;
2816
2817 // TODO: think of better control structure
2818 const_TokenPtr t = lexer.peek_token ();
2819 while (t->get_id () != RIGHT_CURLY)
2820 {
2821 std::unique_ptr<AST::UseTree> use_tree = parse_use_tree ();
2822 if (use_tree == nullptr)
2823 {
2824 break;
2825 }
2826
2827 use_trees.push_back (std::move (use_tree));
2828
2829 if (lexer.peek_token ()->get_id () != COMMA)
2830 break;
2831
2832 lexer.skip_token ();
2833 t = lexer.peek_token ();
2834 }
2835
2836 // skip end curly delimiter
2837 if (!skip_token (RIGHT_CURLY))
2838 {
2839 // skip after somewhere?
2840 return nullptr;
2841 }
2842
2843 return std::unique_ptr<AST::UseTreeList> (
2844 new AST::UseTreeList (AST::UseTreeList::PATH_PREFIXED,
2845 std::move (path), std::move (use_trees),
2846 locus));
2847 }
2848 case AS: {
2849 // rebind UseTree type
2850 lexer.skip_token ();
2851
2852 const_TokenPtr t = lexer.peek_token ();
2853 switch (t->get_id ())
2854 {
2855 case IDENTIFIER:
2856 // skip lexer token
2857 lexer.skip_token ();
2858
2859 return std::unique_ptr<AST::UseTreeRebind> (
2860 new AST::UseTreeRebind (AST::UseTreeRebind::IDENTIFIER,
2861 std::move (path), locus, t));
2862 case UNDERSCORE:
2863 // skip lexer token
2864 lexer.skip_token ();
2865
2866 return std::unique_ptr<AST::UseTreeRebind> (
2867 new AST::UseTreeRebind (AST::UseTreeRebind::WILDCARD,
2868 std::move (path), locus,
2869 {Values::Keywords::UNDERSCORE,
2870 t->get_locus ()}));
2871 default:
2872 add_error (Error (
2873 t->get_locus (),
2874 "unexpected token %qs in use tree with as clause - expected "
2875 "identifier or %<_%>",
2876 t->get_token_description ()));
2877
2878 skip_after_semicolon ();
2879 return nullptr;
2880 }
2881 }
2882 case SEMICOLON:
2883 // rebind UseTree type without rebinding - path only
2884
2885 // don't skip semicolon - handled in parse_use_tree
2886 // lexer.skip_token();
2887
2888 return std::unique_ptr<AST::UseTreeRebind> (
2889 new AST::UseTreeRebind (AST::UseTreeRebind::NONE, std::move (path),
2890 locus));
2891 case COMMA:
2892 case RIGHT_CURLY:
2893 // this may occur in recursive calls - assume it is ok and ignore it
2894 return std::unique_ptr<AST::UseTreeRebind> (
2895 new AST::UseTreeRebind (AST::UseTreeRebind::NONE, std::move (path),
2896 locus));
2897 default:
2898 add_error (Error (t->get_locus (),
2899 "unexpected token %qs in use tree with valid path",
2900 t->get_token_description ()));
2901
2902 // skip_after_semicolon();
2903 return nullptr;
2904 }
2905 }
2906 }
2907
2908 // Parses a function (not a method).
2909 template <typename ManagedTokenSource>
2910 std::unique_ptr<AST::Function>
2911 Parser<ManagedTokenSource>::parse_function (AST::Visibility vis,
2912 AST::AttrVec outer_attrs,
2913 bool is_external)
2914 {
2915 location_t locus = lexer.peek_token ()->get_locus ();
2916 // Get qualifiers for function if they exist
2917 AST::FunctionQualifiers qualifiers = parse_function_qualifiers ();
2918
2919 skip_token (FN_KW);
2920
2921 // Save function name token
2922 const_TokenPtr function_name_tok = expect_token (IDENTIFIER);
2923 if (function_name_tok == nullptr)
2924 {
2925 skip_after_next_block ();
2926 return nullptr;
2927 }
2928 Identifier function_name{function_name_tok};
2929
2930 // parse generic params - if exist
2931 std::vector<std::unique_ptr<AST::GenericParam>> generic_params
2932 = parse_generic_params_in_angles ();
2933
2934 if (!skip_token (LEFT_PAREN))
2935 {
2936 Error error (lexer.peek_token ()->get_locus (),
2937 "function declaration missing opening parentheses before "
2938 "parameter list");
2939 add_error (std::move (error));
2940
2941 skip_after_next_block ();
2942 return nullptr;
2943 }
2944
2945 auto initial_param = parse_self_param ();
2946
2947 if (!initial_param.has_value ()
2948 && initial_param.error () != ParseSelfError::NOT_SELF)
2949 return nullptr;
2950
2951 if (initial_param.has_value () && lexer.peek_token ()->get_id () == COMMA)
2952 skip_token ();
2953
2954 // parse function parameters (only if next token isn't right paren)
2955 std::vector<std::unique_ptr<AST::Param>> function_params;
2956
2957 if (lexer.peek_token ()->get_id () != RIGHT_PAREN)
2958 function_params
2959 = parse_function_params ([] (TokenId id) { return id == RIGHT_PAREN; });
2960
2961 if (initial_param.has_value ())
2962 function_params.insert (function_params.begin (),
2963 std::move (*initial_param));
2964
2965 if (!skip_token (RIGHT_PAREN))
2966 {
2967 Error error (lexer.peek_token ()->get_locus (),
2968 "function declaration missing closing parentheses after "
2969 "parameter list");
2970 add_error (std::move (error));
2971
2972 skip_after_next_block ();
2973 return nullptr;
2974 }
2975
2976 // parse function return type - if exists
2977 std::unique_ptr<AST::Type> return_type = parse_function_return_type ();
2978
2979 // parse where clause - if exists
2980 AST::WhereClause where_clause = parse_where_clause ();
2981
2982 tl::optional<std::unique_ptr<AST::BlockExpr>> body = tl::nullopt;
2983 if (lexer.peek_token ()->get_id () == SEMICOLON)
2984 lexer.skip_token ();
2985 else
2986 {
2987 std::unique_ptr<AST::BlockExpr> block_expr = parse_block_expr ();
2988 if (block_expr != nullptr)
2989 body = std::move (block_expr);
2990 }
2991
2992 return std::unique_ptr<AST::Function> (
2993 new AST::Function (std::move (function_name), std::move (qualifiers),
2994 std::move (generic_params), std::move (function_params),
2995 std::move (return_type), std::move (where_clause),
2996 std::move (body), std::move (vis),
2997 std::move (outer_attrs), locus, false, is_external));
2998 }
2999
3000 // Parses function or method qualifiers (i.e. const, unsafe, and extern).
3001 template <typename ManagedTokenSource>
3002 AST::FunctionQualifiers
3003 Parser<ManagedTokenSource>::parse_function_qualifiers ()
3004 {
3005 Async async_status = Async::No;
3006 Const const_status = Const::No;
3007 Unsafety unsafe_status = Unsafety::Normal;
3008 bool has_extern = false;
3009 std::string abi;
3010
3011 const_TokenPtr t;
3012 location_t locus;
3013 // Check in order of const, unsafe, then extern
3014 for (int i = 0; i < 2; i++)
3015 {
3016 t = lexer.peek_token ();
3017 locus = t->get_locus ();
3018
3019 switch (t->get_id ())
3020 {
3021 case CONST:
3022 lexer.skip_token ();
3023 const_status = Const::Yes;
3024 break;
3025 case ASYNC:
3026 lexer.skip_token ();
3027 async_status = Async::Yes;
3028 break;
3029 default:
3030 // const status is still none
3031 break;
3032 }
3033 }
3034
3035 if (lexer.peek_token ()->get_id () == UNSAFE)
3036 {
3037 lexer.skip_token ();
3038 unsafe_status = Unsafety::Unsafe;
3039 }
3040
3041 if (lexer.peek_token ()->get_id () == EXTERN_KW)
3042 {
3043 lexer.skip_token ();
3044 has_extern = true;
3045
3046 // detect optional abi name
3047 const_TokenPtr next_tok = lexer.peek_token ();
3048 if (next_tok->get_id () == STRING_LITERAL)
3049 {
3050 lexer.skip_token ();
3051 abi = next_tok->get_str ();
3052 }
3053 }
3054
3055 return AST::FunctionQualifiers (locus, async_status, const_status,
3056 unsafe_status, has_extern, std::move (abi));
3057 }
3058
3059 // Parses generic (lifetime or type) params inside angle brackets (optional).
3060 template <typename ManagedTokenSource>
3061 std::vector<std::unique_ptr<AST::GenericParam>>
3062 Parser<ManagedTokenSource>::parse_generic_params_in_angles ()
3063 {
3064 if (lexer.peek_token ()->get_id () != LEFT_ANGLE)
3065 {
3066 // seems to be no generic params, so exit with empty vector
3067 return std::vector<std::unique_ptr<AST::GenericParam>> ();
3068 }
3069 lexer.skip_token ();
3070
3071 // DEBUG:
3072 rust_debug ("skipped left angle in generic param");
3073
3074 std::vector<std::unique_ptr<AST::GenericParam>> generic_params
3075 = parse_generic_params (is_right_angle_tok);
3076
3077 // DEBUG:
3078 rust_debug ("finished parsing actual generic params (i.e. inside angles)");
3079
3080 if (!skip_generics_right_angle ())
3081 {
3082 // DEBUG
3083 rust_debug ("failed to skip generics right angle - returning empty "
3084 "generic params");
3085
3086 return std::vector<std::unique_ptr<AST::GenericParam>> ();
3087 }
3088
3089 return generic_params;
3090 }
3091
3092 template <typename ManagedTokenSource>
3093 template <typename EndTokenPred>
3094 std::unique_ptr<AST::GenericParam>
3095 Parser<ManagedTokenSource>::parse_generic_param (EndTokenPred is_end_token)
3096 {
3097 auto outer_attrs = parse_outer_attributes ();
3098 std::unique_ptr<AST::GenericParam> param;
3099 auto token = lexer.peek_token ();
3100
3101 switch (token->get_id ())
3102 {
3103 case LIFETIME: {
3104 auto lifetime = parse_lifetime (false);
3105 if (!lifetime)
3106 {
3107 rust_error_at (
3108 token->get_locus (),
3109 "failed to parse lifetime in generic parameter list");
3110 return nullptr;
3111 }
3112
3113 std::vector<AST::Lifetime> lifetime_bounds;
3114 if (lexer.peek_token ()->get_id () == COLON)
3115 {
3116 lexer.skip_token ();
3117 // parse required bounds
3118 lifetime_bounds
3119 = parse_lifetime_bounds ([is_end_token] (TokenId id) {
3120 return is_end_token (id) || id == COMMA;
3121 });
3122 }
3123
3124 param = std::unique_ptr<AST::LifetimeParam> (new AST::LifetimeParam (
3125 std::move (lifetime.value ()), std::move (lifetime_bounds),
3126 std::move (outer_attrs), token->get_locus ()));
3127 break;
3128 }
3129 case IDENTIFIER: {
3130 auto type_ident = token->get_str ();
3131 lexer.skip_token ();
3132
3133 std::vector<std::unique_ptr<AST::TypeParamBound>> type_param_bounds;
3134 if (lexer.peek_token ()->get_id () == COLON)
3135 {
3136 lexer.skip_token ();
3137
3138 // parse optional type param bounds
3139 type_param_bounds = parse_type_param_bounds ();
3140 }
3141
3142 std::unique_ptr<AST::Type> type = nullptr;
3143 if (lexer.peek_token ()->get_id () == EQUAL)
3144 {
3145 lexer.skip_token ();
3146
3147 // parse required type
3148 type = parse_type ();
3149 if (!type)
3150 {
3151 rust_error_at (
3152 lexer.peek_token ()->get_locus (),
3153 "failed to parse type in type param in generic params");
3154 return nullptr;
3155 }
3156 }
3157
3158 param = std::unique_ptr<AST::TypeParam> (
3159 new AST::TypeParam (std::move (type_ident), token->get_locus (),
3160 std::move (type_param_bounds), std::move (type),
3161 std::move (outer_attrs)));
3162 break;
3163 }
3164 case CONST: {
3165 lexer.skip_token ();
3166
3167 auto name_token = expect_token (IDENTIFIER);
3168
3169 if (!name_token || !expect_token (COLON))
3170 return nullptr;
3171
3172 auto type = parse_type ();
3173 if (!type)
3174 return nullptr;
3175
3176 // optional default value
3177 auto default_expr = AST::GenericArg::create_error ();
3178 if (lexer.peek_token ()->get_id () == EQUAL)
3179 {
3180 lexer.skip_token ();
3181 auto tok = lexer.peek_token ();
3182 default_expr = parse_generic_arg ();
3183
3184 if (default_expr.is_error ())
3185 rust_error_at (tok->get_locus (),
3186 "invalid token for start of default value for "
3187 "const generic parameter: expected %<block%>, "
3188 "%<identifier%> or %<literal%>, got %qs",
3189 token_id_to_str (tok->get_id ()));
3190
3191 // At this point, we *know* that we are parsing a const
3192 // expression
3193 if (default_expr.get_kind () == AST::GenericArg::Kind::Either)
3194 default_expr = default_expr.disambiguate_to_const ();
3195 }
3196
3197 param = std::unique_ptr<AST::ConstGenericParam> (
3198 new AST::ConstGenericParam (name_token->get_str (), std::move (type),
3199 default_expr, std::move (outer_attrs),
3200 token->get_locus ()));
3201
3202 break;
3203 }
3204 default:
3205 // FIXME: Can we clean this last call with a method call?
3206 rust_error_at (token->get_locus (),
3207 "unexpected token when parsing generic parameters: %qs",
3208 token->as_string ().c_str ());
3209 return nullptr;
3210 }
3211
3212 return param;
3213 }
3214
3215 /* Parse generic (lifetime or type) params NOT INSIDE ANGLE BRACKETS!!! Almost
3216 * always parse_generic_params_in_angles is what is wanted. */
3217 template <typename ManagedTokenSource>
3218 template <typename EndTokenPred>
3219 std::vector<std::unique_ptr<AST::GenericParam>>
3220 Parser<ManagedTokenSource>::parse_generic_params (EndTokenPred is_end_token)
3221 {
3222 std::vector<std::unique_ptr<AST::GenericParam>> generic_params;
3223
3224 /* can't parse lifetime and type params separately due to lookahead issues
3225 * thus, parse them all here */
3226
3227 /* HACK: used to retain attribute data if a lifetime param is tentatively
3228 * parsed but it turns out to be type param */
3229 AST::Attribute parsed_outer_attr = AST::Attribute::create_empty ();
3230
3231 // Did we parse a generic type param yet
3232 auto type_seen = false;
3233 // Did the user write a lifetime parameter after a type one
3234 auto order_error = false;
3235
3236 // parse lifetime params
3237 while (!is_end_token (lexer.peek_token ()->get_id ()))
3238 {
3239 auto param = parse_generic_param (is_end_token);
3240 if (param)
3241 {
3242 // TODO: Handle `Const` here as well if necessary
3243 if (param->get_kind () == AST::GenericParam::Kind::Type)
3244 type_seen = true;
3245 else if (param->get_kind () == AST::GenericParam::Kind::Lifetime
3246 && type_seen)
3247 order_error = true;
3248
3249 generic_params.emplace_back (std::move (param));
3250 maybe_skip_token (COMMA);
3251 }
3252 else
3253 break;
3254 }
3255
3256 // FIXME: Add reordering hint
3257 if (order_error)
3258 {
3259 Error error (generic_params.front ()->get_locus (),
3260 "invalid order for generic parameters: lifetime parameters "
3261 "must be declared prior to type and const parameters");
3262 add_error (std::move (error));
3263 }
3264
3265 generic_params.shrink_to_fit ();
3266 return generic_params;
3267 }
3268
3269 /* Parses lifetime generic parameters (pointers). Will also consume any
3270 * trailing comma. No extra checks for end token. */
3271 template <typename ManagedTokenSource>
3272 std::vector<std::unique_ptr<AST::LifetimeParam>>
3273 Parser<ManagedTokenSource>::parse_lifetime_params ()
3274 {
3275 std::vector<std::unique_ptr<AST::LifetimeParam>> lifetime_params;
3276
3277 while (lexer.peek_token ()->get_id () != END_OF_FILE)
3278 {
3279 auto lifetime_param = parse_lifetime_param ();
3280
3281 if (!lifetime_param)
3282 {
3283 // can't treat as error as only way to get out with trailing comma
3284 break;
3285 }
3286
3287 lifetime_params.push_back (std::unique_ptr<AST::LifetimeParam> (
3288 new AST::LifetimeParam (std::move (lifetime_param.value ()))));
3289
3290 if (lexer.peek_token ()->get_id () != COMMA)
3291 break;
3292
3293 // skip commas, including trailing commas
3294 lexer.skip_token ();
3295 }
3296
3297 lifetime_params.shrink_to_fit ();
3298
3299 return lifetime_params;
3300 }
3301
3302 /* Parses lifetime generic parameters (pointers). Will also consume any
3303 * trailing comma. Has extra is_end_token predicate checking. */
3304 template <typename ManagedTokenSource>
3305 template <typename EndTokenPred>
3306 std::vector<std::unique_ptr<AST::LifetimeParam>>
3307 Parser<ManagedTokenSource>::parse_lifetime_params (EndTokenPred is_end_token)
3308 {
3309 std::vector<std::unique_ptr<AST::LifetimeParam>> lifetime_params;
3310
3311 // if end_token is not specified, it defaults to EOF, so should work fine
3312 while (!is_end_token (lexer.peek_token ()->get_id ()))
3313 {
3314 auto lifetime_param = parse_lifetime_param ();
3315
3316 if (!lifetime_param)
3317 {
3318 /* TODO: is it worth throwing away all lifetime params just because
3319 * one failed? */
3320 Error error (lexer.peek_token ()->get_locus (),
3321 "failed to parse lifetime param in lifetime params");
3322 add_error (std::move (error));
3323
3324 return {};
3325 }
3326
3327 lifetime_params.push_back (std::unique_ptr<AST::LifetimeParam> (
3328 new AST::LifetimeParam (std::move (lifetime_param))));
3329
3330 if (lexer.peek_token ()->get_id () != COMMA)
3331 break;
3332
3333 // skip commas, including trailing commas
3334 lexer.skip_token ();
3335 }
3336
3337 lifetime_params.shrink_to_fit ();
3338
3339 return lifetime_params;
3340 }
3341
3342 /* Parses lifetime generic parameters (objects). Will also consume any
3343 * trailing comma. No extra checks for end token.
3344 * TODO: is this best solution? implements most of the same algorithm. */
3345 template <typename ManagedTokenSource>
3346 std::vector<AST::LifetimeParam>
3347 Parser<ManagedTokenSource>::parse_lifetime_params_objs ()
3348 {
3349 std::vector<AST::LifetimeParam> lifetime_params;
3350
3351 // bad control structure as end token cannot be guaranteed
3352 while (true)
3353 {
3354 auto lifetime_param = parse_lifetime_param ();
3355
3356 if (!lifetime_param)
3357 {
3358 // not an error as only way to exit if trailing comma
3359 break;
3360 }
3361
3362 lifetime_params.push_back (std::move (lifetime_param));
3363
3364 if (lexer.peek_token ()->get_id () != COMMA)
3365 break;
3366
3367 // skip commas, including trailing commas
3368 lexer.skip_token ();
3369 }
3370
3371 lifetime_params.shrink_to_fit ();
3372
3373 return lifetime_params;
3374 }
3375
3376 /* Parses lifetime generic parameters (objects). Will also consume any
3377 * trailing comma. Has extra is_end_token predicate checking.
3378 * TODO: is this best solution? implements most of the same algorithm. */
3379 template <typename ManagedTokenSource>
3380 template <typename EndTokenPred>
3381 std::vector<AST::LifetimeParam>
3382 Parser<ManagedTokenSource>::parse_lifetime_params_objs (
3383 EndTokenPred is_end_token)
3384 {
3385 std::vector<AST::LifetimeParam> lifetime_params;
3386
3387 while (!is_end_token (lexer.peek_token ()->get_id ()))
3388 {
3389 auto lifetime_param = parse_lifetime_param ();
3390
3391 if (!lifetime_param)
3392 {
3393 /* TODO: is it worth throwing away all lifetime params just because
3394 * one failed? */
3395 Error error (lexer.peek_token ()->get_locus (),
3396 "failed to parse lifetime param in lifetime params");
3397 add_error (std::move (error));
3398
3399 return {};
3400 }
3401
3402 lifetime_params.push_back (std::move (lifetime_param.value ()));
3403
3404 if (lexer.peek_token ()->get_id () != COMMA)
3405 break;
3406
3407 // skip commas, including trailing commas
3408 lexer.skip_token ();
3409 }
3410
3411 lifetime_params.shrink_to_fit ();
3412
3413 return lifetime_params;
3414 }
3415
3416 /* Parses a sequence of a certain grammar rule in object form (not pointer or
3417 * smart pointer), delimited by commas and ending when 'is_end_token' is
3418 * satisfied (templated). Will also consume any trailing comma.
3419 * FIXME: this cannot be used due to member function pointer problems (i.e.
3420 * parsing_function cannot be specified properly) */
3421 template <typename ManagedTokenSource>
3422 template <typename ParseFunction, typename EndTokenPred>
3423 auto
3424 Parser<ManagedTokenSource>::parse_non_ptr_sequence (
3425 ParseFunction parsing_function, EndTokenPred is_end_token,
3426 std::string error_msg) -> std::vector<decltype (parsing_function ())>
3427 {
3428 std::vector<decltype (parsing_function ())> params;
3429
3430 while (!is_end_token (lexer.peek_token ()->get_id ()))
3431 {
3432 auto param = parsing_function ();
3433
3434 if (param.is_error ())
3435 {
3436 // TODO: is it worth throwing away all params just because one
3437 // failed?
3438 Error error (lexer.peek_token ()->get_locus (),
3439 std::move (error_msg));
3440 add_error (std::move (error));
3441
3442 return {};
3443 }
3444
3445 params.push_back (std::move (param));
3446
3447 if (lexer.peek_token ()->get_id () != COMMA)
3448 break;
3449
3450 // skip commas, including trailing commas
3451 lexer.skip_token ();
3452 }
3453
3454 params.shrink_to_fit ();
3455
3456 return params;
3457 }
3458
3459 /* Parses a single lifetime generic parameter (not including comma). */
3460 template <typename ManagedTokenSource>
3461 tl::expected<AST::LifetimeParam, ParseLifetimeParamError>
3462 Parser<ManagedTokenSource>::parse_lifetime_param ()
3463 {
3464 // parse outer attributes, which are optional and may not exist
3465 auto outer_attrs = parse_outer_attributes ();
3466
3467 // save lifetime token - required
3468 const_TokenPtr lifetime_tok = lexer.peek_token ();
3469 if (lifetime_tok->get_id () != LIFETIME)
3470 {
3471 // if lifetime is missing, must not be a lifetime param, so return error
3472 return tl::make_unexpected<ParseLifetimeParamError> ({});
3473 }
3474 lexer.skip_token ();
3475 AST::Lifetime lifetime (AST::Lifetime::NAMED, lifetime_tok->get_str (),
3476 lifetime_tok->get_locus ());
3477
3478 // parse lifetime bounds, if it exists
3479 std::vector<AST::Lifetime> lifetime_bounds;
3480 if (lexer.peek_token ()->get_id () == COLON)
3481 {
3482 // parse lifetime bounds
3483 lifetime_bounds = parse_lifetime_bounds ();
3484 // TODO: have end token passed in?
3485 }
3486
3487 return AST::LifetimeParam (std::move (lifetime), std::move (lifetime_bounds),
3488 std::move (outer_attrs),
3489 lifetime_tok->get_locus ());
3490 }
3491
3492 // Parses type generic parameters. Will also consume any trailing comma.
3493 template <typename ManagedTokenSource>
3494 std::vector<std::unique_ptr<AST::TypeParam>>
3495 Parser<ManagedTokenSource>::parse_type_params ()
3496 {
3497 std::vector<std::unique_ptr<AST::TypeParam>> type_params;
3498
3499 // infinite loop with break on failure as no info on ending token
3500 while (true)
3501 {
3502 std::unique_ptr<AST::TypeParam> type_param = parse_type_param ();
3503
3504 if (type_param == nullptr)
3505 {
3506 // break if fails to parse
3507 break;
3508 }
3509
3510 type_params.push_back (std::move (type_param));
3511
3512 if (lexer.peek_token ()->get_id () != COMMA)
3513 break;
3514
3515 // skip commas, including trailing commas
3516 lexer.skip_token ();
3517 }
3518
3519 type_params.shrink_to_fit ();
3520 return type_params;
3521 }
3522
3523 // Parses type generic parameters. Will also consume any trailing comma.
3524 template <typename ManagedTokenSource>
3525 template <typename EndTokenPred>
3526 std::vector<std::unique_ptr<AST::TypeParam>>
3527 Parser<ManagedTokenSource>::parse_type_params (EndTokenPred is_end_token)
3528 {
3529 std::vector<std::unique_ptr<AST::TypeParam>> type_params;
3530
3531 while (!is_end_token (lexer.peek_token ()->get_id ()))
3532 {
3533 std::unique_ptr<AST::TypeParam> type_param = parse_type_param ();
3534
3535 if (type_param == nullptr)
3536 {
3537 Error error (lexer.peek_token ()->get_locus (),
3538 "failed to parse type param in type params");
3539 add_error (std::move (error));
3540
3541 return {};
3542 }
3543
3544 type_params.push_back (std::move (type_param));
3545
3546 if (lexer.peek_token ()->get_id () != COMMA)
3547 break;
3548
3549 // skip commas, including trailing commas
3550 lexer.skip_token ();
3551 }
3552
3553 type_params.shrink_to_fit ();
3554 return type_params;
3555 /* TODO: this shares most code with parse_lifetime_params - good place to
3556 * use template (i.e. parse_non_ptr_sequence if doable) */
3557 }
3558
3559 /* Parses a single type (generic) parameter, not including commas. May change
3560 * to return value. */
3561 template <typename ManagedTokenSource>
3562 std::unique_ptr<AST::TypeParam>
3563 Parser<ManagedTokenSource>::parse_type_param ()
3564 {
3565 // parse outer attributes, which are optional and may not exist
3566 auto outer_attrs = parse_outer_attributes ();
3567
3568 const_TokenPtr identifier_tok = lexer.peek_token ();
3569 if (identifier_tok->get_id () != IDENTIFIER)
3570 {
3571 // return null as type param can't exist without this required
3572 // identifier
3573 return nullptr;
3574 }
3575 Identifier ident{identifier_tok};
3576 lexer.skip_token ();
3577
3578 // parse type param bounds (if they exist)
3579 std::vector<std::unique_ptr<AST::TypeParamBound>> type_param_bounds;
3580 if (lexer.peek_token ()->get_id () == COLON)
3581 {
3582 lexer.skip_token ();
3583
3584 // parse type param bounds, which may or may not exist
3585 type_param_bounds = parse_type_param_bounds ();
3586 }
3587
3588 // parse type (if it exists)
3589 std::unique_ptr<AST::Type> type = nullptr;
3590 if (lexer.peek_token ()->get_id () == EQUAL)
3591 {
3592 lexer.skip_token ();
3593
3594 // parse type (now required)
3595 type = parse_type ();
3596 if (type == nullptr)
3597 {
3598 Error error (lexer.peek_token ()->get_locus (),
3599 "failed to parse type in type param");
3600 add_error (std::move (error));
3601
3602 return nullptr;
3603 }
3604 }
3605
3606 return std::unique_ptr<AST::TypeParam> (
3607 new AST::TypeParam (std::move (ident), identifier_tok->get_locus (),
3608 std::move (type_param_bounds), std::move (type),
3609 std::move (outer_attrs)));
3610 }
3611
3612 /* Parses regular (i.e. non-generic) parameters in functions or methods. Also
3613 * has end token handling. */
3614 template <typename ManagedTokenSource>
3615 template <typename EndTokenPred>
3616 std::vector<std::unique_ptr<AST::Param>>
3617 Parser<ManagedTokenSource>::parse_function_params (EndTokenPred is_end_token)
3618 {
3619 std::vector<std::unique_ptr<AST::Param>> params;
3620
3621 if (is_end_token (lexer.peek_token ()->get_id ()))
3622 return params;
3623
3624 auto initial_param = parse_function_param ();
3625
3626 // Return empty parameter list if no parameter there
3627 if (initial_param == nullptr)
3628 {
3629 // TODO: is this an error?
3630 return params;
3631 }
3632
3633 params.push_back (std::move (initial_param));
3634
3635 // maybe think of a better control structure here - do-while with an initial
3636 // error state? basically, loop through parameter list until can't find any
3637 // more params
3638 const_TokenPtr t = lexer.peek_token ();
3639 while (t->get_id () == COMMA)
3640 {
3641 // skip comma if applies
3642 lexer.skip_token ();
3643
3644 // TODO: strictly speaking, shouldn't there be no trailing comma?
3645 if (is_end_token (lexer.peek_token ()->get_id ()))
3646 break;
3647
3648 // now, as right paren would break, function param is required
3649 auto param = parse_function_param ();
3650 if (param == nullptr)
3651 {
3652 Error error (lexer.peek_token ()->get_locus (),
3653 "failed to parse function param (in function params)");
3654 add_error (std::move (error));
3655
3656 // skip somewhere?
3657 return std::vector<std::unique_ptr<AST::Param>> ();
3658 }
3659
3660 params.push_back (std::move (param));
3661
3662 t = lexer.peek_token ();
3663 }
3664
3665 params.shrink_to_fit ();
3666 return params;
3667 }
3668
3669 /* Parses a single regular (i.e. non-generic) parameter in a function or
3670 * method, i.e. the "name: type" bit. Also handles it not existing. */
3671 template <typename ManagedTokenSource>
3672 std::unique_ptr<AST::Param>
3673 Parser<ManagedTokenSource>::parse_function_param ()
3674 {
3675 // parse outer attributes if they exist
3676 AST::AttrVec outer_attrs = parse_outer_attributes ();
3677
3678 // TODO: should saved location be at start of outer attributes or pattern?
3679 location_t locus = lexer.peek_token ()->get_locus ();
3680
3681 if (lexer.peek_token ()->get_id () == ELLIPSIS) // Unnamed variadic
3682 {
3683 lexer.skip_token (); // Skip ellipsis
3684 return std::make_unique<AST::VariadicParam> (
3685 AST::VariadicParam (std::move (outer_attrs), locus));
3686 }
3687
3688 std::unique_ptr<AST::Pattern> param_pattern = parse_pattern ();
3689
3690 // create error function param if it doesn't exist
3691 if (param_pattern == nullptr)
3692 {
3693 // skip after something
3694 return nullptr;
3695 }
3696
3697 if (!skip_token (COLON))
3698 {
3699 // skip after something
3700 return nullptr;
3701 }
3702
3703 if (lexer.peek_token ()->get_id () == ELLIPSIS) // Named variadic
3704 {
3705 lexer.skip_token (); // Skip ellipsis
3706 return std::make_unique<AST::VariadicParam> (
3707 AST::VariadicParam (std::move (param_pattern), std::move (outer_attrs),
3708 locus));
3709 }
3710 else
3711 {
3712 std::unique_ptr<AST::Type> param_type = parse_type ();
3713 if (param_type == nullptr)
3714 {
3715 return nullptr;
3716 }
3717 return std::make_unique<AST::FunctionParam> (
3718 AST::FunctionParam (std::move (param_pattern), std::move (param_type),
3719 std::move (outer_attrs), locus));
3720 }
3721 }
3722
3723 /* Parses a function or method return type syntactical construction. Also
3724 * handles a function return type not existing. */
3725 template <typename ManagedTokenSource>
3726 std::unique_ptr<AST::Type>
3727 Parser<ManagedTokenSource>::parse_function_return_type ()
3728 {
3729 if (lexer.peek_token ()->get_id () != RETURN_TYPE)
3730 return nullptr;
3731
3732 // skip return type, as it now obviously exists
3733 lexer.skip_token ();
3734
3735 std::unique_ptr<AST::Type> type = parse_type ();
3736
3737 return type;
3738 }
3739
3740 /* Parses a "where clause" (in a function, struct, method, etc.). Also handles
3741 * a where clause not existing, in which it will return
3742 * WhereClause::create_empty(), which can be checked via
3743 * WhereClause::is_empty(). */
3744 template <typename ManagedTokenSource>
3745 AST::WhereClause
3746 Parser<ManagedTokenSource>::parse_where_clause ()
3747 {
3748 const_TokenPtr where_tok = lexer.peek_token ();
3749 if (where_tok->get_id () != WHERE)
3750 {
3751 // where clause doesn't exist, so create empty one
3752 return AST::WhereClause::create_empty ();
3753 }
3754
3755 lexer.skip_token ();
3756
3757 /* parse where clause items - this is not a separate rule in the reference
3758 * so won't be here */
3759 std::vector<std::unique_ptr<AST::WhereClauseItem>> where_clause_items;
3760
3761 std::vector<AST::LifetimeParam> for_lifetimes;
3762 if (lexer.peek_token ()->get_id () == FOR)
3763 for_lifetimes = parse_for_lifetimes ();
3764
3765 /* HACK: where clauses end with a right curly or semicolon or equals in all
3766 * uses currently */
3767 const_TokenPtr t = lexer.peek_token ();
3768 while (t->get_id () != LEFT_CURLY && t->get_id () != SEMICOLON
3769 && t->get_id () != EQUAL)
3770 {
3771 std::unique_ptr<AST::WhereClauseItem> where_clause_item
3772 = parse_where_clause_item (for_lifetimes);
3773
3774 if (where_clause_item == nullptr)
3775 {
3776 Error error (t->get_locus (), "failed to parse where clause item");
3777 add_error (std::move (error));
3778
3779 return AST::WhereClause::create_empty ();
3780 }
3781
3782 where_clause_items.push_back (std::move (where_clause_item));
3783
3784 // also skip comma if it exists
3785 if (lexer.peek_token ()->get_id () != COMMA)
3786 break;
3787
3788 lexer.skip_token ();
3789 t = lexer.peek_token ();
3790 }
3791
3792 where_clause_items.shrink_to_fit ();
3793 return AST::WhereClause (std::move (where_clause_items));
3794 }
3795
3796 /* Parses a where clause item (lifetime or type bound). Does not parse any
3797 * commas. */
3798 template <typename ManagedTokenSource>
3799 std::unique_ptr<AST::WhereClauseItem>
3800 Parser<ManagedTokenSource>::parse_where_clause_item (
3801 const std::vector<AST::LifetimeParam> &outer_for_lifetimes)
3802 {
3803 // shitty cheat way of determining lifetime or type bound - test for
3804 // lifetime
3805 const_TokenPtr t = lexer.peek_token ();
3806
3807 if (t->get_id () == LIFETIME)
3808 return parse_lifetime_where_clause_item ();
3809 else
3810 return parse_type_bound_where_clause_item (outer_for_lifetimes);
3811 }
3812
3813 // Parses a lifetime where clause item.
3814 template <typename ManagedTokenSource>
3815 std::unique_ptr<AST::LifetimeWhereClauseItem>
3816 Parser<ManagedTokenSource>::parse_lifetime_where_clause_item ()
3817 {
3818 auto parsed_lifetime = parse_lifetime (false);
3819 if (!parsed_lifetime)
3820 {
3821 // TODO: error here?
3822 return nullptr;
3823 }
3824 auto lifetime = parsed_lifetime.value ();
3825
3826 if (!skip_token (COLON))
3827 {
3828 // TODO: skip after somewhere
3829 return nullptr;
3830 }
3831
3832 std::vector<AST::Lifetime> lifetime_bounds = parse_lifetime_bounds ();
3833 // TODO: have end token passed in?
3834
3835 location_t locus = lifetime.get_locus ();
3836
3837 return std::unique_ptr<AST::LifetimeWhereClauseItem> (
3838 new AST::LifetimeWhereClauseItem (std::move (lifetime),
3839 std::move (lifetime_bounds), locus));
3840 }
3841
3842 // Parses a type bound where clause item.
3843 template <typename ManagedTokenSource>
3844 std::unique_ptr<AST::TypeBoundWhereClauseItem>
3845 Parser<ManagedTokenSource>::parse_type_bound_where_clause_item (
3846 const std::vector<AST::LifetimeParam> &outer_for_lifetimes)
3847 {
3848 std::vector<AST::LifetimeParam> for_lifetimes = outer_for_lifetimes;
3849
3850 std::unique_ptr<AST::Type> type = parse_type ();
3851 if (type == nullptr)
3852 {
3853 return nullptr;
3854 }
3855
3856 if (!skip_token (COLON))
3857 {
3858 // TODO: skip after somewhere
3859 return nullptr;
3860 }
3861
3862 if (lexer.peek_token ()->get_id () == FOR)
3863 {
3864 auto for_lifetimes_inner = parse_for_lifetimes ();
3865 for_lifetimes.insert (for_lifetimes.end (), for_lifetimes_inner.begin (),
3866 for_lifetimes_inner.end ());
3867 }
3868
3869 // parse type param bounds if they exist
3870 std::vector<std::unique_ptr<AST::TypeParamBound>> type_param_bounds
3871 = parse_type_param_bounds ();
3872
3873 location_t locus = lexer.peek_token ()->get_locus ();
3874
3875 return std::unique_ptr<AST::TypeBoundWhereClauseItem> (
3876 new AST::TypeBoundWhereClauseItem (std::move (for_lifetimes),
3877 std::move (type),
3878 std::move (type_param_bounds), locus));
3879 }
3880
3881 // Parses a for lifetimes clause, including the for keyword and angle
3882 // brackets.
3883 template <typename ManagedTokenSource>
3884 std::vector<AST::LifetimeParam>
3885 Parser<ManagedTokenSource>::parse_for_lifetimes ()
3886 {
3887 std::vector<AST::LifetimeParam> params;
3888
3889 if (!skip_token (FOR))
3890 {
3891 // skip after somewhere?
3892 return params;
3893 }
3894
3895 if (!skip_token (LEFT_ANGLE))
3896 {
3897 // skip after somewhere?
3898 return params;
3899 }
3900
3901 /* cannot specify end token due to parsing problems with '>' tokens being
3902 * nested */
3903 params = parse_lifetime_params_objs (is_right_angle_tok);
3904
3905 if (!skip_generics_right_angle ())
3906 {
3907 // DEBUG
3908 rust_debug ("failed to skip generics right angle after (supposedly) "
3909 "finished parsing where clause items");
3910 // ok, well this gets called.
3911
3912 // skip after somewhere?
3913 return params;
3914 }
3915
3916 return params;
3917 }
3918
3919 // Parses type parameter bounds in where clause or generic arguments.
3920 template <typename ManagedTokenSource>
3921 std::vector<std::unique_ptr<AST::TypeParamBound>>
3922 Parser<ManagedTokenSource>::parse_type_param_bounds ()
3923 {
3924 std::vector<std::unique_ptr<AST::TypeParamBound>> type_param_bounds;
3925
3926 std::unique_ptr<AST::TypeParamBound> initial_bound
3927 = parse_type_param_bound ();
3928
3929 // quick exit if null
3930 if (initial_bound == nullptr)
3931 {
3932 /* error? type param bounds must have at least one term, but are bounds
3933 * optional? */
3934 return type_param_bounds;
3935 }
3936 type_param_bounds.push_back (std::move (initial_bound));
3937
3938 while (lexer.peek_token ()->get_id () == PLUS)
3939 {
3940 lexer.skip_token ();
3941
3942 std::unique_ptr<AST::TypeParamBound> bound = parse_type_param_bound ();
3943 if (bound == nullptr)
3944 {
3945 /* not an error: bound is allowed to be null as trailing plus is
3946 * allowed */
3947 return type_param_bounds;
3948 }
3949
3950 type_param_bounds.push_back (std::move (bound));
3951 }
3952
3953 type_param_bounds.shrink_to_fit ();
3954 return type_param_bounds;
3955 }
3956
3957 /* Parses type parameter bounds in where clause or generic arguments, with end
3958 * token handling. */
3959 template <typename ManagedTokenSource>
3960 template <typename EndTokenPred>
3961 std::vector<std::unique_ptr<AST::TypeParamBound>>
3962 Parser<ManagedTokenSource>::parse_type_param_bounds (EndTokenPred is_end_token)
3963 {
3964 std::vector<std::unique_ptr<AST::TypeParamBound>> type_param_bounds;
3965
3966 std::unique_ptr<AST::TypeParamBound> initial_bound
3967 = parse_type_param_bound ();
3968
3969 // quick exit if null
3970 if (initial_bound == nullptr)
3971 {
3972 /* error? type param bounds must have at least one term, but are bounds
3973 * optional? */
3974 return type_param_bounds;
3975 }
3976 type_param_bounds.push_back (std::move (initial_bound));
3977
3978 while (lexer.peek_token ()->get_id () == PLUS)
3979 {
3980 lexer.skip_token ();
3981
3982 // break if end token character
3983 if (is_end_token (lexer.peek_token ()->get_id ()))
3984 break;
3985
3986 std::unique_ptr<AST::TypeParamBound> bound = parse_type_param_bound ();
3987 if (bound == nullptr)
3988 {
3989 // TODO how wise is it to ditch all bounds if only one failed?
3990 Error error (lexer.peek_token ()->get_locus (),
3991 "failed to parse type param bound in type param bounds");
3992 add_error (std::move (error));
3993
3994 return {};
3995 }
3996
3997 type_param_bounds.push_back (std::move (bound));
3998 }
3999
4000 type_param_bounds.shrink_to_fit ();
4001 return type_param_bounds;
4002 }
4003
4004 /* Parses a single type parameter bound in a where clause or generic argument.
4005 * Does not parse the '+' between arguments. */
4006 template <typename ManagedTokenSource>
4007 std::unique_ptr<AST::TypeParamBound>
4008 Parser<ManagedTokenSource>::parse_type_param_bound ()
4009 {
4010 // shitty cheat way of determining lifetime or trait bound - test for
4011 // lifetime
4012 const_TokenPtr t = lexer.peek_token ();
4013 switch (t->get_id ())
4014 {
4015 case LIFETIME:
4016 return std::unique_ptr<AST::Lifetime> (
4017 new AST::Lifetime (parse_lifetime (false).value ()));
4018 case LEFT_PAREN:
4019 case QUESTION_MARK:
4020 case FOR:
4021 case IDENTIFIER:
4022 case SUPER:
4023 case SELF:
4024 case SELF_ALIAS:
4025 case CRATE:
4026 case DOLLAR_SIGN:
4027 case SCOPE_RESOLUTION:
4028 return parse_trait_bound ();
4029 default:
4030 // don't error - assume this is fine TODO
4031 return nullptr;
4032 }
4033 }
4034
4035 // Parses a trait bound type param bound.
4036 template <typename ManagedTokenSource>
4037 std::unique_ptr<AST::TraitBound>
4038 Parser<ManagedTokenSource>::parse_trait_bound ()
4039 {
4040 bool has_parens = false;
4041 bool has_question_mark = false;
4042
4043 location_t locus = lexer.peek_token ()->get_locus ();
4044
4045 /* parse optional `for lifetimes`. */
4046 std::vector<AST::LifetimeParam> for_lifetimes;
4047 if (lexer.peek_token ()->get_id () == FOR)
4048 for_lifetimes = parse_for_lifetimes ();
4049
4050 // handle trait bound being in parentheses
4051 if (lexer.peek_token ()->get_id () == LEFT_PAREN)
4052 {
4053 has_parens = true;
4054 lexer.skip_token ();
4055 }
4056
4057 // handle having question mark (optional)
4058 if (lexer.peek_token ()->get_id () == QUESTION_MARK)
4059 {
4060 has_question_mark = true;
4061 lexer.skip_token ();
4062 }
4063
4064 // handle TypePath
4065 AST::TypePath type_path = parse_type_path ();
4066
4067 // handle closing parentheses
4068 if (has_parens)
4069 {
4070 if (!skip_token (RIGHT_PAREN))
4071 {
4072 return nullptr;
4073 }
4074 }
4075
4076 return std::unique_ptr<AST::TraitBound> (
4077 new AST::TraitBound (std::move (type_path), locus, has_parens,
4078 has_question_mark, std::move (for_lifetimes)));
4079 }
4080
4081 // Parses lifetime bounds.
4082 template <typename ManagedTokenSource>
4083 std::vector<AST::Lifetime>
4084 Parser<ManagedTokenSource>::parse_lifetime_bounds ()
4085 {
4086 std::vector<AST::Lifetime> lifetime_bounds;
4087
4088 while (true)
4089 {
4090 auto lifetime = parse_lifetime (false);
4091
4092 // quick exit for parsing failure
4093 if (!lifetime)
4094 break;
4095
4096 lifetime_bounds.push_back (std::move (lifetime.value ()));
4097
4098 /* plus is maybe not allowed at end - spec defines it weirdly, so
4099 * assuming allowed at end */
4100 if (lexer.peek_token ()->get_id () != PLUS)
4101 break;
4102
4103 lexer.skip_token ();
4104 }
4105
4106 lifetime_bounds.shrink_to_fit ();
4107 return lifetime_bounds;
4108 }
4109
4110 // Parses lifetime bounds, with added check for ending token.
4111 template <typename ManagedTokenSource>
4112 template <typename EndTokenPred>
4113 std::vector<AST::Lifetime>
4114 Parser<ManagedTokenSource>::parse_lifetime_bounds (EndTokenPred is_end_token)
4115 {
4116 std::vector<AST::Lifetime> lifetime_bounds;
4117
4118 while (!is_end_token (lexer.peek_token ()->get_id ()))
4119 {
4120 auto lifetime = parse_lifetime (false);
4121
4122 if (!lifetime)
4123 {
4124 /* TODO: is it worth throwing away all lifetime bound info just
4125 * because one failed? */
4126 Error error (lexer.peek_token ()->get_locus (),
4127 "failed to parse lifetime in lifetime bounds");
4128 add_error (std::move (error));
4129
4130 return {};
4131 }
4132
4133 lifetime_bounds.push_back (std::move (lifetime.value ()));
4134
4135 /* plus is maybe not allowed at end - spec defines it weirdly, so
4136 * assuming allowed at end */
4137 if (lexer.peek_token ()->get_id () != PLUS)
4138 break;
4139
4140 lexer.skip_token ();
4141 }
4142
4143 lifetime_bounds.shrink_to_fit ();
4144 return lifetime_bounds;
4145 }
4146
4147 /* Parses a lifetime token (named, 'static, or '_). Also handles lifetime not
4148 * existing. */
4149 template <typename ManagedTokenSource>
4150 tl::expected<AST::Lifetime, ParseLifetimeError>
4151 Parser<ManagedTokenSource>::parse_lifetime (bool allow_elided)
4152 {
4153 const_TokenPtr lifetime_tok = lexer.peek_token ();
4154 if (lifetime_tok->get_id () != LIFETIME)
4155 {
4156 if (allow_elided)
4157 {
4158 return AST::Lifetime::elided ();
4159 }
4160 else
4161 {
4162 return tl::make_unexpected<ParseLifetimeError> ({});
4163 }
4164 }
4165 lexer.skip_token ();
4166
4167 return lifetime_from_token (lifetime_tok);
4168 }
4169
4170 template <typename ManagedTokenSource>
4171 AST::Lifetime
4172 Parser<ManagedTokenSource>::lifetime_from_token (const_TokenPtr tok)
4173 {
4174 location_t locus = tok->get_locus ();
4175 std::string lifetime_ident = tok->get_str ();
4176
4177 if (lifetime_ident == "static")
4178 {
4179 return AST::Lifetime (AST::Lifetime::STATIC, "", locus);
4180 }
4181 else if (lifetime_ident == "_")
4182 {
4183 // Explicitly and implicitly elided lifetimes follow the same rules.
4184 return AST::Lifetime (AST::Lifetime::WILDCARD, "", locus);
4185 }
4186 else
4187 {
4188 return AST::Lifetime (AST::Lifetime::NAMED, std::move (lifetime_ident),
4189 locus);
4190 }
4191 }
4192
4193 template <typename ManagedTokenSource>
4194 std::unique_ptr<AST::ExternalTypeItem>
4195 Parser<ManagedTokenSource>::parse_external_type_item (AST::Visibility vis,
4196 AST::AttrVec outer_attrs)
4197 {
4198 location_t locus = lexer.peek_token ()->get_locus ();
4199 skip_token (TYPE);
4200
4201 const_TokenPtr alias_name_tok = expect_token (IDENTIFIER);
4202 if (alias_name_tok == nullptr)
4203 {
4204 Error error (lexer.peek_token ()->get_locus (),
4205 "could not parse identifier in external opaque type");
4206 add_error (std::move (error));
4207
4208 skip_after_semicolon ();
4209 return nullptr;
4210 }
4211
4212 if (!skip_token (SEMICOLON))
4213 return nullptr;
4214
4215 return std::unique_ptr<AST::ExternalTypeItem> (
4216 new AST::ExternalTypeItem (alias_name_tok->get_str (), std::move (vis),
4217 std::move (outer_attrs), std::move (locus)));
4218 }
4219
4220 // Parses a "type alias" (typedef) item.
4221 template <typename ManagedTokenSource>
4222 std::unique_ptr<AST::TypeAlias>
4223 Parser<ManagedTokenSource>::parse_type_alias (AST::Visibility vis,
4224 AST::AttrVec outer_attrs)
4225 {
4226 location_t locus = lexer.peek_token ()->get_locus ();
4227 skip_token (TYPE);
4228
4229 // TODO: use this token for identifier when finished that
4230 const_TokenPtr alias_name_tok = expect_token (IDENTIFIER);
4231 if (alias_name_tok == nullptr)
4232 {
4233 Error error (lexer.peek_token ()->get_locus (),
4234 "could not parse identifier in type alias");
4235 add_error (std::move (error));
4236
4237 skip_after_semicolon ();
4238 return nullptr;
4239 }
4240 Identifier alias_name{alias_name_tok};
4241
4242 // parse generic params, which may not exist
4243 std::vector<std::unique_ptr<AST::GenericParam>> generic_params
4244 = parse_generic_params_in_angles ();
4245
4246 // parse where clause, which may not exist
4247 AST::WhereClause where_clause = parse_where_clause ();
4248
4249 if (!skip_token (EQUAL))
4250 {
4251 skip_after_semicolon ();
4252 return nullptr;
4253 }
4254
4255 std::unique_ptr<AST::Type> type_to_alias = parse_type ();
4256
4257 if (!skip_token (SEMICOLON))
4258 {
4259 // should be skipping past this, not the next line
4260 return nullptr;
4261 }
4262
4263 return std::unique_ptr<AST::TypeAlias> (
4264 new AST::TypeAlias (std::move (alias_name), std::move (generic_params),
4265 std::move (where_clause), std::move (type_to_alias),
4266 std::move (vis), std::move (outer_attrs), locus));
4267 }
4268
4269 // Parse a struct item AST node.
4270 template <typename ManagedTokenSource>
4271 std::unique_ptr<AST::Struct>
4272 Parser<ManagedTokenSource>::parse_struct (AST::Visibility vis,
4273 AST::AttrVec outer_attrs)
4274 {
4275 /* TODO: determine best way to parse the proper struct vs tuple struct -
4276 * share most of initial constructs so lookahead might be impossible, and if
4277 * not probably too expensive. Best way is probably unified parsing for the
4278 * initial parts and then pass them in as params to more derived functions.
4279 * Alternatively, just parse everything in this one function - do this if
4280 * function not too long. */
4281
4282 /* Proper struct <- 'struct' IDENTIFIER generic_params? where_clause? ( '{'
4283 * struct_fields? '}' | ';' ) */
4284 /* Tuple struct <- 'struct' IDENTIFIER generic_params? '(' tuple_fields? ')'
4285 * where_clause? ';' */
4286 location_t locus = lexer.peek_token ()->get_locus ();
4287 skip_token (STRUCT_KW);
4288
4289 // parse struct name
4290 const_TokenPtr name_tok = expect_token (IDENTIFIER);
4291 if (name_tok == nullptr)
4292 {
4293 Error error (lexer.peek_token ()->get_locus (),
4294 "could not parse struct or tuple struct identifier");
4295 add_error (std::move (error));
4296
4297 // skip after somewhere?
4298 return nullptr;
4299 }
4300 Identifier struct_name{name_tok};
4301
4302 // parse generic params, which may or may not exist
4303 std::vector<std::unique_ptr<AST::GenericParam>> generic_params
4304 = parse_generic_params_in_angles ();
4305
4306 // branch on next token - determines whether proper struct or tuple struct
4307 if (lexer.peek_token ()->get_id () == LEFT_PAREN)
4308 {
4309 // tuple struct
4310
4311 // skip left parenthesis
4312 lexer.skip_token ();
4313
4314 // parse tuple fields
4315 std::vector<AST::TupleField> tuple_fields;
4316 // Might be empty tuple for unit tuple struct.
4317 if (lexer.peek_token ()->get_id () == RIGHT_PAREN)
4318 tuple_fields = std::vector<AST::TupleField> ();
4319 else
4320 tuple_fields = parse_tuple_fields ();
4321
4322 // tuple parameters must have closing parenthesis
4323 if (!skip_token (RIGHT_PAREN))
4324 {
4325 skip_after_semicolon ();
4326 return nullptr;
4327 }
4328
4329 // parse where clause, which is optional
4330 AST::WhereClause where_clause = parse_where_clause ();
4331
4332 if (!skip_token (SEMICOLON))
4333 {
4334 // can't skip after semicolon because it's meant to be here
4335 return nullptr;
4336 }
4337
4338 return std::unique_ptr<AST::TupleStruct> (
4339 new AST::TupleStruct (std::move (tuple_fields), std::move (struct_name),
4340 std::move (generic_params),
4341 std::move (where_clause), std::move (vis),
4342 std::move (outer_attrs), locus));
4343 }
4344
4345 // assume it is a proper struct being parsed and continue outside of switch
4346 // - label only here to suppress warning
4347
4348 // parse where clause, which is optional
4349 AST::WhereClause where_clause = parse_where_clause ();
4350
4351 // branch on next token - determines whether struct is a unit struct
4352 const_TokenPtr t = lexer.peek_token ();
4353 switch (t->get_id ())
4354 {
4355 case LEFT_CURLY: {
4356 // struct with body
4357
4358 // skip curly bracket
4359 lexer.skip_token ();
4360
4361 // parse struct fields, if any
4362 std::vector<AST::StructField> struct_fields
4363 = parse_struct_fields ([] (TokenId id) { return id == RIGHT_CURLY; });
4364
4365 if (!skip_token (RIGHT_CURLY))
4366 {
4367 // skip somewhere?
4368 return nullptr;
4369 }
4370
4371 return std::unique_ptr<AST::StructStruct> (new AST::StructStruct (
4372 std::move (struct_fields), std::move (struct_name),
4373 std::move (generic_params), std::move (where_clause), false,
4374 std::move (vis), std::move (outer_attrs), locus));
4375 }
4376 case SEMICOLON:
4377 // unit struct declaration
4378
4379 lexer.skip_token ();
4380
4381 return std::unique_ptr<AST::StructStruct> (
4382 new AST::StructStruct (std::move (struct_name),
4383 std::move (generic_params),
4384 std::move (where_clause), std::move (vis),
4385 std::move (outer_attrs), locus));
4386 default:
4387 add_error (Error (t->get_locus (),
4388 "unexpected token %qs in struct declaration",
4389 t->get_token_description ()));
4390
4391 // skip somewhere?
4392 return nullptr;
4393 }
4394 }
4395
4396 // Parses struct fields in struct declarations.
4397 template <typename ManagedTokenSource>
4398 std::vector<AST::StructField>
4399 Parser<ManagedTokenSource>::parse_struct_fields ()
4400 {
4401 std::vector<AST::StructField> fields;
4402
4403 AST::StructField initial_field = parse_struct_field ();
4404
4405 // Return empty field list if no field there
4406 if (initial_field.is_error ())
4407 return fields;
4408
4409 fields.push_back (std::move (initial_field));
4410
4411 while (lexer.peek_token ()->get_id () == COMMA)
4412 {
4413 lexer.skip_token ();
4414
4415 AST::StructField field = parse_struct_field ();
4416
4417 if (field.is_error ())
4418 {
4419 // would occur with trailing comma, so allowed
4420 break;
4421 }
4422
4423 fields.push_back (std::move (field));
4424 }
4425
4426 fields.shrink_to_fit ();
4427 return fields;
4428 // TODO: template if possible (parse_non_ptr_seq)
4429 }
4430
4431 // Parses struct fields in struct declarations.
4432 template <typename ManagedTokenSource>
4433 template <typename EndTokenPred>
4434 std::vector<AST::StructField>
4435 Parser<ManagedTokenSource>::parse_struct_fields (EndTokenPred is_end_tok)
4436 {
4437 std::vector<AST::StructField> fields;
4438
4439 AST::StructField initial_field = parse_struct_field ();
4440
4441 // Return empty field list if no field there
4442 if (initial_field.is_error ())
4443 return fields;
4444
4445 fields.push_back (std::move (initial_field));
4446
4447 while (lexer.peek_token ()->get_id () == COMMA)
4448 {
4449 lexer.skip_token ();
4450
4451 if (is_end_tok (lexer.peek_token ()->get_id ()))
4452 break;
4453
4454 AST::StructField field = parse_struct_field ();
4455 if (field.is_error ())
4456 {
4457 /* TODO: should every field be ditched just because one couldn't be
4458 * parsed? */
4459 Error error (lexer.peek_token ()->get_locus (),
4460 "failed to parse struct field in struct fields");
4461 add_error (std::move (error));
4462
4463 return {};
4464 }
4465
4466 fields.push_back (std::move (field));
4467 }
4468
4469 fields.shrink_to_fit ();
4470 return fields;
4471 // TODO: template if possible (parse_non_ptr_seq)
4472 }
4473
4474 // Parses a single struct field (in a struct definition). Does not parse
4475 // commas.
4476 template <typename ManagedTokenSource>
4477 AST::StructField
4478 Parser<ManagedTokenSource>::parse_struct_field ()
4479 {
4480 // parse outer attributes, if they exist
4481 AST::AttrVec outer_attrs = parse_outer_attributes ();
4482
4483 // parse visibility, if it exists
4484 AST::Visibility vis = parse_visibility ();
4485
4486 location_t locus = lexer.peek_token ()->get_locus ();
4487
4488 // parse field name
4489 const_TokenPtr field_name_tok = lexer.peek_token ();
4490 if (field_name_tok->get_id () != IDENTIFIER)
4491 {
4492 // if not identifier, assumes there is no struct field and exits - not
4493 // necessarily error
4494 return AST::StructField::create_error ();
4495 }
4496 Identifier field_name{field_name_tok};
4497 lexer.skip_token ();
4498
4499 if (!skip_token (COLON))
4500 {
4501 // skip after somewhere?
4502 return AST::StructField::create_error ();
4503 }
4504
4505 // parse field type - this is required
4506 std::unique_ptr<AST::Type> field_type = parse_type ();
4507 if (field_type == nullptr)
4508 {
4509 Error error (lexer.peek_token ()->get_locus (),
4510 "could not parse type in struct field definition");
4511 add_error (std::move (error));
4512
4513 // skip after somewhere
4514 return AST::StructField::create_error ();
4515 }
4516
4517 return AST::StructField (std::move (field_name), std::move (field_type),
4518 std::move (vis), locus, std::move (outer_attrs));
4519 }
4520
4521 // Parses tuple fields in tuple/tuple struct declarations.
4522 template <typename ManagedTokenSource>
4523 std::vector<AST::TupleField>
4524 Parser<ManagedTokenSource>::parse_tuple_fields ()
4525 {
4526 std::vector<AST::TupleField> fields;
4527
4528 AST::TupleField initial_field = parse_tuple_field ();
4529
4530 // Return empty field list if no field there
4531 if (initial_field.is_error ())
4532 {
4533 return fields;
4534 }
4535
4536 fields.push_back (std::move (initial_field));
4537
4538 // maybe think of a better control structure here - do-while with an initial
4539 // error state? basically, loop through field list until can't find any more
4540 // params HACK: all current syntax uses of tuple fields have them ending
4541 // with a right paren token
4542 const_TokenPtr t = lexer.peek_token ();
4543 while (t->get_id () == COMMA)
4544 {
4545 // skip comma if applies - e.g. trailing comma
4546 lexer.skip_token ();
4547
4548 // break out due to right paren if it exists
4549 if (lexer.peek_token ()->get_id () == RIGHT_PAREN)
4550 {
4551 break;
4552 }
4553
4554 AST::TupleField field = parse_tuple_field ();
4555 if (field.is_error ())
4556 {
4557 Error error (lexer.peek_token ()->get_locus (),
4558 "failed to parse tuple field in tuple fields");
4559 add_error (std::move (error));
4560
4561 return std::vector<AST::TupleField> ();
4562 }
4563
4564 fields.push_back (std::move (field));
4565
4566 t = lexer.peek_token ();
4567 }
4568
4569 fields.shrink_to_fit ();
4570 return fields;
4571
4572 // TODO: this shares basically all code with function params and struct
4573 // fields
4574 // - templates?
4575 }
4576
4577 /* Parses a single tuple struct field in a tuple struct definition. Does not
4578 * parse commas. */
4579 template <typename ManagedTokenSource>
4580 AST::TupleField
4581 Parser<ManagedTokenSource>::parse_tuple_field ()
4582 {
4583 // parse outer attributes if they exist
4584 AST::AttrVec outer_attrs = parse_outer_attributes ();
4585
4586 // parse visibility if it exists
4587 AST::Visibility vis = parse_visibility ();
4588
4589 location_t locus = lexer.peek_token ()->get_locus ();
4590
4591 // parse type, which is required
4592 std::unique_ptr<AST::Type> field_type = parse_type ();
4593 if (field_type == nullptr)
4594 {
4595 // error if null
4596 Error error (lexer.peek_token ()->get_locus (),
4597 "could not parse type in tuple struct field");
4598 add_error (std::move (error));
4599
4600 // skip after something
4601 return AST::TupleField::create_error ();
4602 }
4603
4604 return AST::TupleField (std::move (field_type), std::move (vis), locus,
4605 std::move (outer_attrs));
4606 }
4607
4608 // Parses a Rust "enum" tagged union item definition.
4609 template <typename ManagedTokenSource>
4610 std::unique_ptr<AST::Enum>
4611 Parser<ManagedTokenSource>::parse_enum (AST::Visibility vis,
4612 AST::AttrVec outer_attrs)
4613 {
4614 location_t locus = lexer.peek_token ()->get_locus ();
4615 skip_token (ENUM_KW);
4616
4617 // parse enum name
4618 const_TokenPtr enum_name_tok = expect_token (IDENTIFIER);
4619 if (enum_name_tok == nullptr)
4620 return nullptr;
4621
4622 Identifier enum_name = {enum_name_tok};
4623
4624 // parse generic params (of enum container, not enum variants) if they exist
4625 std::vector<std::unique_ptr<AST::GenericParam>> generic_params
4626 = parse_generic_params_in_angles ();
4627
4628 // parse where clause if it exists
4629 AST::WhereClause where_clause = parse_where_clause ();
4630
4631 if (!skip_token (LEFT_CURLY))
4632 {
4633 skip_after_end_block ();
4634 return nullptr;
4635 }
4636
4637 // parse actual enum variant definitions
4638 std::vector<std::unique_ptr<AST::EnumItem>> enum_items
4639 = parse_enum_items ([] (TokenId id) { return id == RIGHT_CURLY; });
4640
4641 if (!skip_token (RIGHT_CURLY))
4642 {
4643 skip_after_end_block ();
4644 return nullptr;
4645 }
4646
4647 return std::unique_ptr<AST::Enum> (
4648 new AST::Enum (std::move (enum_name), std::move (vis),
4649 std::move (generic_params), std::move (where_clause),
4650 std::move (enum_items), std::move (outer_attrs), locus));
4651 }
4652
4653 // Parses the enum variants inside an enum definiton.
4654 template <typename ManagedTokenSource>
4655 std::vector<std::unique_ptr<AST::EnumItem>>
4656 Parser<ManagedTokenSource>::parse_enum_items ()
4657 {
4658 std::vector<std::unique_ptr<AST::EnumItem>> items;
4659
4660 std::unique_ptr<AST::EnumItem> initial_item = parse_enum_item ();
4661
4662 // Return empty item list if no field there
4663 if (initial_item == nullptr)
4664 return items;
4665
4666 items.push_back (std::move (initial_item));
4667
4668 while (lexer.peek_token ()->get_id () == COMMA)
4669 {
4670 lexer.skip_token ();
4671
4672 std::unique_ptr<AST::EnumItem> item = parse_enum_item ();
4673 if (item == nullptr)
4674 {
4675 // this would occur with a trailing comma, which is allowed
4676 break;
4677 }
4678
4679 items.push_back (std::move (item));
4680 }
4681
4682 items.shrink_to_fit ();
4683 return items;
4684
4685 /* TODO: use template if doable (parse_non_ptr_sequence) */
4686 }
4687
4688 // Parses the enum variants inside an enum definiton.
4689 template <typename ManagedTokenSource>
4690 template <typename EndTokenPred>
4691 std::vector<std::unique_ptr<AST::EnumItem>>
4692 Parser<ManagedTokenSource>::parse_enum_items (EndTokenPred is_end_tok)
4693 {
4694 std::vector<std::unique_ptr<AST::EnumItem>> items;
4695
4696 std::unique_ptr<AST::EnumItem> initial_item = parse_enum_item ();
4697
4698 // Return empty item list if no field there
4699 if (initial_item == nullptr)
4700 return items;
4701
4702 items.push_back (std::move (initial_item));
4703
4704 while (lexer.peek_token ()->get_id () == COMMA)
4705 {
4706 lexer.skip_token ();
4707
4708 if (is_end_tok (lexer.peek_token ()->get_id ()))
4709 break;
4710
4711 std::unique_ptr<AST::EnumItem> item = parse_enum_item ();
4712 if (item == nullptr)
4713 {
4714 /* TODO should this ignore all successfully parsed enum items just
4715 * because one failed? */
4716 Error error (lexer.peek_token ()->get_locus (),
4717 "failed to parse enum item in enum items");
4718 add_error (std::move (error));
4719
4720 return {};
4721 }
4722
4723 items.push_back (std::move (item));
4724 }
4725
4726 items.shrink_to_fit ();
4727 return items;
4728
4729 /* TODO: use template if doable (parse_non_ptr_sequence) */
4730 }
4731
4732 /* Parses a single enum variant item in an enum definition. Does not parse
4733 * commas. */
4734 template <typename ManagedTokenSource>
4735 std::unique_ptr<AST::EnumItem>
4736 Parser<ManagedTokenSource>::parse_enum_item ()
4737 {
4738 // parse outer attributes if they exist
4739 AST::AttrVec outer_attrs = parse_outer_attributes ();
4740
4741 // parse visibility, which may or may not exist
4742 AST::Visibility vis = parse_visibility ();
4743
4744 // parse name for enum item, which is required
4745 const_TokenPtr item_name_tok = lexer.peek_token ();
4746 if (item_name_tok->get_id () != IDENTIFIER)
4747 {
4748 // this may not be an error but it means there is no enum item here
4749 return nullptr;
4750 }
4751 lexer.skip_token ();
4752 Identifier item_name{item_name_tok};
4753
4754 // branch based on next token
4755 const_TokenPtr t = lexer.peek_token ();
4756 switch (t->get_id ())
4757 {
4758 case LEFT_PAREN: {
4759 // tuple enum item
4760 lexer.skip_token ();
4761
4762 std::vector<AST::TupleField> tuple_fields;
4763 // Might be empty tuple for unit tuple enum variant.
4764 if (lexer.peek_token ()->get_id () == RIGHT_PAREN)
4765 tuple_fields = std::vector<AST::TupleField> ();
4766 else
4767 tuple_fields = parse_tuple_fields ();
4768
4769 if (!skip_token (RIGHT_PAREN))
4770 {
4771 // skip after somewhere
4772 return nullptr;
4773 }
4774
4775 return std::unique_ptr<AST::EnumItemTuple> (new AST::EnumItemTuple (
4776 std::move (item_name), std::move (vis), std::move (tuple_fields),
4777 std::move (outer_attrs), item_name_tok->get_locus ()));
4778 }
4779 case LEFT_CURLY: {
4780 // struct enum item
4781 lexer.skip_token ();
4782
4783 std::vector<AST::StructField> struct_fields
4784 = parse_struct_fields ([] (TokenId id) { return id == RIGHT_CURLY; });
4785
4786 if (!skip_token (RIGHT_CURLY))
4787 {
4788 // skip after somewhere
4789 return nullptr;
4790 }
4791
4792 return std::unique_ptr<AST::EnumItemStruct> (new AST::EnumItemStruct (
4793 std::move (item_name), std::move (vis), std::move (struct_fields),
4794 std::move (outer_attrs), item_name_tok->get_locus ()));
4795 }
4796 case EQUAL: {
4797 // discriminant enum item
4798 lexer.skip_token ();
4799
4800 std::unique_ptr<AST::Expr> discriminant_expr = parse_expr ();
4801
4802 return std::unique_ptr<AST::EnumItemDiscriminant> (
4803 new AST::EnumItemDiscriminant (std::move (item_name), std::move (vis),
4804 std::move (discriminant_expr),
4805 std::move (outer_attrs),
4806 item_name_tok->get_locus ()));
4807 }
4808 default:
4809 // regular enum with just an identifier
4810 return std::unique_ptr<AST::EnumItem> (
4811 new AST::EnumItem (std::move (item_name), std::move (vis),
4812 std::move (outer_attrs),
4813 item_name_tok->get_locus ()));
4814 }
4815 }
4816
4817 // Parses a C-style (and C-compat) untagged union declaration.
4818 template <typename ManagedTokenSource>
4819 std::unique_ptr<AST::Union>
4820 Parser<ManagedTokenSource>::parse_union (AST::Visibility vis,
4821 AST::AttrVec outer_attrs)
4822 {
4823 /* hack - "weak keyword" by finding identifier called "union" (lookahead in
4824 * item switch) */
4825 const_TokenPtr union_keyword = expect_token (IDENTIFIER);
4826 rust_assert (union_keyword->get_str () == Values::WeakKeywords::UNION);
4827 location_t locus = union_keyword->get_locus ();
4828
4829 // parse actual union name
4830 const_TokenPtr union_name_tok = expect_token (IDENTIFIER);
4831 if (union_name_tok == nullptr)
4832 {
4833 skip_after_next_block ();
4834 return nullptr;
4835 }
4836 Identifier union_name{union_name_tok};
4837
4838 // parse optional generic parameters
4839 std::vector<std::unique_ptr<AST::GenericParam>> generic_params
4840 = parse_generic_params_in_angles ();
4841
4842 // parse optional where clause
4843 AST::WhereClause where_clause = parse_where_clause ();
4844
4845 if (!skip_token (LEFT_CURLY))
4846 {
4847 skip_after_end_block ();
4848 return nullptr;
4849 }
4850
4851 /* parse union inner items as "struct fields" because hey, syntax reuse.
4852 * Spec said so. */
4853 std::vector<AST::StructField> union_fields
4854 = parse_struct_fields ([] (TokenId id) { return id == RIGHT_CURLY; });
4855
4856 if (!skip_token (RIGHT_CURLY))
4857 {
4858 // skip after somewhere
4859 return nullptr;
4860 }
4861
4862 return std::unique_ptr<AST::Union> (
4863 new AST::Union (std::move (union_name), std::move (vis),
4864 std::move (generic_params), std::move (where_clause),
4865 std::move (union_fields), std::move (outer_attrs), locus));
4866 }
4867
4868 /* Parses a "constant item" (compile-time constant to maybe "inline"
4869 * throughout the program - like constexpr). */
4870 template <typename ManagedTokenSource>
4871 std::unique_ptr<AST::ConstantItem>
4872 Parser<ManagedTokenSource>::parse_const_item (AST::Visibility vis,
4873 AST::AttrVec outer_attrs)
4874 {
4875 location_t locus = lexer.peek_token ()->get_locus ();
4876 skip_token (CONST);
4877
4878 /* get constant identifier - this is either a proper identifier or the _
4879 * wildcard */
4880 const_TokenPtr ident_tok = lexer.peek_token ();
4881 // make default identifier the underscore wildcard one
4882 std::string ident (Values::Keywords::UNDERSCORE);
4883 switch (ident_tok->get_id ())
4884 {
4885 case IDENTIFIER:
4886 ident = ident_tok->get_str ();
4887 lexer.skip_token ();
4888 break;
4889 case UNDERSCORE:
4890 // do nothing - identifier is already "_"
4891 lexer.skip_token ();
4892 break;
4893 default:
4894 add_error (
4895 Error (ident_tok->get_locus (),
4896 "expected item name (identifier or %<_%>) in constant item "
4897 "declaration - found %qs",
4898 ident_tok->get_token_description ()));
4899
4900 skip_after_semicolon ();
4901 return nullptr;
4902 }
4903
4904 if (!skip_token (COLON))
4905 {
4906 skip_after_semicolon ();
4907 return nullptr;
4908 }
4909
4910 // parse constant type (required)
4911 std::unique_ptr<AST::Type> type = parse_type ();
4912
4913 // A const with no given expression value
4914 if (lexer.peek_token ()->get_id () == SEMICOLON)
4915 {
4916 lexer.skip_token ();
4917 return std::unique_ptr<AST::ConstantItem> (
4918 new AST::ConstantItem (std::move (ident), std::move (vis),
4919 std::move (type), std::move (outer_attrs),
4920 locus));
4921 }
4922
4923 if (!skip_token (EQUAL))
4924 {
4925 skip_after_semicolon ();
4926 return nullptr;
4927 }
4928
4929 // parse constant expression (required)
4930 std::unique_ptr<AST::Expr> expr = parse_expr ();
4931
4932 if (!skip_token (SEMICOLON))
4933 {
4934 // skip somewhere?
4935 return nullptr;
4936 }
4937
4938 return std::unique_ptr<AST::ConstantItem> (
4939 new AST::ConstantItem (std::move (ident), std::move (vis), std::move (type),
4940 std::move (expr), std::move (outer_attrs), locus));
4941 }
4942
4943 // Parses a "static item" (static storage item, with 'static lifetime).
4944 template <typename ManagedTokenSource>
4945 std::unique_ptr<AST::StaticItem>
4946 Parser<ManagedTokenSource>::parse_static_item (AST::Visibility vis,
4947 AST::AttrVec outer_attrs)
4948 {
4949 location_t locus = lexer.peek_token ()->get_locus ();
4950 skip_token (STATIC_KW);
4951
4952 // determine whether static item is mutable
4953 bool is_mut = false;
4954 if (lexer.peek_token ()->get_id () == MUT)
4955 {
4956 is_mut = true;
4957 lexer.skip_token ();
4958 }
4959
4960 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
4961 if (ident_tok == nullptr)
4962 return nullptr;
4963
4964 Identifier ident{ident_tok};
4965
4966 if (!skip_token (COLON))
4967 {
4968 skip_after_semicolon ();
4969 return nullptr;
4970 }
4971
4972 // parse static item type (required)
4973 std::unique_ptr<AST::Type> type = parse_type ();
4974
4975 if (!skip_token (EQUAL))
4976 {
4977 skip_after_semicolon ();
4978 return nullptr;
4979 }
4980
4981 // parse static item expression (required)
4982 std::unique_ptr<AST::Expr> expr = parse_expr ();
4983
4984 if (!skip_token (SEMICOLON))
4985 {
4986 // skip after somewhere
4987 return nullptr;
4988 }
4989
4990 return std::unique_ptr<AST::StaticItem> (
4991 new AST::StaticItem (std::move (ident), is_mut, std::move (type),
4992 std::move (expr), std::move (vis),
4993 std::move (outer_attrs), locus));
4994 }
4995
4996 // Parses a trait definition item, including unsafe ones.
4997 template <typename ManagedTokenSource>
4998 std::unique_ptr<AST::Trait>
4999 Parser<ManagedTokenSource>::parse_trait (AST::Visibility vis,
5000 AST::AttrVec outer_attrs)
5001 {
5002 location_t locus = lexer.peek_token ()->get_locus ();
5003 bool is_unsafe = false;
5004 bool is_auto_trait = false;
5005
5006 if (lexer.peek_token ()->get_id () == UNSAFE)
5007 {
5008 is_unsafe = true;
5009 lexer.skip_token ();
5010 }
5011
5012 if (lexer.peek_token ()->get_id () == AUTO)
5013 {
5014 is_auto_trait = true;
5015 lexer.skip_token ();
5016 }
5017
5018 skip_token (TRAIT);
5019
5020 // parse trait name
5021 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
5022 if (ident_tok == nullptr)
5023 return nullptr;
5024
5025 Identifier ident{ident_tok};
5026
5027 // parse generic parameters (if they exist)
5028 std::vector<std::unique_ptr<AST::GenericParam>> generic_params
5029 = parse_generic_params_in_angles ();
5030
5031 // create placeholder type param bounds in case they don't exist
5032 std::vector<std::unique_ptr<AST::TypeParamBound>> type_param_bounds;
5033
5034 // parse type param bounds (if they exist)
5035 if (lexer.peek_token ()->get_id () == COLON)
5036 {
5037 lexer.skip_token ();
5038
5039 type_param_bounds = parse_type_param_bounds (
5040 [] (TokenId id) { return id == WHERE || id == LEFT_CURLY; });
5041 // type_param_bounds = parse_type_param_bounds ();
5042 }
5043
5044 // parse where clause (if it exists)
5045 AST::WhereClause where_clause = parse_where_clause ();
5046
5047 if (!skip_token (LEFT_CURLY))
5048 {
5049 skip_after_end_block ();
5050 return nullptr;
5051 }
5052
5053 // parse inner attrs (if they exist)
5054 AST::AttrVec inner_attrs = parse_inner_attributes ();
5055
5056 // parse trait items
5057 std::vector<std::unique_ptr<AST::AssociatedItem>> trait_items;
5058
5059 const_TokenPtr t = lexer.peek_token ();
5060 while (t->get_id () != RIGHT_CURLY)
5061 {
5062 std::unique_ptr<AST::AssociatedItem> trait_item = parse_trait_item ();
5063
5064 if (trait_item == nullptr)
5065 {
5066 Error error (lexer.peek_token ()->get_locus (),
5067 "failed to parse trait item in trait");
5068 add_error (std::move (error));
5069
5070 return nullptr;
5071 }
5072 trait_items.push_back (std::move (trait_item));
5073
5074 t = lexer.peek_token ();
5075 }
5076
5077 if (!skip_token (RIGHT_CURLY))
5078 {
5079 // skip after something
5080 return nullptr;
5081 }
5082
5083 trait_items.shrink_to_fit ();
5084 return std::unique_ptr<AST::Trait> (
5085 new AST::Trait (std::move (ident), is_unsafe, is_auto_trait,
5086 std::move (generic_params), std::move (type_param_bounds),
5087 std::move (where_clause), std::move (trait_items),
5088 std::move (vis), std::move (outer_attrs),
5089 std::move (inner_attrs), locus));
5090 }
5091
5092 // Parses a trait item used inside traits (not trait, the Item).
5093 template <typename ManagedTokenSource>
5094 std::unique_ptr<AST::AssociatedItem>
5095 Parser<ManagedTokenSource>::parse_trait_item ()
5096 {
5097 // parse outer attributes (if they exist)
5098 AST::AttrVec outer_attrs = parse_outer_attributes ();
5099
5100 AST::Visibility vis = parse_visibility ();
5101
5102 // lookahead to determine what type of trait item to parse
5103 const_TokenPtr tok = lexer.peek_token ();
5104 switch (tok->get_id ())
5105 {
5106 case SUPER:
5107 case SELF:
5108 case CRATE:
5109 case DOLLAR_SIGN:
5110 // these seem to be SimplePath tokens, so this is a macro invocation
5111 // semi
5112 return parse_macro_invocation_semi (std::move (outer_attrs));
5113 case IDENTIFIER:
5114 if (lexer.peek_token ()->get_str () == Values::WeakKeywords::DEFAULT)
5115 return parse_function (std::move (vis), std::move (outer_attrs));
5116 else
5117 return parse_macro_invocation_semi (std::move (outer_attrs));
5118 case TYPE:
5119 return parse_trait_type (std::move (outer_attrs), vis);
5120 case CONST:
5121 // disambiguate with function qualifier
5122 if (lexer.peek_token (1)->get_id () == IDENTIFIER)
5123 {
5124 return parse_trait_const (std::move (outer_attrs));
5125 }
5126 // else, fallthrough to function
5127 // TODO: find out how to disable gcc "implicit fallthrough" error
5128 gcc_fallthrough ();
5129 case ASYNC:
5130 case UNSAFE:
5131 case EXTERN_KW:
5132 case FN_KW:
5133 return parse_function (std::move (vis), std::move (outer_attrs));
5134 default:
5135 break;
5136 }
5137 add_error (Error (tok->get_locus (),
5138 "unrecognised token %qs for item in trait",
5139 tok->get_token_description ()));
5140 // skip?
5141 return nullptr;
5142 }
5143
5144 // Parse a typedef trait item.
5145 template <typename ManagedTokenSource>
5146 std::unique_ptr<AST::TraitItemType>
5147 Parser<ManagedTokenSource>::parse_trait_type (AST::AttrVec outer_attrs,
5148 AST::Visibility vis)
5149 {
5150 location_t locus = lexer.peek_token ()->get_locus ();
5151 skip_token (TYPE);
5152
5153 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
5154 if (ident_tok == nullptr)
5155 return nullptr;
5156
5157 Identifier ident{ident_tok};
5158
5159 std::vector<std::unique_ptr<AST::TypeParamBound>> bounds;
5160
5161 // parse optional colon
5162 if (lexer.peek_token ()->get_id () == COLON)
5163 {
5164 lexer.skip_token ();
5165
5166 // parse optional type param bounds
5167 bounds
5168 = parse_type_param_bounds ([] (TokenId id) { return id == SEMICOLON; });
5169 // bounds = parse_type_param_bounds ();
5170 }
5171
5172 if (!skip_token (SEMICOLON))
5173 {
5174 // skip?
5175 return nullptr;
5176 }
5177
5178 return std::unique_ptr<AST::TraitItemType> (
5179 new AST::TraitItemType (std::move (ident), std::move (bounds),
5180 std::move (outer_attrs), vis, locus));
5181 }
5182
5183 // Parses a constant trait item.
5184 template <typename ManagedTokenSource>
5185 std::unique_ptr<AST::TraitItemConst>
5186 Parser<ManagedTokenSource>::parse_trait_const (AST::AttrVec outer_attrs)
5187 {
5188 location_t locus = lexer.peek_token ()->get_locus ();
5189 skip_token (CONST);
5190
5191 // parse constant item name
5192 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
5193 if (ident_tok == nullptr)
5194 return nullptr;
5195
5196 Identifier ident{ident_tok};
5197
5198 if (!skip_token (COLON))
5199 {
5200 skip_after_semicolon ();
5201 return nullptr;
5202 }
5203
5204 // parse constant trait item type
5205 std::unique_ptr<AST::Type> type = parse_type ();
5206
5207 // parse constant trait body expression, if it exists
5208 std::unique_ptr<AST::Expr> const_body = nullptr;
5209 if (lexer.peek_token ()->get_id () == EQUAL)
5210 {
5211 lexer.skip_token ();
5212
5213 // expression must exist, so parse it
5214 const_body = parse_expr ();
5215 }
5216
5217 if (!skip_token (SEMICOLON))
5218 {
5219 // skip after something?
5220 return nullptr;
5221 }
5222
5223 return std::unique_ptr<AST::TraitItemConst> (
5224 new AST::TraitItemConst (std::move (ident), std::move (type),
5225 std::move (const_body), std::move (outer_attrs),
5226 locus));
5227 }
5228
5229 /* Parses a struct "impl" item (both inherent impl and trait impl can be
5230 * parsed here), */
5231 template <typename ManagedTokenSource>
5232 std::unique_ptr<AST::Impl>
5233 Parser<ManagedTokenSource>::parse_impl (AST::Visibility vis,
5234 AST::AttrVec outer_attrs)
5235 {
5236 /* Note that only trait impls are allowed to be unsafe. So if unsafe, it
5237 * must be a trait impl. However, this isn't enough for full disambiguation,
5238 * so don't branch here. */
5239 location_t locus = lexer.peek_token ()->get_locus ();
5240 bool is_unsafe = false;
5241 if (lexer.peek_token ()->get_id () == UNSAFE)
5242 {
5243 lexer.skip_token ();
5244 is_unsafe = true;
5245 }
5246
5247 if (!skip_token (IMPL))
5248 {
5249 skip_after_next_block ();
5250 return nullptr;
5251 }
5252
5253 // parse generic params (shared by trait and inherent impls)
5254 std::vector<std::unique_ptr<AST::GenericParam>> generic_params
5255 = parse_generic_params_in_angles ();
5256
5257 // Again, trait impl-only feature, but optional one, so can be used for
5258 // branching yet.
5259 bool has_exclam = false;
5260 if (lexer.peek_token ()->get_id () == EXCLAM)
5261 {
5262 lexer.skip_token ();
5263 has_exclam = true;
5264 }
5265
5266 /* FIXME: code that doesn't look shit for TypePath. Also, make sure this
5267 * doesn't parse too much and not work. */
5268 AST::TypePath type_path = parse_type_path ();
5269 if (type_path.is_error () || lexer.peek_token ()->get_id () != FOR)
5270 {
5271 /* cannot parse type path (or not for token next, at least), so must be
5272 * inherent impl */
5273
5274 // hacky conversion of TypePath stack object to Type pointer
5275 std::unique_ptr<AST::Type> type = nullptr;
5276 if (!type_path.is_error ())
5277 type = std::unique_ptr<AST::TypePath> (
5278 new AST::TypePath (std::move (type_path)));
5279 else
5280 type = parse_type ();
5281
5282 // Type is required, so error if null
5283 if (type == nullptr)
5284 {
5285 Error error (lexer.peek_token ()->get_locus (),
5286 "could not parse type in inherent impl");
5287 add_error (std::move (error));
5288
5289 skip_after_next_block ();
5290 return nullptr;
5291 }
5292
5293 // parse optional where clause
5294 AST::WhereClause where_clause = parse_where_clause ();
5295
5296 if (!skip_token (LEFT_CURLY))
5297 {
5298 // TODO: does this still skip properly?
5299 skip_after_end_block ();
5300 return nullptr;
5301 }
5302
5303 // parse inner attributes (optional)
5304 AST::AttrVec inner_attrs = parse_inner_attributes ();
5305
5306 // parse inherent impl items
5307 std::vector<std::unique_ptr<AST::AssociatedItem>> impl_items;
5308
5309 const_TokenPtr t = lexer.peek_token ();
5310 while (t->get_id () != RIGHT_CURLY)
5311 {
5312 std::unique_ptr<AST::AssociatedItem> impl_item
5313 = parse_inherent_impl_item ();
5314
5315 if (impl_item == nullptr)
5316 {
5317 Error error (
5318 lexer.peek_token ()->get_locus (),
5319 "failed to parse inherent impl item in inherent impl");
5320 add_error (std::move (error));
5321
5322 return nullptr;
5323 }
5324
5325 impl_items.push_back (std::move (impl_item));
5326
5327 t = lexer.peek_token ();
5328 }
5329
5330 if (!skip_token (RIGHT_CURLY))
5331 {
5332 // skip somewhere
5333 return nullptr;
5334 }
5335
5336 // DEBUG
5337 rust_debug ("successfully parsed inherent impl");
5338
5339 impl_items.shrink_to_fit ();
5340
5341 return std::unique_ptr<AST::InherentImpl> (new AST::InherentImpl (
5342 std::move (impl_items), std::move (generic_params), std::move (type),
5343 std::move (where_clause), std::move (vis), std::move (inner_attrs),
5344 std::move (outer_attrs), locus));
5345 }
5346 else
5347 {
5348 // type path must both be valid and next token is for, so trait impl
5349 if (!skip_token (FOR))
5350 {
5351 skip_after_next_block ();
5352 return nullptr;
5353 }
5354
5355 // parse type
5356 std::unique_ptr<AST::Type> type = parse_type ();
5357 // ensure type is included as it is required
5358 if (type == nullptr)
5359 {
5360 Error error (lexer.peek_token ()->get_locus (),
5361 "could not parse type in trait impl");
5362 add_error (std::move (error));
5363
5364 skip_after_next_block ();
5365 return nullptr;
5366 }
5367
5368 // parse optional where clause
5369 AST::WhereClause where_clause = parse_where_clause ();
5370
5371 if (!skip_token (LEFT_CURLY))
5372 {
5373 // TODO: does this still skip properly?
5374 skip_after_end_block ();
5375 return nullptr;
5376 }
5377
5378 // parse inner attributes (optional)
5379 AST::AttrVec inner_attrs = parse_inner_attributes ();
5380
5381 // parse trait impl items
5382 std::vector<std::unique_ptr<AST::AssociatedItem>> impl_items;
5383
5384 const_TokenPtr t = lexer.peek_token ();
5385 while (t->get_id () != RIGHT_CURLY)
5386 {
5387 std::unique_ptr<AST::AssociatedItem> impl_item
5388 = parse_trait_impl_item ();
5389
5390 if (impl_item == nullptr)
5391 {
5392 Error error (lexer.peek_token ()->get_locus (),
5393 "failed to parse trait impl item in trait impl");
5394 add_error (std::move (error));
5395
5396 return nullptr;
5397 }
5398
5399 impl_items.push_back (std::move (impl_item));
5400
5401 t = lexer.peek_token ();
5402
5403 // DEBUG
5404 rust_debug ("successfully parsed a trait impl item");
5405 }
5406 // DEBUG
5407 rust_debug ("successfully finished trait impl items");
5408
5409 if (!skip_token (RIGHT_CURLY))
5410 {
5411 // skip somewhere
5412 return nullptr;
5413 }
5414
5415 // DEBUG
5416 rust_debug ("successfully parsed trait impl");
5417
5418 impl_items.shrink_to_fit ();
5419
5420 return std::unique_ptr<AST::TraitImpl> (
5421 new AST::TraitImpl (std::move (type_path), is_unsafe, has_exclam,
5422 std::move (impl_items), std::move (generic_params),
5423 std::move (type), std::move (where_clause),
5424 std::move (vis), std::move (inner_attrs),
5425 std::move (outer_attrs), locus));
5426 }
5427 }
5428
5429 // Parses a single inherent impl item (item inside an inherent impl block).
5430 template <typename ManagedTokenSource>
5431 std::unique_ptr<AST::AssociatedItem>
5432 Parser<ManagedTokenSource>::parse_inherent_impl_item ()
5433 {
5434 // parse outer attributes (if they exist)
5435 AST::AttrVec outer_attrs = parse_outer_attributes ();
5436
5437 // TODO: cleanup - currently an unreadable mess
5438
5439 // branch on next token:
5440 const_TokenPtr t = lexer.peek_token ();
5441 switch (t->get_id ())
5442 {
5443 case IDENTIFIER:
5444 // FIXME: Arthur: Do we need to some lookahead here?
5445 return parse_macro_invocation_semi (outer_attrs);
5446 case SUPER:
5447 case SELF:
5448 case CRATE:
5449 case PUB: {
5450 // visibility, so not a macro invocation semi - must be constant,
5451 // function, or method
5452 AST::Visibility vis = parse_visibility ();
5453
5454 // TODO: is a recursive call to parse_inherent_impl_item better?
5455 switch (lexer.peek_token ()->get_id ())
5456 {
5457 case EXTERN_KW:
5458 case UNSAFE:
5459 case FN_KW:
5460 // function or method
5461 return parse_inherent_impl_function_or_method (std::move (vis),
5462 std::move (
5463 outer_attrs));
5464 case CONST:
5465 // lookahead to resolve production - could be function/method or
5466 // const item
5467 t = lexer.peek_token (1);
5468
5469 switch (t->get_id ())
5470 {
5471 case IDENTIFIER:
5472 case UNDERSCORE:
5473 return parse_const_item (std::move (vis),
5474 std::move (outer_attrs));
5475 case UNSAFE:
5476 case EXTERN_KW:
5477 case FN_KW:
5478 return parse_inherent_impl_function_or_method (std::move (vis),
5479 std::move (
5480 outer_attrs));
5481 default:
5482 add_error (Error (t->get_locus (),
5483 "unexpected token %qs in some sort of const "
5484 "item in inherent impl",
5485 t->get_token_description ()));
5486
5487 lexer.skip_token (1); // TODO: is this right thing to do?
5488 return nullptr;
5489 }
5490 default:
5491 add_error (
5492 Error (t->get_locus (),
5493 "unrecognised token %qs for item in inherent impl",
5494 t->get_token_description ()));
5495 // skip?
5496 return nullptr;
5497 }
5498 }
5499 case ASYNC:
5500 case EXTERN_KW:
5501 case UNSAFE:
5502 case FN_KW:
5503 // function or method
5504 return parse_inherent_impl_function_or_method (
5505 AST::Visibility::create_private (), std::move (outer_attrs));
5506 case CONST:
5507 /* lookahead to resolve production - could be function/method or const
5508 * item */
5509 t = lexer.peek_token (1);
5510
5511 switch (t->get_id ())
5512 {
5513 case IDENTIFIER:
5514 case UNDERSCORE:
5515 return parse_const_item (AST::Visibility::create_private (),
5516 std::move (outer_attrs));
5517 case UNSAFE:
5518 case EXTERN_KW:
5519 case FN_KW:
5520 return parse_inherent_impl_function_or_method (
5521 AST::Visibility::create_private (), std::move (outer_attrs));
5522 default:
5523 add_error (Error (t->get_locus (),
5524 "unexpected token %qs in some sort of const item "
5525 "in inherent impl",
5526 t->get_token_description ()));
5527
5528 lexer.skip_token (1); // TODO: is this right thing to do?
5529 return nullptr;
5530 }
5531 rust_unreachable ();
5532 default:
5533 add_error (Error (t->get_locus (),
5534 "unrecognised token %qs for item in inherent impl",
5535 t->get_token_description ()));
5536
5537 // skip?
5538 return nullptr;
5539 }
5540 }
5541
5542 /* For internal use only by parse_inherent_impl_item() - splits giant method
5543 * into smaller ones and prevents duplication of logic. Strictly, this parses
5544 * a function or method item inside an inherent impl item block. */
5545 // TODO: make this a templated function with "return type" as type param -
5546 // InherentImplItem is this specialisation of the template while TraitImplItem
5547 // will be the other.
5548 template <typename ManagedTokenSource>
5549 std::unique_ptr<AST::AssociatedItem>
5550 Parser<ManagedTokenSource>::parse_inherent_impl_function_or_method (
5551 AST::Visibility vis, AST::AttrVec outer_attrs)
5552 {
5553 location_t locus = lexer.peek_token ()->get_locus ();
5554 // parse function or method qualifiers
5555 AST::FunctionQualifiers qualifiers = parse_function_qualifiers ();
5556
5557 skip_token (FN_KW);
5558
5559 // parse function or method name
5560 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
5561 if (ident_tok == nullptr)
5562 return nullptr;
5563
5564 Identifier ident{ident_tok};
5565
5566 // parse generic params
5567 std::vector<std::unique_ptr<AST::GenericParam>> generic_params
5568 = parse_generic_params_in_angles ();
5569
5570 if (!skip_token (LEFT_PAREN))
5571 {
5572 // skip after somewhere?
5573 return nullptr;
5574 }
5575
5576 // now for function vs method disambiguation - method has opening "self"
5577 // param
5578 auto initial_param = parse_self_param ();
5579
5580 if (!initial_param.has_value () && initial_param.error () != NOT_SELF)
5581 return nullptr;
5582
5583 /* FIXME: ensure that self param doesn't accidently consume tokens for a
5584 * function one idea is to lookahead up to 4 tokens to see whether self is
5585 * one of them */
5586 bool is_method = false;
5587 if (initial_param.has_value ())
5588 {
5589 if ((*initial_param)->is_self ())
5590 is_method = true;
5591
5592 /* skip comma so function and method regular params can be parsed in
5593 * same way */
5594 if (lexer.peek_token ()->get_id () == COMMA)
5595 lexer.skip_token ();
5596 }
5597
5598 // parse trait function params
5599 std::vector<std::unique_ptr<AST::Param>> function_params
5600 = parse_function_params ([] (TokenId id) { return id == RIGHT_PAREN; });
5601
5602 if (initial_param.has_value ())
5603 function_params.insert (function_params.begin (),
5604 std::move (*initial_param));
5605
5606 if (!skip_token (RIGHT_PAREN))
5607 {
5608 skip_after_end_block ();
5609 return nullptr;
5610 }
5611
5612 // parse return type (optional)
5613 std::unique_ptr<AST::Type> return_type = parse_function_return_type ();
5614
5615 // parse where clause (optional)
5616 AST::WhereClause where_clause = parse_where_clause ();
5617
5618 tl::optional<std::unique_ptr<AST::BlockExpr>> body = tl::nullopt;
5619 if (lexer.peek_token ()->get_id () == SEMICOLON)
5620 lexer.skip_token ();
5621 else
5622 {
5623 auto result = parse_block_expr ();
5624
5625 if (result == nullptr)
5626 {
5627 Error error (
5628 lexer.peek_token ()->get_locus (),
5629 "could not parse definition in inherent impl %s definition",
5630 is_method ? "method" : "function");
5631 add_error (std::move (error));
5632
5633 skip_after_end_block ();
5634 return nullptr;
5635 }
5636 body = std::move (result);
5637 }
5638
5639 return std::unique_ptr<AST::Function> (
5640 new AST::Function (std::move (ident), std::move (qualifiers),
5641 std::move (generic_params), std::move (function_params),
5642 std::move (return_type), std::move (where_clause),
5643 std::move (body), std::move (vis),
5644 std::move (outer_attrs), locus));
5645 }
5646
5647 // Parses a single trait impl item (item inside a trait impl block).
5648 template <typename ManagedTokenSource>
5649 std::unique_ptr<AST::AssociatedItem>
5650 Parser<ManagedTokenSource>::parse_trait_impl_item ()
5651 {
5652 // parse outer attributes (if they exist)
5653 AST::AttrVec outer_attrs = parse_outer_attributes ();
5654
5655 auto visibility = AST::Visibility::create_private ();
5656 if (lexer.peek_token ()->get_id () == PUB)
5657 visibility = parse_visibility ();
5658
5659 // branch on next token:
5660 const_TokenPtr t = lexer.peek_token ();
5661 switch (t->get_id ())
5662 {
5663 case SUPER:
5664 case SELF:
5665 case CRATE:
5666 case DOLLAR_SIGN:
5667 // these seem to be SimplePath tokens, so this is a macro invocation
5668 // semi
5669 return parse_macro_invocation_semi (std::move (outer_attrs));
5670 case IDENTIFIER:
5671 if (lexer.peek_token ()->get_str () == Values::WeakKeywords::DEFAULT)
5672 return parse_trait_impl_function_or_method (visibility,
5673 std::move (outer_attrs));
5674 else
5675 return parse_macro_invocation_semi (std::move (outer_attrs));
5676 case TYPE:
5677 return parse_type_alias (visibility, std::move (outer_attrs));
5678 case EXTERN_KW:
5679 case UNSAFE:
5680 case FN_KW:
5681 // function or method
5682 return parse_trait_impl_function_or_method (visibility,
5683 std::move (outer_attrs));
5684 case ASYNC:
5685 return parse_async_item (visibility, std::move (outer_attrs));
5686 case CONST:
5687 // lookahead to resolve production - could be function/method or const
5688 // item
5689 t = lexer.peek_token (1);
5690
5691 switch (t->get_id ())
5692 {
5693 case IDENTIFIER:
5694 case UNDERSCORE:
5695 return parse_const_item (visibility, std::move (outer_attrs));
5696 case UNSAFE:
5697 case EXTERN_KW:
5698 case FN_KW:
5699 return parse_trait_impl_function_or_method (visibility,
5700 std::move (outer_attrs));
5701 default:
5702 add_error (Error (
5703 t->get_locus (),
5704 "unexpected token %qs in some sort of const item in trait impl",
5705 t->get_token_description ()));
5706
5707 lexer.skip_token (1); // TODO: is this right thing to do?
5708 return nullptr;
5709 }
5710 rust_unreachable ();
5711 default:
5712 break;
5713 }
5714 add_error (Error (t->get_locus (),
5715 "unrecognised token %qs for item in trait impl",
5716 t->get_token_description ()));
5717
5718 // skip?
5719 return nullptr;
5720 }
5721
5722 /* For internal use only by parse_trait_impl_item() - splits giant method into
5723 * smaller ones and prevents duplication of logic. Strictly, this parses a
5724 * function or method item inside a trait impl item block. */
5725 template <typename ManagedTokenSource>
5726 std::unique_ptr<AST::AssociatedItem>
5727 Parser<ManagedTokenSource>::parse_trait_impl_function_or_method (
5728 AST::Visibility vis, AST::AttrVec outer_attrs)
5729 {
5730 // this shares virtually all logic with
5731 // parse_inherent_impl_function_or_method
5732 // - template?
5733 location_t locus = lexer.peek_token ()->get_locus ();
5734
5735 auto is_default = false;
5736 auto t = lexer.peek_token ();
5737 if (t->get_id () == IDENTIFIER
5738 && t->get_str () == Values::WeakKeywords::DEFAULT)
5739 {
5740 is_default = true;
5741 lexer.skip_token ();
5742 }
5743
5744 // parse function or method qualifiers
5745 AST::FunctionQualifiers qualifiers = parse_function_qualifiers ();
5746
5747 skip_token (FN_KW);
5748
5749 // parse function or method name
5750 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
5751 if (ident_tok == nullptr)
5752 {
5753 return nullptr;
5754 }
5755 Identifier ident{ident_tok};
5756
5757 // DEBUG:
5758 rust_debug (
5759 "about to start parsing generic params in trait impl function or method");
5760
5761 // parse generic params
5762 std::vector<std::unique_ptr<AST::GenericParam>> generic_params
5763 = parse_generic_params_in_angles ();
5764
5765 // DEBUG:
5766 rust_debug (
5767 "finished parsing generic params in trait impl function or method");
5768
5769 if (!skip_token (LEFT_PAREN))
5770 {
5771 // skip after somewhere?
5772 return nullptr;
5773 }
5774
5775 // now for function vs method disambiguation - method has opening "self"
5776 // param
5777 auto initial_param = parse_self_param ();
5778
5779 if (!initial_param.has_value () && initial_param.error () != NOT_SELF)
5780 return nullptr;
5781
5782 // FIXME: ensure that self param doesn't accidently consume tokens for a
5783 // function
5784 bool is_method = false;
5785 if (initial_param.has_value ())
5786 {
5787 if ((*initial_param)->is_self ())
5788 is_method = true;
5789
5790 // skip comma so function and method regular params can be parsed in
5791 // same way
5792 if (lexer.peek_token ()->get_id () == COMMA)
5793 {
5794 lexer.skip_token ();
5795 }
5796
5797 // DEBUG
5798 rust_debug ("successfully parsed self param in method trait impl item");
5799 }
5800
5801 // DEBUG
5802 rust_debug (
5803 "started to parse function params in function or method trait impl item");
5804
5805 // parse trait function params (only if next token isn't right paren)
5806 std::vector<std::unique_ptr<AST::Param>> function_params;
5807 if (lexer.peek_token ()->get_id () != RIGHT_PAREN)
5808 {
5809 function_params
5810 = parse_function_params ([] (TokenId id) { return id == RIGHT_PAREN; });
5811
5812 if (function_params.empty ())
5813 {
5814 Error error (
5815 lexer.peek_token ()->get_locus (),
5816 "failed to parse function params in trait impl %s definition",
5817 is_method ? "method" : "function");
5818 add_error (std::move (error));
5819
5820 skip_after_next_block ();
5821 return nullptr;
5822 }
5823 }
5824
5825 if (initial_param.has_value ())
5826 function_params.insert (function_params.begin (),
5827 std::move (*initial_param));
5828
5829 // DEBUG
5830 rust_debug ("successfully parsed function params in function or method "
5831 "trait impl item");
5832
5833 if (!skip_token (RIGHT_PAREN))
5834 {
5835 skip_after_next_block ();
5836 return nullptr;
5837 }
5838
5839 // parse return type (optional)
5840 std::unique_ptr<AST::Type> return_type = parse_function_return_type ();
5841
5842 // DEBUG
5843 rust_debug (
5844 "successfully parsed return type in function or method trait impl item");
5845
5846 // parse where clause (optional)
5847 AST::WhereClause where_clause = parse_where_clause ();
5848
5849 // DEBUG
5850 rust_debug (
5851 "successfully parsed where clause in function or method trait impl item");
5852
5853 // parse function definition (in block) - semicolon not allowed
5854 tl::optional<std::unique_ptr<AST::BlockExpr>> body = tl::nullopt;
5855
5856 if (lexer.peek_token ()->get_id () == SEMICOLON)
5857 lexer.skip_token ();
5858 else
5859 {
5860 auto result = parse_block_expr ();
5861 if (result == nullptr)
5862 {
5863 Error error (lexer.peek_token ()->get_locus (),
5864 "could not parse definition in trait impl %s definition",
5865 is_method ? "method" : "function");
5866 add_error (std::move (error));
5867
5868 skip_after_end_block ();
5869 return nullptr;
5870 }
5871 body = std::move (result);
5872 }
5873
5874 return std::unique_ptr<AST::Function> (
5875 new AST::Function (std::move (ident), std::move (qualifiers),
5876 std::move (generic_params), std::move (function_params),
5877 std::move (return_type), std::move (where_clause),
5878 std::move (body), std::move (vis),
5879 std::move (outer_attrs), locus, is_default));
5880 }
5881
5882 // Parses an extern block of declarations.
5883 template <typename ManagedTokenSource>
5884 std::unique_ptr<AST::ExternBlock>
5885 Parser<ManagedTokenSource>::parse_extern_block (AST::Visibility vis,
5886 AST::AttrVec outer_attrs)
5887 {
5888 location_t locus = lexer.peek_token ()->get_locus ();
5889 skip_token (EXTERN_KW);
5890
5891 // detect optional abi name
5892 std::string abi;
5893 const_TokenPtr next_tok = lexer.peek_token ();
5894 if (next_tok->get_id () == STRING_LITERAL)
5895 {
5896 lexer.skip_token ();
5897 abi = next_tok->get_str ();
5898 }
5899
5900 if (!skip_token (LEFT_CURLY))
5901 {
5902 skip_after_end_block ();
5903 return nullptr;
5904 }
5905
5906 AST::AttrVec inner_attrs = parse_inner_attributes ();
5907
5908 // parse declarations inside extern block
5909 std::vector<std::unique_ptr<AST::ExternalItem>> extern_items;
5910
5911 const_TokenPtr t = lexer.peek_token ();
5912 while (t->get_id () != RIGHT_CURLY)
5913 {
5914 std::unique_ptr<AST::ExternalItem> extern_item = parse_external_item ();
5915
5916 if (extern_item == nullptr)
5917 {
5918 Error error (t->get_locus (),
5919 "failed to parse external item despite not reaching "
5920 "end of extern block");
5921 add_error (std::move (error));
5922
5923 return nullptr;
5924 }
5925
5926 extern_items.push_back (std::move (extern_item));
5927
5928 t = lexer.peek_token ();
5929 }
5930
5931 if (!skip_token (RIGHT_CURLY))
5932 {
5933 // skip somewhere
5934 return nullptr;
5935 }
5936
5937 extern_items.shrink_to_fit ();
5938
5939 return std::unique_ptr<AST::ExternBlock> (
5940 new AST::ExternBlock (std::move (abi), std::move (extern_items),
5941 std::move (vis), std::move (inner_attrs),
5942 std::move (outer_attrs), locus));
5943 }
5944
5945 // Parses a single extern block item (static or function declaration).
5946 template <typename ManagedTokenSource>
5947 std::unique_ptr<AST::ExternalItem>
5948 Parser<ManagedTokenSource>::parse_external_item ()
5949 {
5950 // parse optional outer attributes
5951 AST::AttrVec outer_attrs = parse_outer_attributes ();
5952
5953 location_t locus = lexer.peek_token ()->get_locus ();
5954
5955 // parse optional visibility
5956 AST::Visibility vis = parse_visibility ();
5957
5958 const_TokenPtr t = lexer.peek_token ();
5959 switch (t->get_id ())
5960 {
5961 case IDENTIFIER:
5962 return parse_macro_invocation_semi (outer_attrs);
5963 case STATIC_KW: {
5964 // parse extern static item
5965 lexer.skip_token ();
5966
5967 // parse mut (optional)
5968 bool has_mut = false;
5969 if (lexer.peek_token ()->get_id () == MUT)
5970 {
5971 lexer.skip_token ();
5972 has_mut = true;
5973 }
5974
5975 // parse identifier
5976 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
5977 if (ident_tok == nullptr)
5978 {
5979 skip_after_semicolon ();
5980 return nullptr;
5981 }
5982 Identifier ident{ident_tok};
5983
5984 if (!skip_token (COLON))
5985 {
5986 skip_after_semicolon ();
5987 return nullptr;
5988 }
5989
5990 // parse type (required)
5991 std::unique_ptr<AST::Type> type = parse_type ();
5992 if (type == nullptr)
5993 {
5994 Error error (lexer.peek_token ()->get_locus (),
5995 "failed to parse type in external static item");
5996 add_error (std::move (error));
5997
5998 skip_after_semicolon ();
5999 return nullptr;
6000 }
6001
6002 if (!skip_token (SEMICOLON))
6003 {
6004 // skip after somewhere?
6005 return nullptr;
6006 }
6007
6008 return std::unique_ptr<AST::ExternalStaticItem> (
6009 new AST::ExternalStaticItem (std::move (ident), std::move (type),
6010 has_mut, std::move (vis),
6011 std::move (outer_attrs), locus));
6012 }
6013 case FN_KW:
6014 return parse_function (std::move (vis), std::move (outer_attrs), true);
6015
6016 case TYPE:
6017 return parse_external_type_item (std::move (vis),
6018 std::move (outer_attrs));
6019 default:
6020 // error
6021 add_error (
6022 Error (t->get_locus (),
6023 "unrecognised token %qs in extern block item declaration",
6024 t->get_token_description ()));
6025
6026 skip_after_semicolon ();
6027 return nullptr;
6028 }
6029 }
6030
6031 // Parses a statement (will further disambiguate any statement).
6032 template <typename ManagedTokenSource>
6033 std::unique_ptr<AST::Stmt>
6034 Parser<ManagedTokenSource>::parse_stmt (ParseRestrictions restrictions)
6035 {
6036 // quick exit for empty statement
6037 // FIXME: Can we have empty statements without semicolons? Just nothing?
6038 const_TokenPtr t = lexer.peek_token ();
6039 if (t->get_id () == SEMICOLON)
6040 {
6041 lexer.skip_token ();
6042 return std::unique_ptr<AST::EmptyStmt> (
6043 new AST::EmptyStmt (t->get_locus ()));
6044 }
6045
6046 // parse outer attributes
6047 AST::AttrVec outer_attrs = parse_outer_attributes ();
6048
6049 // parsing this will be annoying because of the many different possibilities
6050 /* best may be just to copy paste in parse_item switch, and failing that try
6051 * to parse outer attributes, and then pass them in to either a let
6052 * statement or (fallback) expression statement. */
6053 // FIXME: think of a way to do this without such a large switch?
6054 t = lexer.peek_token ();
6055 switch (t->get_id ())
6056 {
6057 case LET:
6058 // let statement
6059 return parse_let_stmt (std::move (outer_attrs), restrictions);
6060 case PUB:
6061 case MOD:
6062 case EXTERN_KW:
6063 case USE:
6064 case FN_KW:
6065 case TYPE:
6066 case STRUCT_KW:
6067 case ENUM_KW:
6068 case CONST:
6069 case STATIC_KW:
6070 case AUTO:
6071 case TRAIT:
6072 case IMPL:
6073 case MACRO:
6074 /* TODO: implement union keyword but not really because of
6075 * context-dependence crappy hack way to parse a union written below to
6076 * separate it from the good code. */
6077 // case UNION:
6078 case UNSAFE: // maybe - unsafe traits are a thing
6079 /* if any of these (should be all possible VisItem prefixes), parse a
6080 * VisItem can't parse item because would require reparsing outer
6081 * attributes */
6082 // may also be unsafe block
6083 if (lexer.peek_token (1)->get_id () == LEFT_CURLY)
6084 {
6085 return parse_expr_stmt (std::move (outer_attrs), restrictions);
6086 }
6087 else
6088 {
6089 return parse_vis_item (std::move (outer_attrs));
6090 }
6091 break;
6092 // crappy hack to do union "keyword"
6093 case IDENTIFIER:
6094 if (t->get_str () == Values::WeakKeywords::UNION
6095 && lexer.peek_token (1)->get_id () == IDENTIFIER)
6096 {
6097 return parse_vis_item (std::move (outer_attrs));
6098 // or should this go straight to parsing union?
6099 }
6100 else if (is_macro_rules_def (t))
6101 {
6102 // macro_rules! macro item
6103 return parse_macro_rules_def (std::move (outer_attrs));
6104 }
6105 gcc_fallthrough ();
6106 // TODO: find out how to disable gcc "implicit fallthrough" warning
6107 default:
6108 // fallback: expression statement
6109 return parse_expr_stmt (std::move (outer_attrs), restrictions);
6110 break;
6111 }
6112 }
6113
6114 // Parses a let statement.
6115 template <typename ManagedTokenSource>
6116 std::unique_ptr<AST::LetStmt>
6117 Parser<ManagedTokenSource>::parse_let_stmt (AST::AttrVec outer_attrs,
6118 ParseRestrictions restrictions)
6119 {
6120 location_t locus = lexer.peek_token ()->get_locus ();
6121 skip_token (LET);
6122
6123 // parse pattern (required)
6124 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
6125 if (pattern == nullptr)
6126 {
6127 Error error (lexer.peek_token ()->get_locus (),
6128 "failed to parse pattern in let statement");
6129 add_error (std::move (error));
6130
6131 skip_after_semicolon ();
6132 return nullptr;
6133 }
6134
6135 // parse type declaration (optional)
6136 std::unique_ptr<AST::Type> type = nullptr;
6137 if (lexer.peek_token ()->get_id () == COLON)
6138 {
6139 // must have a type declaration
6140 lexer.skip_token ();
6141
6142 type = parse_type ();
6143 if (type == nullptr)
6144 {
6145 Error error (lexer.peek_token ()->get_locus (),
6146 "failed to parse type in let statement");
6147 add_error (std::move (error));
6148
6149 skip_after_semicolon ();
6150 return nullptr;
6151 }
6152 }
6153
6154 // parse expression to set variable to (optional)
6155 std::unique_ptr<AST::Expr> expr = nullptr;
6156 if (lexer.peek_token ()->get_id () == EQUAL)
6157 {
6158 // must have an expression
6159 lexer.skip_token ();
6160
6161 expr = parse_expr ();
6162 if (expr == nullptr)
6163 {
6164 Error error (lexer.peek_token ()->get_locus (),
6165 "failed to parse expression in let statement");
6166 add_error (std::move (error));
6167
6168 skip_after_semicolon ();
6169 return nullptr;
6170 }
6171 }
6172
6173 tl::optional<std::unique_ptr<AST::Expr>> else_expr = tl::nullopt;
6174 if (maybe_skip_token (ELSE))
6175 else_expr = parse_block_expr ();
6176
6177 if (restrictions.consume_semi)
6178 {
6179 // `stmt` macro variables are parsed without a semicolon, but should be
6180 // parsed as a full statement when interpolated. This should be handled
6181 // by having the interpolated statement be distinguishable from normal
6182 // tokens, e.g. by NT tokens.
6183 if (restrictions.allow_close_after_expr_stmt)
6184 maybe_skip_token (SEMICOLON);
6185 else if (!skip_token (SEMICOLON))
6186 return nullptr;
6187 }
6188
6189 return std::unique_ptr<AST::LetStmt> (
6190 new AST::LetStmt (std::move (pattern), std::move (expr), std::move (type),
6191 std::move (else_expr), std::move (outer_attrs), locus));
6192 }
6193
6194 // Parses a type path.
6195 template <typename ManagedTokenSource>
6196 AST::TypePath
6197 Parser<ManagedTokenSource>::parse_type_path ()
6198 {
6199 bool has_opening_scope_resolution = false;
6200 location_t locus = lexer.peek_token ()->get_locus ();
6201 if (lexer.peek_token ()->get_id () == SCOPE_RESOLUTION)
6202 {
6203 has_opening_scope_resolution = true;
6204 lexer.skip_token ();
6205 }
6206
6207 // create segment vector
6208 std::vector<std::unique_ptr<AST::TypePathSegment>> segments;
6209
6210 // parse required initial segment
6211 std::unique_ptr<AST::TypePathSegment> initial_segment
6212 = parse_type_path_segment ();
6213 if (initial_segment == nullptr)
6214 {
6215 // skip after somewhere?
6216 // don't necessarily throw error but yeah
6217 return AST::TypePath::create_error ();
6218 }
6219 segments.push_back (std::move (initial_segment));
6220
6221 // parse optional segments (as long as scope resolution operator exists)
6222 const_TokenPtr t = lexer.peek_token ();
6223 while (t->get_id () == SCOPE_RESOLUTION)
6224 {
6225 // skip scope resolution operator
6226 lexer.skip_token ();
6227
6228 // parse the actual segment - it is an error if it doesn't exist now
6229 std::unique_ptr<AST::TypePathSegment> segment
6230 = parse_type_path_segment ();
6231 if (segment == nullptr)
6232 {
6233 // skip after somewhere?
6234 Error error (t->get_locus (), "could not parse type path segment");
6235 add_error (std::move (error));
6236
6237 return AST::TypePath::create_error ();
6238 }
6239
6240 segments.push_back (std::move (segment));
6241
6242 t = lexer.peek_token ();
6243 }
6244
6245 segments.shrink_to_fit ();
6246
6247 return AST::TypePath (std::move (segments), locus,
6248 has_opening_scope_resolution);
6249 }
6250
6251 template <typename ManagedTokenSource>
6252 AST::GenericArg
6253 Parser<ManagedTokenSource>::parse_generic_arg ()
6254 {
6255 auto tok = lexer.peek_token ();
6256 std::unique_ptr<AST::Expr> expr = nullptr;
6257
6258 switch (tok->get_id ())
6259 {
6260 case IDENTIFIER: {
6261 // This is a bit of a weird situation: With an identifier token, we
6262 // could either have a valid type or a macro (FIXME: anything else?). So
6263 // we need one bit of lookahead to differentiate if this is really
6264 auto next_tok = lexer.peek_token (1);
6265 if (next_tok->get_id () == LEFT_ANGLE
6266 || next_tok->get_id () == SCOPE_RESOLUTION
6267 || next_tok->get_id () == EXCLAM)
6268 {
6269 auto type = parse_type ();
6270 if (type)
6271 return AST::GenericArg::create_type (std::move (type));
6272 else
6273 return AST::GenericArg::create_error ();
6274 }
6275 else if (next_tok->get_id () == COLON)
6276 {
6277 lexer.skip_token (); // skip ident
6278 lexer.skip_token (); // skip colon
6279
6280 auto tok = lexer.peek_token ();
6281 std::vector<std::unique_ptr<AST::TypeParamBound>> bounds
6282 = parse_type_param_bounds ();
6283
6284 auto type = std::unique_ptr<AST::TraitObjectType> (
6285 new AST::TraitObjectType (std::move (bounds), tok->get_locus (),
6286 false));
6287 if (type)
6288 return AST::GenericArg::create_type (std::move (type));
6289 else
6290 return AST::GenericArg::create_error ();
6291 }
6292 lexer.skip_token ();
6293 return AST::GenericArg::create_ambiguous (tok->get_str (),
6294 tok->get_locus ());
6295 }
6296 case LEFT_CURLY:
6297 expr = parse_block_expr ();
6298 break;
6299 case MINUS:
6300 case STRING_LITERAL:
6301 case CHAR_LITERAL:
6302 case INT_LITERAL:
6303 case FLOAT_LITERAL:
6304 case TRUE_LITERAL:
6305 case FALSE_LITERAL:
6306 expr = parse_literal_expr ();
6307 break;
6308 // FIXME: Because of this, error reporting is garbage for const generic
6309 // parameter's default values
6310 default: {
6311 auto type = parse_type ();
6312 // FIXME: Find a better way to do this?
6313 if (type)
6314 return AST::GenericArg::create_type (std::move (type));
6315 else
6316 return AST::GenericArg::create_error ();
6317 }
6318 }
6319
6320 if (!expr)
6321 return AST::GenericArg::create_error ();
6322
6323 return AST::GenericArg::create_const (std::move (expr));
6324 }
6325
6326 // Parses the generic arguments in each path segment.
6327 template <typename ManagedTokenSource>
6328 AST::GenericArgs
6329 Parser<ManagedTokenSource>::parse_path_generic_args ()
6330 {
6331 if (lexer.peek_token ()->get_id () == LEFT_SHIFT)
6332 lexer.split_current_token (LEFT_ANGLE, LEFT_ANGLE);
6333
6334 if (!skip_token (LEFT_ANGLE))
6335 {
6336 // skip after somewhere?
6337 return AST::GenericArgs::create_empty ();
6338 }
6339
6340 // We need to parse all lifetimes, then parse types and const generics in
6341 // any order.
6342
6343 // try to parse lifetimes first
6344 std::vector<AST::Lifetime> lifetime_args;
6345
6346 const_TokenPtr t = lexer.peek_token ();
6347 location_t locus = t->get_locus ();
6348 while (!is_right_angle_tok (t->get_id ()))
6349 {
6350 auto lifetime = parse_lifetime (false);
6351 if (!lifetime)
6352 {
6353 // not necessarily an error
6354 break;
6355 }
6356
6357 lifetime_args.push_back (std::move (lifetime.value ()));
6358
6359 // if next token isn't comma, then it must be end of list
6360 if (lexer.peek_token ()->get_id () != COMMA)
6361 {
6362 break;
6363 }
6364 // skip comma
6365 lexer.skip_token ();
6366
6367 t = lexer.peek_token ();
6368 }
6369
6370 // try to parse types and const generics second
6371 std::vector<AST::GenericArg> generic_args;
6372
6373 // TODO: think of better control structure
6374 t = lexer.peek_token ();
6375 while (!is_right_angle_tok (t->get_id ()))
6376 {
6377 // FIXME: Is it fine to break if there is one binding? Can't there be
6378 // bindings in between types?
6379
6380 // ensure not binding being parsed as type accidently
6381 if (t->get_id () == IDENTIFIER
6382 && lexer.peek_token (1)->get_id () == EQUAL)
6383 break;
6384
6385 auto arg = parse_generic_arg ();
6386 if (!arg.is_error ())
6387 {
6388 generic_args.emplace_back (std::move (arg));
6389 }
6390
6391 // FIXME: Do we need to break if we encounter an error?
6392
6393 // if next token isn't comma, then it must be end of list
6394 if (lexer.peek_token ()->get_id () != COMMA)
6395 break;
6396
6397 // skip comma
6398 lexer.skip_token ();
6399 t = lexer.peek_token ();
6400 }
6401
6402 // try to parse bindings third
6403 std::vector<AST::GenericArgsBinding> binding_args;
6404
6405 // TODO: think of better control structure
6406 t = lexer.peek_token ();
6407 while (!is_right_angle_tok (t->get_id ()))
6408 {
6409 AST::GenericArgsBinding binding = parse_generic_args_binding ();
6410 if (binding.is_error ())
6411 {
6412 // not necessarily an error
6413 break;
6414 }
6415
6416 binding_args.push_back (std::move (binding));
6417
6418 // if next token isn't comma, then it must be end of list
6419 if (lexer.peek_token ()->get_id () != COMMA)
6420 {
6421 break;
6422 }
6423 // skip comma
6424 lexer.skip_token ();
6425
6426 t = lexer.peek_token ();
6427 }
6428
6429 // skip any trailing commas
6430 if (lexer.peek_token ()->get_id () == COMMA)
6431 lexer.skip_token ();
6432
6433 if (!skip_generics_right_angle ())
6434 return AST::GenericArgs::create_empty ();
6435
6436 lifetime_args.shrink_to_fit ();
6437 generic_args.shrink_to_fit ();
6438 binding_args.shrink_to_fit ();
6439
6440 return AST::GenericArgs (std::move (lifetime_args), std::move (generic_args),
6441 std::move (binding_args), locus);
6442 }
6443
6444 // Parses a binding in a generic args path segment.
6445 template <typename ManagedTokenSource>
6446 AST::GenericArgsBinding
6447 Parser<ManagedTokenSource>::parse_generic_args_binding ()
6448 {
6449 const_TokenPtr ident_tok = lexer.peek_token ();
6450 if (ident_tok->get_id () != IDENTIFIER)
6451 {
6452 // allow non error-inducing use
6453 // skip somewhere?
6454 return AST::GenericArgsBinding::create_error ();
6455 }
6456 lexer.skip_token ();
6457 Identifier ident{ident_tok};
6458
6459 if (!skip_token (EQUAL))
6460 {
6461 // skip after somewhere?
6462 return AST::GenericArgsBinding::create_error ();
6463 }
6464
6465 // parse type (required)
6466 std::unique_ptr<AST::Type> type = parse_type ();
6467 if (type == nullptr)
6468 {
6469 // skip somewhere?
6470 return AST::GenericArgsBinding::create_error ();
6471 }
6472
6473 return AST::GenericArgsBinding (std::move (ident), std::move (type),
6474 ident_tok->get_locus ());
6475 }
6476
6477 /* Parses a single type path segment (not including opening scope resolution,
6478 * but includes any internal ones). Includes generic args or type path
6479 * functions too. */
6480 template <typename ManagedTokenSource>
6481 std::unique_ptr<AST::TypePathSegment>
6482 Parser<ManagedTokenSource>::parse_type_path_segment ()
6483 {
6484 location_t locus = lexer.peek_token ()->get_locus ();
6485 // parse ident segment part
6486 AST::PathIdentSegment ident_segment = parse_path_ident_segment ();
6487 if (ident_segment.is_error ())
6488 {
6489 // not necessarily an error
6490 return nullptr;
6491 }
6492
6493 /* lookahead to determine if variants exist - only consume scope resolution
6494 * then */
6495 bool has_separating_scope_resolution = false;
6496 const_TokenPtr next = lexer.peek_token (1);
6497 if (lexer.peek_token ()->get_id () == SCOPE_RESOLUTION
6498 && (next->get_id () == LEFT_ANGLE || next->get_id () == LEFT_PAREN))
6499 {
6500 has_separating_scope_resolution = true;
6501 lexer.skip_token ();
6502 }
6503
6504 // branch into variants on next token
6505 const_TokenPtr t = lexer.peek_token ();
6506 switch (t->get_id ())
6507 {
6508 case LEFT_SHIFT:
6509 case LEFT_ANGLE: {
6510 // parse generic args
6511 AST::GenericArgs generic_args = parse_path_generic_args ();
6512
6513 return std::unique_ptr<AST::TypePathSegmentGeneric> (
6514 new AST::TypePathSegmentGeneric (std::move (ident_segment),
6515 has_separating_scope_resolution,
6516 std::move (generic_args), locus));
6517 }
6518 case LEFT_PAREN: {
6519 // parse type path function
6520 AST::TypePathFunction type_path_function
6521 = parse_type_path_function (locus);
6522
6523 if (type_path_function.is_error ())
6524 {
6525 // skip after somewhere?
6526 return nullptr;
6527 }
6528
6529 return std::unique_ptr<AST::TypePathSegmentFunction> (
6530 new AST::TypePathSegmentFunction (std::move (ident_segment),
6531 has_separating_scope_resolution,
6532 std::move (type_path_function),
6533 locus));
6534 }
6535 default:
6536 // neither of them
6537 return std::unique_ptr<AST::TypePathSegment> (
6538 new AST::TypePathSegment (std::move (ident_segment),
6539 has_separating_scope_resolution, locus));
6540 }
6541 rust_unreachable ();
6542 }
6543
6544 // Parses a function call representation inside a type path.
6545 template <typename ManagedTokenSource>
6546 AST::TypePathFunction
6547 Parser<ManagedTokenSource>::parse_type_path_function (location_t id_location)
6548 {
6549 if (!skip_token (LEFT_PAREN))
6550 {
6551 // skip somewhere?
6552 return AST::TypePathFunction::create_error ();
6553 }
6554
6555 // parse function inputs
6556 std::vector<std::unique_ptr<AST::Type>> inputs;
6557
6558 while (lexer.peek_token ()->get_id () != RIGHT_PAREN)
6559 {
6560 std::unique_ptr<AST::Type> type = parse_type ();
6561 if (type == nullptr)
6562 {
6563 /* this is an error as there should've been a ')' there if there
6564 * wasn't a type */
6565 Error error (
6566 lexer.peek_token ()->get_locus (),
6567 "failed to parse type in parameters of type path function");
6568 add_error (std::move (error));
6569
6570 // skip somewhere?
6571 return AST::TypePathFunction::create_error ();
6572 }
6573
6574 inputs.push_back (std::move (type));
6575
6576 // skip commas, including trailing commas
6577 if (lexer.peek_token ()->get_id () != COMMA)
6578 break;
6579
6580 lexer.skip_token ();
6581 }
6582
6583 if (!skip_token (RIGHT_PAREN))
6584 {
6585 // skip somewhere?
6586 return AST::TypePathFunction::create_error ();
6587 }
6588
6589 // parse optional return type
6590 std::unique_ptr<AST::Type> return_type = parse_function_return_type ();
6591
6592 inputs.shrink_to_fit ();
6593 return AST::TypePathFunction (std::move (inputs), id_location,
6594 std::move (return_type));
6595 }
6596
6597 // Parses a path inside an expression that allows generic arguments.
6598 template <typename ManagedTokenSource>
6599 AST::PathInExpression
6600 Parser<ManagedTokenSource>::parse_path_in_expression ()
6601 {
6602 location_t locus = UNKNOWN_LOCATION;
6603 bool has_opening_scope_resolution = false;
6604 if (lexer.peek_token ()->get_id () == SCOPE_RESOLUTION)
6605 {
6606 has_opening_scope_resolution = true;
6607
6608 locus = lexer.peek_token ()->get_locus ();
6609
6610 lexer.skip_token ();
6611 }
6612
6613 // create segment vector
6614 std::vector<AST::PathExprSegment> segments;
6615
6616 if (locus == UNKNOWN_LOCATION)
6617 {
6618 locus = lexer.peek_token ()->get_locus ();
6619 }
6620
6621 // parse required initial segment
6622 AST::PathExprSegment initial_segment = parse_path_expr_segment ();
6623 if (initial_segment.is_error ())
6624 {
6625 // skip after somewhere?
6626 // don't necessarily throw error but yeah
6627 return AST::PathInExpression::create_error ();
6628 }
6629 segments.push_back (std::move (initial_segment));
6630
6631 // parse optional segments (as long as scope resolution operator exists)
6632 const_TokenPtr t = lexer.peek_token ();
6633 while (t->get_id () == SCOPE_RESOLUTION)
6634 {
6635 // skip scope resolution operator
6636 lexer.skip_token ();
6637
6638 // parse the actual segment - it is an error if it doesn't exist now
6639 AST::PathExprSegment segment = parse_path_expr_segment ();
6640 if (segment.is_error ())
6641 {
6642 // skip after somewhere?
6643 Error error (t->get_locus (),
6644 "could not parse path expression segment");
6645 add_error (std::move (error));
6646
6647 return AST::PathInExpression::create_error ();
6648 }
6649
6650 segments.push_back (std::move (segment));
6651
6652 t = lexer.peek_token ();
6653 }
6654
6655 segments.shrink_to_fit ();
6656
6657 return AST::PathInExpression (std::move (segments), {}, locus,
6658 has_opening_scope_resolution);
6659 }
6660
6661 /* Parses a single path in expression path segment (including generic
6662 * arguments). */
6663 template <typename ManagedTokenSource>
6664 AST::PathExprSegment
6665 Parser<ManagedTokenSource>::parse_path_expr_segment ()
6666 {
6667 location_t locus = lexer.peek_token ()->get_locus ();
6668 // parse ident segment
6669 AST::PathIdentSegment ident = parse_path_ident_segment ();
6670 if (ident.is_error ())
6671 {
6672 // not necessarily an error?
6673 return AST::PathExprSegment::create_error ();
6674 }
6675
6676 // parse generic args (and turbofish), if they exist
6677 /* use lookahead to determine if they actually exist (don't want to
6678 * accidently parse over next ident segment) */
6679 if (lexer.peek_token ()->get_id () == SCOPE_RESOLUTION
6680 && (lexer.peek_token (1)->get_id () == LEFT_ANGLE
6681 || lexer.peek_token (1)->get_id () == LEFT_SHIFT))
6682 {
6683 // skip scope resolution
6684 lexer.skip_token ();
6685
6686 // Let parse_path_generic_args split "<<" tokens
6687 AST::GenericArgs generic_args = parse_path_generic_args ();
6688
6689 return AST::PathExprSegment (std::move (ident), locus,
6690 std::move (generic_args));
6691 }
6692
6693 // return a generic parameter-less expr segment if not found
6694 return AST::PathExprSegment (std::move (ident), locus);
6695 }
6696
6697 /* Parses a fully qualified path in expression (i.e. a pattern). FIXME does
6698 * not parse outer attrs. */
6699 template <typename ManagedTokenSource>
6700 AST::QualifiedPathInExpression
6701 Parser<ManagedTokenSource>::parse_qualified_path_in_expression (
6702 location_t pratt_parsed_loc)
6703 {
6704 /* Note: the Rust grammar is defined in such a way that it is impossible to
6705 * determine whether a prospective qualified path is a
6706 * QualifiedPathInExpression or QualifiedPathInType in all cases by the
6707 * rules themselves (the only possible difference is a TypePathSegment with
6708 * function, and lookahead to find this is too difficult). However, as this
6709 * is a pattern and QualifiedPathInType is a type, I believe it that their
6710 * construction will not be confused (due to rules regarding patterns vs
6711 * types).
6712 * As such, this function will not attempt to minimise errors created by
6713 * their confusion. */
6714
6715 // parse the qualified path type (required)
6716 AST::QualifiedPathType qual_path_type
6717 = parse_qualified_path_type (pratt_parsed_loc);
6718 if (qual_path_type.is_error ())
6719 {
6720 // TODO: should this create a parse error?
6721 return AST::QualifiedPathInExpression::create_error ();
6722 }
6723 location_t locus = qual_path_type.get_locus ();
6724
6725 // parse path segments
6726 std::vector<AST::PathExprSegment> segments;
6727
6728 // parse initial required segment
6729 if (!expect_token (SCOPE_RESOLUTION))
6730 {
6731 // skip after somewhere?
6732
6733 return AST::QualifiedPathInExpression::create_error ();
6734 }
6735 AST::PathExprSegment initial_segment = parse_path_expr_segment ();
6736 if (initial_segment.is_error ())
6737 {
6738 // skip after somewhere?
6739 Error error (lexer.peek_token ()->get_locus (),
6740 "required initial path expression segment in "
6741 "qualified path in expression could not be parsed");
6742 add_error (std::move (error));
6743
6744 return AST::QualifiedPathInExpression::create_error ();
6745 }
6746 segments.push_back (std::move (initial_segment));
6747
6748 // parse optional segments (as long as scope resolution operator exists)
6749 const_TokenPtr t = lexer.peek_token ();
6750 while (t->get_id () == SCOPE_RESOLUTION)
6751 {
6752 // skip scope resolution operator
6753 lexer.skip_token ();
6754
6755 // parse the actual segment - it is an error if it doesn't exist now
6756 AST::PathExprSegment segment = parse_path_expr_segment ();
6757 if (segment.is_error ())
6758 {
6759 // skip after somewhere?
6760 Error error (t->get_locus (),
6761 "could not parse path expression segment in qualified "
6762 "path in expression");
6763 add_error (std::move (error));
6764
6765 return AST::QualifiedPathInExpression::create_error ();
6766 }
6767
6768 segments.push_back (std::move (segment));
6769
6770 t = lexer.peek_token ();
6771 }
6772
6773 segments.shrink_to_fit ();
6774
6775 // FIXME: outer attr parsing
6776 return AST::QualifiedPathInExpression (std::move (qual_path_type),
6777 std::move (segments), {}, locus);
6778 }
6779
6780 // Parses the type syntactical construction at the start of a qualified path.
6781 template <typename ManagedTokenSource>
6782 AST::QualifiedPathType
6783 Parser<ManagedTokenSource>::parse_qualified_path_type (
6784 location_t pratt_parsed_loc)
6785 {
6786 location_t locus = pratt_parsed_loc;
6787 /* TODO: should this actually be error? is there anywhere where this could
6788 * be valid? */
6789 if (locus == UNKNOWN_LOCATION)
6790 {
6791 locus = lexer.peek_token ()->get_locus ();
6792
6793 if (lexer.peek_token ()->get_id () == LEFT_SHIFT)
6794 lexer.split_current_token (LEFT_ANGLE, LEFT_ANGLE);
6795
6796 // skip after somewhere?
6797 if (!skip_token (LEFT_ANGLE))
6798 return AST::QualifiedPathType::create_error ();
6799 }
6800
6801 // parse type (required)
6802 std::unique_ptr<AST::Type> type = parse_type ();
6803 if (type == nullptr)
6804 {
6805 Error error (lexer.peek_token ()->get_locus (),
6806 "could not parse type in qualified path type");
6807 add_error (std::move (error));
6808
6809 // skip somewhere?
6810 return AST::QualifiedPathType::create_error ();
6811 }
6812
6813 // parse optional as clause
6814 AST::TypePath as_type_path = AST::TypePath::create_error ();
6815 if (lexer.peek_token ()->get_id () == AS)
6816 {
6817 lexer.skip_token ();
6818
6819 // parse type path, which is required now
6820 as_type_path = parse_type_path ();
6821 if (as_type_path.is_error ())
6822 {
6823 Error error (
6824 lexer.peek_token ()->get_locus (),
6825 "could not parse type path in as clause in qualified path type");
6826 add_error (std::move (error));
6827
6828 // skip somewhere?
6829 return AST::QualifiedPathType::create_error ();
6830 }
6831 }
6832
6833 /* NOTE: should actually be a right-angle token, so
6834 * skip_generics_right_angle shouldn't be required */
6835 if (!skip_token (RIGHT_ANGLE))
6836 {
6837 // skip after somewhere?
6838 return AST::QualifiedPathType::create_error ();
6839 }
6840
6841 return AST::QualifiedPathType (std::move (type), locus,
6842 std::move (as_type_path));
6843 }
6844
6845 // Parses a fully qualified path in type (i.e. a type).
6846 template <typename ManagedTokenSource>
6847 AST::QualifiedPathInType
6848 Parser<ManagedTokenSource>::parse_qualified_path_in_type ()
6849 {
6850 location_t locus = lexer.peek_token ()->get_locus ();
6851 // parse the qualified path type (required)
6852 AST::QualifiedPathType qual_path_type = parse_qualified_path_type ();
6853 if (qual_path_type.is_error ())
6854 {
6855 // TODO: should this create a parse error?
6856 return AST::QualifiedPathInType::create_error ();
6857 }
6858
6859 // parse initial required segment
6860 if (!expect_token (SCOPE_RESOLUTION))
6861 {
6862 // skip after somewhere?
6863
6864 return AST::QualifiedPathInType::create_error ();
6865 }
6866 std::unique_ptr<AST::TypePathSegment> initial_segment
6867 = parse_type_path_segment ();
6868 if (initial_segment == nullptr)
6869 {
6870 // skip after somewhere?
6871 Error error (lexer.peek_token ()->get_locus (),
6872 "required initial type path segment in qualified path in "
6873 "type could not be parsed");
6874 add_error (std::move (error));
6875
6876 return AST::QualifiedPathInType::create_error ();
6877 }
6878
6879 // parse optional segments (as long as scope resolution operator exists)
6880 std::vector<std::unique_ptr<AST::TypePathSegment>> segments;
6881 const_TokenPtr t = lexer.peek_token ();
6882 while (t->get_id () == SCOPE_RESOLUTION)
6883 {
6884 // skip scope resolution operator
6885 lexer.skip_token ();
6886
6887 // parse the actual segment - it is an error if it doesn't exist now
6888 std::unique_ptr<AST::TypePathSegment> segment
6889 = parse_type_path_segment ();
6890 if (segment == nullptr)
6891 {
6892 // skip after somewhere?
6893 Error error (
6894 t->get_locus (),
6895 "could not parse type path segment in qualified path in type");
6896 add_error (std::move (error));
6897
6898 return AST::QualifiedPathInType::create_error ();
6899 }
6900
6901 segments.push_back (std::move (segment));
6902
6903 t = lexer.peek_token ();
6904 }
6905
6906 segments.shrink_to_fit ();
6907
6908 return AST::QualifiedPathInType (std::move (qual_path_type),
6909 std::move (initial_segment),
6910 std::move (segments), locus);
6911 }
6912
6913 // Parses a self param. Also handles self param not existing.
6914 template <typename ManagedTokenSource>
6915 tl::expected<std::unique_ptr<AST::Param>, ParseSelfError>
6916 Parser<ManagedTokenSource>::parse_self_param ()
6917 {
6918 bool has_reference = false;
6919 AST::Lifetime lifetime = AST::Lifetime::elided ();
6920
6921 location_t locus = lexer.peek_token ()->get_locus ();
6922
6923 // TODO: Feels off, find a better way to clearly express this
6924 std::vector<std::vector<TokenId>> ptrs
6925 = {{ASTERISK, SELF} /* *self */,
6926 {ASTERISK, CONST, SELF} /* *const self */,
6927 {ASTERISK, MUT, SELF} /* *mut self */};
6928
6929 for (auto &s : ptrs)
6930 {
6931 size_t i = 0;
6932 for (i = 0; i < s.size (); i++)
6933 if (lexer.peek_token (i)->get_id () != s[i])
6934 break;
6935 if (i == s.size ())
6936 {
6937 rust_error_at (lexer.peek_token ()->get_locus (),
6938 "cannot pass %<self%> by raw pointer");
6939 return tl::make_unexpected (ParseSelfError::SELF_PTR);
6940 }
6941 }
6942
6943 // Trying to find those patterns:
6944 //
6945 // &'lifetime mut self
6946 // &'lifetime self
6947 // & mut self
6948 // & self
6949 // mut self
6950 // self
6951 //
6952 // If not found, it is probably a function, exit and let function parsing
6953 // handle it.
6954 bool is_self = false;
6955 for (size_t i = 0; i < 5; i++)
6956 if (lexer.peek_token (i)->get_id () == SELF)
6957 is_self = true;
6958
6959 if (!is_self)
6960 return tl::make_unexpected (ParseSelfError::NOT_SELF);
6961
6962 // test if self is a reference parameter
6963 if (lexer.peek_token ()->get_id () == AMP)
6964 {
6965 has_reference = true;
6966 lexer.skip_token ();
6967
6968 // now test whether it has a lifetime
6969 if (lexer.peek_token ()->get_id () == LIFETIME)
6970 {
6971 // something went wrong somehow
6972 if (auto parsed_lifetime = parse_lifetime (true))
6973 {
6974 lifetime = parsed_lifetime.value ();
6975 }
6976 else
6977 {
6978 Error error (lexer.peek_token ()->get_locus (),
6979 "failed to parse lifetime in self param");
6980 add_error (std::move (error));
6981
6982 // skip after somewhere?
6983 return tl::make_unexpected (ParseSelfError::PARSING);
6984 }
6985 }
6986 }
6987
6988 // test for mut
6989 bool has_mut = false;
6990 if (lexer.peek_token ()->get_id () == MUT)
6991 {
6992 has_mut = true;
6993 lexer.skip_token ();
6994 }
6995
6996 // skip self token
6997 const_TokenPtr self_tok = lexer.peek_token ();
6998 if (self_tok->get_id () != SELF)
6999 {
7000 // skip after somewhere?
7001 return tl::make_unexpected (ParseSelfError::NOT_SELF);
7002 }
7003 lexer.skip_token ();
7004
7005 // parse optional type
7006 std::unique_ptr<AST::Type> type = nullptr;
7007 if (lexer.peek_token ()->get_id () == COLON)
7008 {
7009 lexer.skip_token ();
7010
7011 // type is now required
7012 type = parse_type ();
7013 if (type == nullptr)
7014 {
7015 Error error (lexer.peek_token ()->get_locus (),
7016 "could not parse type in self param");
7017 add_error (std::move (error));
7018
7019 // skip after somewhere?
7020 return tl::make_unexpected (ParseSelfError::PARSING);
7021 }
7022 }
7023
7024 // ensure that cannot have both type and reference
7025 if (type != nullptr && has_reference)
7026 {
7027 Error error (
7028 lexer.peek_token ()->get_locus (),
7029 "cannot have both a reference and a type specified in a self param");
7030 add_error (std::move (error));
7031
7032 // skip after somewhere?
7033 return tl::make_unexpected (ParseSelfError::PARSING);
7034 }
7035
7036 if (has_reference)
7037 {
7038 return std::make_unique<AST::SelfParam> (std::move (lifetime), has_mut,
7039 locus);
7040 }
7041 else
7042 {
7043 // note that type may be nullptr here and that's fine
7044 return std::make_unique<AST::SelfParam> (std::move (type), has_mut,
7045 locus);
7046 }
7047 }
7048
7049 /* Parses an expression or macro statement. */
7050 template <typename ManagedTokenSource>
7051 std::unique_ptr<AST::Stmt>
7052 Parser<ManagedTokenSource>::parse_expr_stmt (AST::AttrVec outer_attrs,
7053 ParseRestrictions restrictions)
7054 {
7055 location_t locus = lexer.peek_token ()->get_locus ();
7056
7057 std::unique_ptr<AST::Expr> expr;
7058
7059 switch (lexer.peek_token ()->get_id ())
7060 {
7061 case IDENTIFIER:
7062 case CRATE:
7063 case SUPER:
7064 case SELF:
7065 case SELF_ALIAS:
7066 case DOLLAR_SIGN:
7067 case SCOPE_RESOLUTION: {
7068 AST::PathInExpression path = parse_path_in_expression ();
7069 std::unique_ptr<AST::Expr> null_denotation;
7070
7071 if (lexer.peek_token ()->get_id () == EXCLAM)
7072 {
7073 // Bind a reference to avoid -Wredundant-move on post-P1825R0
7074 // compilers. Change to non-reference type and remove the moves
7075 // below once C++20 is required to build gcc.
7076 std::unique_ptr<AST::MacroInvocation> &&invoc
7077 = parse_macro_invocation_partial (std::move (path),
7078 std::move (outer_attrs));
7079
7080 if (restrictions.consume_semi && maybe_skip_token (SEMICOLON))
7081 {
7082 invoc->add_semicolon ();
7083 // Macro invocation with semicolon.
7084 return std::move (invoc);
7085 }
7086
7087 TokenId after_macro = lexer.peek_token ()->get_id ();
7088
7089 if (restrictions.allow_close_after_expr_stmt
7090 && (after_macro == RIGHT_PAREN || after_macro == RIGHT_CURLY
7091 || after_macro == RIGHT_SQUARE))
7092 return std::move (invoc);
7093
7094 if (invoc->get_invoc_data ().get_delim_tok_tree ().get_delim_type ()
7095 == AST::CURLY
7096 && after_macro != DOT && after_macro != QUESTION_MARK)
7097 {
7098 rust_debug ("braced macro statement");
7099 return std::move (invoc);
7100 }
7101
7102 null_denotation = std::move (invoc);
7103 }
7104 else
7105 {
7106 null_denotation
7107 = null_denotation_path (std::move (path), {}, restrictions);
7108 }
7109
7110 expr = left_denotations (std::move (null_denotation), LBP_LOWEST,
7111 std::move (outer_attrs), restrictions);
7112 break;
7113 }
7114 default:
7115 restrictions.expr_can_be_stmt = true;
7116 expr = parse_expr (std::move (outer_attrs), restrictions);
7117 break;
7118 }
7119
7120 if (expr == nullptr)
7121 {
7122 // expr is required, error
7123 Error error (lexer.peek_token ()->get_locus (),
7124 "failed to parse expr in expr statement");
7125 add_error (std::move (error));
7126
7127 skip_after_semicolon ();
7128 return nullptr;
7129 }
7130
7131 bool has_semi = false;
7132
7133 if (restrictions.consume_semi)
7134 {
7135 if (maybe_skip_token (SEMICOLON))
7136 {
7137 has_semi = true;
7138 }
7139 else if (expr->is_expr_without_block ())
7140 {
7141 if (restrictions.allow_close_after_expr_stmt)
7142 {
7143 TokenId id = lexer.peek_token ()->get_id ();
7144 if (id != RIGHT_PAREN && id != RIGHT_CURLY && id != RIGHT_SQUARE)
7145 {
7146 expect_token (SEMICOLON);
7147 return nullptr;
7148 }
7149 }
7150 else
7151 {
7152 expect_token (SEMICOLON);
7153 return nullptr;
7154 }
7155 }
7156 }
7157
7158 return std::unique_ptr<AST::ExprStmt> (
7159 new AST::ExprStmt (std::move (expr), locus, has_semi));
7160 }
7161
7162 // Parses a block expression, including the curly braces at start and end.
7163 template <typename ManagedTokenSource>
7164 std::unique_ptr<AST::BlockExpr>
7165 Parser<ManagedTokenSource>::parse_block_expr (
7166 AST::AttrVec outer_attrs, tl::optional<AST::LoopLabel> label,
7167 location_t pratt_parsed_loc)
7168 {
7169 location_t locus = pratt_parsed_loc;
7170 if (locus == UNKNOWN_LOCATION)
7171 {
7172 locus = lexer.peek_token ()->get_locus ();
7173 if (!skip_token (LEFT_CURLY))
7174 {
7175 skip_after_end_block ();
7176 return nullptr;
7177 }
7178 }
7179
7180 AST::AttrVec inner_attrs = parse_inner_attributes ();
7181
7182 // parse statements and expression
7183 std::vector<std::unique_ptr<AST::Stmt>> stmts;
7184 std::unique_ptr<AST::Expr> expr = nullptr;
7185
7186 const_TokenPtr t = lexer.peek_token ();
7187 while (t->get_id () != RIGHT_CURLY)
7188 {
7189 ExprOrStmt expr_or_stmt = parse_stmt_or_expr ();
7190 if (expr_or_stmt.is_error ())
7191 {
7192 Error error (
7193 t->get_locus (),
7194 "failed to parse statement or expression in block expression");
7195 add_error (std::move (error));
7196
7197 return nullptr;
7198 }
7199
7200 t = lexer.peek_token ();
7201
7202 if (expr_or_stmt.stmt != nullptr)
7203 {
7204 stmts.push_back (std::move (expr_or_stmt.stmt));
7205 }
7206 else
7207 {
7208 // assign to expression and end parsing inside
7209 expr = std::move (expr_or_stmt.expr);
7210 break;
7211 }
7212 }
7213
7214 location_t end_locus = t->get_locus ();
7215
7216 if (!skip_token (RIGHT_CURLY))
7217 {
7218 Error error (t->get_locus (),
7219 "error may be from having an expression (as opposed to "
7220 "statement) in the body of the function but not last");
7221 add_error (std::move (error));
7222
7223 skip_after_end_block ();
7224 return nullptr;
7225 }
7226
7227 // grammar allows for empty block expressions
7228
7229 stmts.shrink_to_fit ();
7230
7231 return std::unique_ptr<AST::BlockExpr> (
7232 new AST::BlockExpr (std::move (stmts), std::move (expr),
7233 std::move (inner_attrs), std::move (outer_attrs),
7234 std::move (label), locus, end_locus));
7235 }
7236
7237 /* Parses a "grouped" expression (expression in parentheses), used to control
7238 * precedence. */
7239 template <typename ManagedTokenSource>
7240 std::unique_ptr<AST::GroupedExpr>
7241 Parser<ManagedTokenSource>::parse_grouped_expr (AST::AttrVec outer_attrs)
7242 {
7243 location_t locus = lexer.peek_token ()->get_locus ();
7244 skip_token (LEFT_PAREN);
7245
7246 AST::AttrVec inner_attrs = parse_inner_attributes ();
7247
7248 // parse required expr inside parentheses
7249 std::unique_ptr<AST::Expr> expr_in_parens = parse_expr ();
7250 if (expr_in_parens == nullptr)
7251 {
7252 // skip after somewhere?
7253 // error?
7254 return nullptr;
7255 }
7256
7257 if (!skip_token (RIGHT_PAREN))
7258 {
7259 // skip after somewhere?
7260 return nullptr;
7261 }
7262
7263 return std::unique_ptr<AST::GroupedExpr> (
7264 new AST::GroupedExpr (std::move (expr_in_parens), std::move (inner_attrs),
7265 std::move (outer_attrs), locus));
7266 }
7267
7268 // Parses a closure expression (closure definition).
7269 template <typename ManagedTokenSource>
7270 std::unique_ptr<AST::ClosureExpr>
7271 Parser<ManagedTokenSource>::parse_closure_expr (AST::AttrVec outer_attrs)
7272 {
7273 location_t locus = lexer.peek_token ()->get_locus ();
7274 // detect optional "move"
7275 bool has_move = false;
7276 if (lexer.peek_token ()->get_id () == MOVE)
7277 {
7278 lexer.skip_token ();
7279 has_move = true;
7280 }
7281
7282 // handle parameter list
7283 std::vector<AST::ClosureParam> params;
7284
7285 const_TokenPtr t = lexer.peek_token ();
7286 switch (t->get_id ())
7287 {
7288 case OR:
7289 // skip token, no parameters
7290 lexer.skip_token ();
7291 break;
7292 case PIPE:
7293 // actually may have parameters
7294 lexer.skip_token ();
7295 t = lexer.peek_token ();
7296
7297 while (t->get_id () != PIPE)
7298 {
7299 AST::ClosureParam param = parse_closure_param ();
7300 if (param.is_error ())
7301 {
7302 // TODO is this really an error?
7303 Error error (t->get_locus (), "could not parse closure param");
7304 add_error (std::move (error));
7305
7306 break;
7307 }
7308 params.push_back (std::move (param));
7309
7310 if (lexer.peek_token ()->get_id () != COMMA)
7311 {
7312 lexer.skip_token ();
7313 // not an error but means param list is done
7314 break;
7315 }
7316 // skip comma
7317 lexer.skip_token ();
7318
7319 t = lexer.peek_token ();
7320 }
7321 params.shrink_to_fit ();
7322 break;
7323 default:
7324 add_error (Error (t->get_locus (),
7325 "unexpected token %qs in closure expression - expected "
7326 "%<|%> or %<||%>",
7327 t->get_token_description ()));
7328
7329 // skip somewhere?
7330 return nullptr;
7331 }
7332
7333 // again branch based on next token
7334 t = lexer.peek_token ();
7335 if (t->get_id () == RETURN_TYPE)
7336 {
7337 // must be return type closure with block expr
7338
7339 // skip "return type" token
7340 lexer.skip_token ();
7341
7342 // parse actual type, which is required
7343 std::unique_ptr<AST::TypeNoBounds> type = parse_type_no_bounds ();
7344 if (type == nullptr)
7345 {
7346 // error
7347 Error error (t->get_locus (), "failed to parse type for closure");
7348 add_error (std::move (error));
7349
7350 // skip somewhere?
7351 return nullptr;
7352 }
7353
7354 // parse block expr, which is required
7355 std::unique_ptr<AST::BlockExpr> block = parse_block_expr ();
7356 if (block == nullptr)
7357 {
7358 // error
7359 Error error (lexer.peek_token ()->get_locus (),
7360 "failed to parse block expr in closure");
7361 add_error (std::move (error));
7362
7363 // skip somewhere?
7364 return nullptr;
7365 }
7366
7367 return std::unique_ptr<AST::ClosureExprInnerTyped> (
7368 new AST::ClosureExprInnerTyped (std::move (type), std::move (block),
7369 std::move (params), locus, has_move,
7370 std::move (outer_attrs)));
7371 }
7372 else
7373 {
7374 // must be expr-only closure
7375
7376 // parse expr, which is required
7377 std::unique_ptr<AST::Expr> expr = parse_expr ();
7378 if (expr == nullptr)
7379 {
7380 Error error (t->get_locus (),
7381 "failed to parse expression in closure");
7382 add_error (std::move (error));
7383
7384 // skip somewhere?
7385 return nullptr;
7386 }
7387
7388 return std::unique_ptr<AST::ClosureExprInner> (
7389 new AST::ClosureExprInner (std::move (expr), std::move (params), locus,
7390 has_move, std::move (outer_attrs)));
7391 }
7392 }
7393
7394 // Parses a literal token (to literal expression).
7395 template <typename ManagedTokenSource>
7396 std::unique_ptr<AST::LiteralExpr>
7397 Parser<ManagedTokenSource>::parse_literal_expr (AST::AttrVec outer_attrs)
7398 {
7399 // TODO: change if literal representation in lexer changes
7400
7401 std::string literal_value;
7402 AST::Literal::LitType type = AST::Literal::STRING;
7403
7404 // branch based on token
7405 const_TokenPtr t = lexer.peek_token ();
7406 switch (t->get_id ())
7407 {
7408 case CHAR_LITERAL:
7409 type = AST::Literal::CHAR;
7410 literal_value = t->get_str ();
7411 lexer.skip_token ();
7412 break;
7413 case STRING_LITERAL:
7414 type = AST::Literal::STRING;
7415 literal_value = t->get_str ();
7416 lexer.skip_token ();
7417 break;
7418 case BYTE_CHAR_LITERAL:
7419 type = AST::Literal::BYTE;
7420 literal_value = t->get_str ();
7421 lexer.skip_token ();
7422 break;
7423 case BYTE_STRING_LITERAL:
7424 type = AST::Literal::BYTE_STRING;
7425 literal_value = t->get_str ();
7426 lexer.skip_token ();
7427 break;
7428 case RAW_STRING_LITERAL:
7429 type = AST::Literal::RAW_STRING;
7430 literal_value = t->get_str ();
7431 lexer.skip_token ();
7432 break;
7433 case INT_LITERAL:
7434 type = AST::Literal::INT;
7435 literal_value = t->get_str ();
7436 lexer.skip_token ();
7437 break;
7438 case FLOAT_LITERAL:
7439 type = AST::Literal::FLOAT;
7440 literal_value = t->get_str ();
7441 lexer.skip_token ();
7442 break;
7443 // case BOOL_LITERAL
7444 // use true and false keywords rather than "bool literal" Rust terminology
7445 case TRUE_LITERAL:
7446 type = AST::Literal::BOOL;
7447 literal_value = Values::Keywords::TRUE_LITERAL;
7448 lexer.skip_token ();
7449 break;
7450 case FALSE_LITERAL:
7451 type = AST::Literal::BOOL;
7452 literal_value = Values::Keywords::FALSE_LITERAL;
7453 lexer.skip_token ();
7454 break;
7455 default:
7456 // error - cannot be a literal expr
7457 add_error (Error (t->get_locus (),
7458 "unexpected token %qs when parsing literal expression",
7459 t->get_token_description ()));
7460
7461 // skip?
7462 return nullptr;
7463 }
7464
7465 // create literal based on stuff in switch
7466 return std::unique_ptr<AST::LiteralExpr> (
7467 new AST::LiteralExpr (std::move (literal_value), std::move (type),
7468 t->get_type_hint (), std::move (outer_attrs),
7469 t->get_locus ()));
7470 }
7471
7472 template <typename ManagedTokenSource>
7473 std::unique_ptr<AST::BoxExpr>
7474 Parser<ManagedTokenSource>::parse_box_expr (AST::AttrVec outer_attrs,
7475 location_t pratt_parsed_loc)
7476 {
7477 location_t locus = pratt_parsed_loc;
7478 if (locus == UNKNOWN_LOCATION)
7479 {
7480 locus = lexer.peek_token ()->get_locus ();
7481 skip_token (BOX);
7482 }
7483
7484 ParseRestrictions restrictions;
7485 restrictions.expr_can_be_null = false;
7486
7487 std::unique_ptr<AST::Expr> expr = parse_expr (AST::AttrVec (), restrictions);
7488
7489 return std::unique_ptr<AST::BoxExpr> (
7490 new AST::BoxExpr (std::move (expr), std::move (outer_attrs), locus));
7491 }
7492
7493 // Parses a return expression (including any expression to return).
7494 template <typename ManagedTokenSource>
7495 std::unique_ptr<AST::ReturnExpr>
7496 Parser<ManagedTokenSource>::parse_return_expr (AST::AttrVec outer_attrs,
7497 location_t pratt_parsed_loc)
7498 {
7499 location_t locus = pratt_parsed_loc;
7500 if (locus == UNKNOWN_LOCATION)
7501 {
7502 locus = lexer.peek_token ()->get_locus ();
7503 skip_token (RETURN_KW);
7504 }
7505
7506 // parse expression to return, if it exists
7507 ParseRestrictions restrictions;
7508 restrictions.expr_can_be_null = true;
7509 std::unique_ptr<AST::Expr> returned_expr
7510 = parse_expr (AST::AttrVec (), restrictions);
7511
7512 return std::unique_ptr<AST::ReturnExpr> (
7513 new AST::ReturnExpr (std::move (returned_expr), std::move (outer_attrs),
7514 locus));
7515 }
7516
7517 /* Parses a break expression (including any label to break to AND any return
7518 * expression). */
7519 template <typename ManagedTokenSource>
7520 std::unique_ptr<AST::BreakExpr>
7521 Parser<ManagedTokenSource>::parse_break_expr (AST::AttrVec outer_attrs,
7522 location_t pratt_parsed_loc)
7523 {
7524 location_t locus = pratt_parsed_loc;
7525 if (locus == UNKNOWN_LOCATION)
7526 {
7527 locus = lexer.peek_token ()->get_locus ();
7528 skip_token (BREAK);
7529 }
7530
7531 auto parsed_label = parse_lifetime (false);
7532 auto label = (parsed_label)
7533 ? tl::optional<AST::Lifetime> (parsed_label.value ())
7534 : tl::nullopt;
7535
7536 // parse break return expression if it exists
7537 ParseRestrictions restrictions;
7538 restrictions.expr_can_be_null = true;
7539 std::unique_ptr<AST::Expr> return_expr
7540 = parse_expr (AST::AttrVec (), restrictions);
7541
7542 return std::unique_ptr<AST::BreakExpr> (
7543 new AST::BreakExpr (std::move (label), std::move (return_expr),
7544 std::move (outer_attrs), locus));
7545 }
7546
7547 // Parses a continue expression (including any label to continue from).
7548 template <typename ManagedTokenSource>
7549 std::unique_ptr<AST::ContinueExpr>
7550 Parser<ManagedTokenSource>::parse_continue_expr (AST::AttrVec outer_attrs,
7551 location_t pratt_parsed_loc)
7552 {
7553 location_t locus = pratt_parsed_loc;
7554 if (locus == UNKNOWN_LOCATION)
7555 {
7556 locus = lexer.peek_token ()->get_locus ();
7557 skip_token (CONTINUE);
7558 }
7559
7560 auto parsed_label = parse_lifetime (false);
7561 auto label = (parsed_label)
7562 ? tl::optional<AST::Lifetime> (parsed_label.value ())
7563 : tl::nullopt;
7564
7565 return std::unique_ptr<AST::ContinueExpr> (
7566 new AST::ContinueExpr (std::move (label), std::move (outer_attrs), locus));
7567 }
7568
7569 // Parses a loop label used in loop expressions.
7570 template <typename ManagedTokenSource>
7571 tl::expected<AST::LoopLabel, ParseLoopLabelError>
7572 Parser<ManagedTokenSource>::parse_loop_label (const_TokenPtr tok)
7573 {
7574 // parse lifetime - if doesn't exist, assume no label
7575 if (tok->get_id () != LIFETIME)
7576 {
7577 // not necessarily an error
7578 return tl::unexpected<ParseLoopLabelError> (
7579 ParseLoopLabelError::NOT_LOOP_LABEL);
7580 }
7581 /* FIXME: check for named lifetime requirement here? or check in semantic
7582 * analysis phase? */
7583 AST::Lifetime label = lifetime_from_token (tok);
7584
7585 if (!skip_token (COLON))
7586 {
7587 // skip somewhere?
7588 return tl::unexpected<ParseLoopLabelError> (
7589 ParseLoopLabelError::MISSING_COLON);
7590 }
7591
7592 return tl::expected<AST::LoopLabel, ParseLoopLabelError> (
7593 AST::LoopLabel (std::move (label), tok->get_locus ()));
7594 }
7595
7596 /* Parses an if expression of any kind, including with else, else if, else if
7597 * let, and neither. Note that any outer attributes will be ignored because if
7598 * expressions don't support them. */
7599 template <typename ManagedTokenSource>
7600 std::unique_ptr<AST::IfExpr>
7601 Parser<ManagedTokenSource>::parse_if_expr (AST::AttrVec outer_attrs,
7602 location_t pratt_parsed_loc)
7603 {
7604 // TODO: make having outer attributes an error?
7605 location_t locus = pratt_parsed_loc;
7606 if (locus == UNKNOWN_LOCATION)
7607 {
7608 locus = lexer.peek_token ()->get_locus ();
7609 if (!skip_token (IF))
7610 {
7611 skip_after_end_block ();
7612 return nullptr;
7613 }
7614 }
7615
7616 // detect accidental if let
7617 if (lexer.peek_token ()->get_id () == LET)
7618 {
7619 Error error (lexer.peek_token ()->get_locus (),
7620 "if let expression probably exists, but is being parsed "
7621 "as an if expression. This may be a parser error");
7622 add_error (std::move (error));
7623
7624 // skip somewhere?
7625 return nullptr;
7626 }
7627
7628 /* parse required condition expr - HACK to prevent struct expr from being
7629 * parsed */
7630 ParseRestrictions no_struct_expr;
7631 no_struct_expr.can_be_struct_expr = false;
7632 std::unique_ptr<AST::Expr> condition = parse_expr ({}, no_struct_expr);
7633 if (condition == nullptr)
7634 {
7635 Error error (lexer.peek_token ()->get_locus (),
7636 "failed to parse condition expression in if expression");
7637 add_error (std::move (error));
7638
7639 // skip somewhere?
7640 return nullptr;
7641 }
7642
7643 // parse required block expr
7644 std::unique_ptr<AST::BlockExpr> if_body = parse_block_expr ();
7645 if (if_body == nullptr)
7646 {
7647 Error error (lexer.peek_token ()->get_locus (),
7648 "failed to parse if body block expression in if expression");
7649 add_error (std::move (error));
7650
7651 // skip somewhere?
7652 return nullptr;
7653 }
7654
7655 // branch to parse end or else (and then else, else if, or else if let)
7656 if (lexer.peek_token ()->get_id () != ELSE)
7657 {
7658 // single selection - end of if expression
7659 return std::unique_ptr<AST::IfExpr> (
7660 new AST::IfExpr (std::move (condition), std::move (if_body),
7661 std::move (outer_attrs), locus));
7662 }
7663 else
7664 {
7665 // double or multiple selection - branch on end, else if, or else if let
7666
7667 // skip "else"
7668 lexer.skip_token ();
7669
7670 // branch on whether next token is '{' or 'if'
7671 const_TokenPtr t = lexer.peek_token ();
7672 switch (t->get_id ())
7673 {
7674 case LEFT_CURLY: {
7675 // double selection - else
7676 // parse else block expr (required)
7677 std::unique_ptr<AST::BlockExpr> else_body = parse_block_expr ();
7678 if (else_body == nullptr)
7679 {
7680 Error error (lexer.peek_token ()->get_locus (),
7681 "failed to parse else body block expression in "
7682 "if expression");
7683 add_error (std::move (error));
7684
7685 // skip somewhere?
7686 return nullptr;
7687 }
7688
7689 return std::unique_ptr<AST::IfExprConseqElse> (
7690 new AST::IfExprConseqElse (std::move (condition),
7691 std::move (if_body),
7692 std::move (else_body),
7693 std::move (outer_attrs), locus));
7694 }
7695 case IF: {
7696 // multiple selection - else if or else if let
7697 // branch on whether next token is 'let' or not
7698 if (lexer.peek_token (1)->get_id () == LET)
7699 {
7700 // parse if let expr (required)
7701 std::unique_ptr<AST::IfLetExpr> if_let_expr
7702 = parse_if_let_expr ();
7703 if (if_let_expr == nullptr)
7704 {
7705 Error error (lexer.peek_token ()->get_locus (),
7706 "failed to parse (else) if let expression "
7707 "after if expression");
7708 add_error (std::move (error));
7709
7710 // skip somewhere?
7711 return nullptr;
7712 }
7713
7714 return std::unique_ptr<AST::IfExprConseqElse> (
7715 new AST::IfExprConseqElse (std::move (condition),
7716 std::move (if_body),
7717 std::move (if_let_expr),
7718 std::move (outer_attrs), locus));
7719 }
7720 else
7721 {
7722 // parse if expr (required)
7723 std::unique_ptr<AST::IfExpr> if_expr = parse_if_expr ();
7724 if (if_expr == nullptr)
7725 {
7726 Error error (lexer.peek_token ()->get_locus (),
7727 "failed to parse (else) if expression after "
7728 "if expression");
7729 add_error (std::move (error));
7730
7731 // skip somewhere?
7732 return nullptr;
7733 }
7734
7735 return std::unique_ptr<AST::IfExprConseqElse> (
7736 new AST::IfExprConseqElse (std::move (condition),
7737 std::move (if_body),
7738 std::move (if_expr),
7739 std::move (outer_attrs), locus));
7740 }
7741 }
7742 default:
7743 // error - invalid token
7744 add_error (Error (t->get_locus (),
7745 "unexpected token %qs after else in if expression",
7746 t->get_token_description ()));
7747
7748 // skip somewhere?
7749 return nullptr;
7750 }
7751 }
7752 }
7753
7754 /* Parses an if let expression of any kind, including with else, else if, else
7755 * if let, and none. Note that any outer attributes will be ignored as if let
7756 * expressions don't support them. */
7757 template <typename ManagedTokenSource>
7758 std::unique_ptr<AST::IfLetExpr>
7759 Parser<ManagedTokenSource>::parse_if_let_expr (AST::AttrVec outer_attrs,
7760 location_t pratt_parsed_loc)
7761 {
7762 // TODO: make having outer attributes an error?
7763 location_t locus = pratt_parsed_loc;
7764 if (locus == UNKNOWN_LOCATION)
7765 {
7766 locus = lexer.peek_token ()->get_locus ();
7767 if (!skip_token (IF))
7768 {
7769 skip_after_end_block ();
7770 return nullptr;
7771 }
7772 }
7773
7774 // detect accidental if expr parsed as if let expr
7775 if (lexer.peek_token ()->get_id () != LET)
7776 {
7777 Error error (lexer.peek_token ()->get_locus (),
7778 "if expression probably exists, but is being parsed as an "
7779 "if let expression. This may be a parser error");
7780 add_error (std::move (error));
7781
7782 // skip somewhere?
7783 return nullptr;
7784 }
7785 lexer.skip_token ();
7786
7787 // parse match arm patterns (which are required)
7788 std::vector<std::unique_ptr<AST::Pattern>> match_arm_patterns
7789 = parse_match_arm_patterns (EQUAL);
7790 if (match_arm_patterns.empty ())
7791 {
7792 Error error (
7793 lexer.peek_token ()->get_locus (),
7794 "failed to parse any match arm patterns in if let expression");
7795 add_error (std::move (error));
7796
7797 // skip somewhere?
7798 return nullptr;
7799 }
7800
7801 if (!skip_token (EQUAL))
7802 {
7803 // skip somewhere?
7804 return nullptr;
7805 }
7806
7807 // parse expression (required) - HACK to prevent struct expr being parsed
7808 ParseRestrictions no_struct_expr;
7809 no_struct_expr.can_be_struct_expr = false;
7810 std::unique_ptr<AST::Expr> scrutinee_expr = parse_expr ({}, no_struct_expr);
7811 if (scrutinee_expr == nullptr)
7812 {
7813 Error error (lexer.peek_token ()->get_locus (),
7814 "failed to parse scrutinee expression in if let expression");
7815 add_error (std::move (error));
7816
7817 // skip somewhere?
7818 return nullptr;
7819 }
7820 /* TODO: check for expression not being a struct expression or lazy boolean
7821 * expression here? or actually probably in semantic analysis. */
7822
7823 // parse block expression (required)
7824 std::unique_ptr<AST::BlockExpr> if_let_body = parse_block_expr ();
7825 if (if_let_body == nullptr)
7826 {
7827 Error error (
7828 lexer.peek_token ()->get_locus (),
7829 "failed to parse if let body block expression in if let expression");
7830 add_error (std::move (error));
7831
7832 // skip somewhere?
7833 return nullptr;
7834 }
7835
7836 // branch to parse end or else (and then else, else if, or else if let)
7837 if (lexer.peek_token ()->get_id () != ELSE)
7838 {
7839 // single selection - end of if let expression
7840 return std::unique_ptr<AST::IfLetExpr> (
7841 new AST::IfLetExpr (std::move (match_arm_patterns),
7842 std::move (scrutinee_expr), std::move (if_let_body),
7843 std::move (outer_attrs), locus));
7844 }
7845 else
7846 {
7847 // double or multiple selection - branch on end, else if, or else if let
7848
7849 // skip "else"
7850 lexer.skip_token ();
7851
7852 // branch on whether next token is '{' or 'if'
7853 const_TokenPtr t = lexer.peek_token ();
7854 switch (t->get_id ())
7855 {
7856 case LEFT_CURLY: {
7857 // double selection - else
7858 // parse else block expr (required)
7859 std::unique_ptr<AST::BlockExpr> else_body = parse_block_expr ();
7860 if (else_body == nullptr)
7861 {
7862 Error error (lexer.peek_token ()->get_locus (),
7863 "failed to parse else body block expression in "
7864 "if let expression");
7865 add_error (std::move (error));
7866
7867 // skip somewhere?
7868 return nullptr;
7869 }
7870
7871 return std::unique_ptr<AST::IfLetExprConseqElse> (
7872 new AST::IfLetExprConseqElse (std::move (match_arm_patterns),
7873 std::move (scrutinee_expr),
7874 std::move (if_let_body),
7875 std::move (else_body),
7876 std::move (outer_attrs), locus));
7877 }
7878 case IF: {
7879 // multiple selection - else if or else if let
7880 // branch on whether next token is 'let' or not
7881 if (lexer.peek_token (1)->get_id () == LET)
7882 {
7883 // parse if let expr (required)
7884 std::unique_ptr<AST::IfLetExpr> if_let_expr
7885 = parse_if_let_expr ();
7886 if (if_let_expr == nullptr)
7887 {
7888 Error error (lexer.peek_token ()->get_locus (),
7889 "failed to parse (else) if let expression "
7890 "after if let expression");
7891 add_error (std::move (error));
7892
7893 // skip somewhere?
7894 return nullptr;
7895 }
7896
7897 return std::unique_ptr<AST::IfLetExprConseqElse> (
7898 new AST::IfLetExprConseqElse (
7899 std::move (match_arm_patterns), std::move (scrutinee_expr),
7900 std::move (if_let_body), std::move (if_let_expr),
7901 std::move (outer_attrs), locus));
7902 }
7903 else
7904 {
7905 // parse if expr (required)
7906 std::unique_ptr<AST::IfExpr> if_expr = parse_if_expr ();
7907 if (if_expr == nullptr)
7908 {
7909 Error error (lexer.peek_token ()->get_locus (),
7910 "failed to parse (else) if expression after "
7911 "if let expression");
7912 add_error (std::move (error));
7913
7914 // skip somewhere?
7915 return nullptr;
7916 }
7917
7918 return std::unique_ptr<AST::IfLetExprConseqElse> (
7919 new AST::IfLetExprConseqElse (
7920 std::move (match_arm_patterns), std::move (scrutinee_expr),
7921 std::move (if_let_body), std::move (if_expr),
7922 std::move (outer_attrs), locus));
7923 }
7924 }
7925 default:
7926 // error - invalid token
7927 add_error (
7928 Error (t->get_locus (),
7929 "unexpected token %qs after else in if let expression",
7930 t->get_token_description ()));
7931
7932 // skip somewhere?
7933 return nullptr;
7934 }
7935 }
7936 }
7937
7938 /* TODO: possibly decide on different method of handling label (i.e. not
7939 * parameter) */
7940
7941 /* Parses a "loop" infinite loop expression. Label is not parsed and should be
7942 * parsed via parse_labelled_loop_expr, which would call this. */
7943 template <typename ManagedTokenSource>
7944 std::unique_ptr<AST::LoopExpr>
7945 Parser<ManagedTokenSource>::parse_loop_expr (AST::AttrVec outer_attrs,
7946 tl::optional<AST::LoopLabel> label,
7947 location_t pratt_parsed_loc)
7948 {
7949 location_t locus = pratt_parsed_loc;
7950 if (locus == UNKNOWN_LOCATION)
7951 {
7952 if (label)
7953 locus = label->get_locus ();
7954 else
7955 locus = lexer.peek_token ()->get_locus ();
7956
7957 if (!skip_token (LOOP))
7958 {
7959 skip_after_end_block ();
7960 return nullptr;
7961 }
7962 }
7963 else
7964 {
7965 if (label)
7966 locus = label->get_locus ();
7967 }
7968
7969 // parse loop body, which is required
7970 std::unique_ptr<AST::BlockExpr> loop_body = parse_block_expr ();
7971 if (loop_body == nullptr)
7972 {
7973 Error error (lexer.peek_token ()->get_locus (),
7974 "could not parse loop body in (infinite) loop expression");
7975 add_error (std::move (error));
7976
7977 return nullptr;
7978 }
7979
7980 return std::unique_ptr<AST::LoopExpr> (
7981 new AST::LoopExpr (std::move (loop_body), locus, std::move (label),
7982 std::move (outer_attrs)));
7983 }
7984
7985 /* Parses a "while" loop expression. Label is not parsed and should be parsed
7986 * via parse_labelled_loop_expr, which would call this. */
7987 template <typename ManagedTokenSource>
7988 std::unique_ptr<AST::WhileLoopExpr>
7989 Parser<ManagedTokenSource>::parse_while_loop_expr (
7990 AST::AttrVec outer_attrs, tl::optional<AST::LoopLabel> label,
7991 location_t pratt_parsed_loc)
7992 {
7993 location_t locus = pratt_parsed_loc;
7994 if (locus == UNKNOWN_LOCATION)
7995 {
7996 if (label)
7997 locus = label->get_locus ();
7998 else
7999 locus = lexer.peek_token ()->get_locus ();
8000
8001 if (!skip_token (WHILE))
8002 {
8003 skip_after_end_block ();
8004 return nullptr;
8005 }
8006 }
8007 else
8008 {
8009 if (label)
8010 locus = label->get_locus ();
8011 }
8012
8013 // ensure it isn't a while let loop
8014 if (lexer.peek_token ()->get_id () == LET)
8015 {
8016 Error error (lexer.peek_token ()->get_locus (),
8017 "appears to be while let loop but is being parsed by "
8018 "while loop - this may be a compiler issue");
8019 add_error (std::move (error));
8020
8021 // skip somewhere?
8022 return nullptr;
8023 }
8024
8025 // parse loop predicate (required) with HACK to prevent struct expr parsing
8026 ParseRestrictions no_struct_expr;
8027 no_struct_expr.can_be_struct_expr = false;
8028 std::unique_ptr<AST::Expr> predicate = parse_expr ({}, no_struct_expr);
8029 if (predicate == nullptr)
8030 {
8031 Error error (lexer.peek_token ()->get_locus (),
8032 "failed to parse predicate expression in while loop");
8033 add_error (std::move (error));
8034
8035 // skip somewhere?
8036 return nullptr;
8037 }
8038 /* TODO: check that it isn't struct expression here? actually, probably in
8039 * semantic analysis */
8040
8041 // parse loop body (required)
8042 std::unique_ptr<AST::BlockExpr> body = parse_block_expr ();
8043 if (body == nullptr)
8044 {
8045 Error error (lexer.peek_token ()->get_locus (),
8046 "failed to parse loop body block expression in while loop");
8047 add_error (std::move (error));
8048
8049 // skip somewhere
8050 return nullptr;
8051 }
8052
8053 return std::unique_ptr<AST::WhileLoopExpr> (
8054 new AST::WhileLoopExpr (std::move (predicate), std::move (body), locus,
8055 std::move (label), std::move (outer_attrs)));
8056 }
8057
8058 /* Parses a "while let" loop expression. Label is not parsed and should be
8059 * parsed via parse_labelled_loop_expr, which would call this. */
8060 template <typename ManagedTokenSource>
8061 std::unique_ptr<AST::WhileLetLoopExpr>
8062 Parser<ManagedTokenSource>::parse_while_let_loop_expr (
8063 AST::AttrVec outer_attrs, tl::optional<AST::LoopLabel> label)
8064 {
8065 location_t locus = UNKNOWN_LOCATION;
8066 if (label)
8067 locus = label->get_locus ();
8068 else
8069 locus = lexer.peek_token ()->get_locus ();
8070 maybe_skip_token (WHILE);
8071
8072 /* check for possible accidental recognition of a while loop as a while let
8073 * loop */
8074 if (lexer.peek_token ()->get_id () != LET)
8075 {
8076 Error error (lexer.peek_token ()->get_locus (),
8077 "appears to be a while loop but is being parsed by "
8078 "while let loop - this may be a compiler issue");
8079 add_error (std::move (error));
8080
8081 // skip somewhere
8082 return nullptr;
8083 }
8084 // as this token is definitely let now, save the computation of comparison
8085 lexer.skip_token ();
8086
8087 // parse predicate patterns
8088 std::vector<std::unique_ptr<AST::Pattern>> predicate_patterns
8089 = parse_match_arm_patterns (EQUAL);
8090 // TODO: have to ensure that there is at least 1 pattern?
8091
8092 if (!skip_token (EQUAL))
8093 {
8094 // skip somewhere?
8095 return nullptr;
8096 }
8097
8098 /* parse predicate expression, which is required (and HACK to prevent struct
8099 * expr) */
8100 ParseRestrictions no_struct_expr;
8101 no_struct_expr.can_be_struct_expr = false;
8102 std::unique_ptr<AST::Expr> predicate_expr = parse_expr ({}, no_struct_expr);
8103 if (predicate_expr == nullptr)
8104 {
8105 Error error (lexer.peek_token ()->get_locus (),
8106 "failed to parse predicate expression in while let loop");
8107 add_error (std::move (error));
8108
8109 // skip somewhere?
8110 return nullptr;
8111 }
8112 /* TODO: ensure that struct expression is not parsed? Actually, probably in
8113 * semantic analysis. */
8114
8115 // parse loop body, which is required
8116 std::unique_ptr<AST::BlockExpr> body = parse_block_expr ();
8117 if (body == nullptr)
8118 {
8119 Error error (lexer.peek_token ()->get_locus (),
8120 "failed to parse block expr (loop body) of while let loop");
8121 add_error (std::move (error));
8122
8123 // skip somewhere?
8124 return nullptr;
8125 }
8126
8127 return std::unique_ptr<AST::WhileLetLoopExpr> (new AST::WhileLetLoopExpr (
8128 std::move (predicate_patterns), std::move (predicate_expr),
8129 std::move (body), locus, std::move (label), std::move (outer_attrs)));
8130 }
8131
8132 /* Parses a "for" iterative loop. Label is not parsed and should be parsed via
8133 * parse_labelled_loop_expr, which would call this. */
8134 template <typename ManagedTokenSource>
8135 std::unique_ptr<AST::ForLoopExpr>
8136 Parser<ManagedTokenSource>::parse_for_loop_expr (
8137 AST::AttrVec outer_attrs, tl::optional<AST::LoopLabel> label)
8138 {
8139 location_t locus = UNKNOWN_LOCATION;
8140 if (label)
8141 locus = label->get_locus ();
8142 else
8143 locus = lexer.peek_token ()->get_locus ();
8144 maybe_skip_token (FOR);
8145
8146 // parse pattern, which is required
8147 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
8148 if (pattern == nullptr)
8149 {
8150 Error error (lexer.peek_token ()->get_locus (),
8151 "failed to parse iterator pattern in for loop");
8152 add_error (std::move (error));
8153
8154 // skip somewhere?
8155 return nullptr;
8156 }
8157
8158 if (!skip_token (IN))
8159 {
8160 // skip somewhere?
8161 return nullptr;
8162 }
8163
8164 /* parse iterator expression, which is required - also HACK to prevent
8165 * struct expr */
8166 ParseRestrictions no_struct_expr;
8167 no_struct_expr.can_be_struct_expr = false;
8168 std::unique_ptr<AST::Expr> expr = parse_expr ({}, no_struct_expr);
8169 if (expr == nullptr)
8170 {
8171 Error error (lexer.peek_token ()->get_locus (),
8172 "failed to parse iterator expression in for loop");
8173 add_error (std::move (error));
8174
8175 // skip somewhere?
8176 return nullptr;
8177 }
8178 // TODO: check to ensure this isn't struct expr? Or in semantic analysis.
8179
8180 // parse loop body, which is required
8181 std::unique_ptr<AST::BlockExpr> body = parse_block_expr ();
8182 if (body == nullptr)
8183 {
8184 Error error (lexer.peek_token ()->get_locus (),
8185 "failed to parse loop body block expression in for loop");
8186 add_error (std::move (error));
8187
8188 // skip somewhere?
8189 return nullptr;
8190 }
8191
8192 return std::unique_ptr<AST::ForLoopExpr> (
8193 new AST::ForLoopExpr (std::move (pattern), std::move (expr),
8194 std::move (body), locus, std::move (label),
8195 std::move (outer_attrs)));
8196 }
8197
8198 // Parses a loop expression with label (any kind of loop - disambiguates).
8199 template <typename ManagedTokenSource>
8200 std::unique_ptr<AST::Expr>
8201 Parser<ManagedTokenSource>::parse_labelled_loop_expr (const_TokenPtr tok,
8202 AST::AttrVec outer_attrs)
8203 {
8204 /* TODO: decide whether it should not work if there is no label, or parse it
8205 * with no label at the moment, I will make it not work with no label
8206 * because that's the implication. */
8207
8208 if (tok->get_id () != LIFETIME)
8209 {
8210 Error error (tok->get_locus (),
8211 "expected lifetime in labelled loop expr (to parse loop "
8212 "label) - found %qs",
8213 tok->get_token_description ());
8214 add_error (std::move (error));
8215
8216 // skip?
8217 return nullptr;
8218 }
8219
8220 // parse loop label (required)
8221 // TODO: Convert this return type to tl::expected instead of tl::optional
8222 auto parsed_label = parse_loop_label (tok);
8223 if (!parsed_label)
8224 {
8225 Error error (lexer.peek_token ()->get_locus (),
8226 "failed to parse loop label in labelled loop expr");
8227 add_error (std::move (error));
8228
8229 // skip?
8230 return nullptr;
8231 }
8232
8233 auto label = parsed_label
8234 ? tl::optional<AST::LoopLabel> (parsed_label.value ())
8235 : tl::nullopt;
8236
8237 // branch on next token
8238 const_TokenPtr t = lexer.peek_token ();
8239 switch (t->get_id ())
8240 {
8241 case LOOP:
8242 return parse_loop_expr (std::move (outer_attrs), std::move (label));
8243 case FOR:
8244 return parse_for_loop_expr (std::move (outer_attrs), std::move (label));
8245 case WHILE:
8246 // further disambiguate into while vs while let
8247 if (lexer.peek_token (1)->get_id () == LET)
8248 {
8249 return parse_while_let_loop_expr (std::move (outer_attrs),
8250 std::move (label));
8251 }
8252 else
8253 {
8254 return parse_while_loop_expr (std::move (outer_attrs),
8255 std::move (label));
8256 }
8257 case LEFT_CURLY:
8258 return parse_block_expr (std::move (outer_attrs), std::move (label));
8259 default:
8260 // error
8261 add_error (Error (t->get_locus (),
8262 "unexpected token %qs when parsing labelled loop",
8263 t->get_token_description ()));
8264
8265 // skip?
8266 return nullptr;
8267 }
8268 }
8269
8270 // Parses a match expression.
8271 template <typename ManagedTokenSource>
8272 std::unique_ptr<AST::MatchExpr>
8273 Parser<ManagedTokenSource>::parse_match_expr (AST::AttrVec outer_attrs,
8274 location_t pratt_parsed_loc)
8275 {
8276 location_t locus = pratt_parsed_loc;
8277 if (locus == UNKNOWN_LOCATION)
8278 {
8279 locus = lexer.peek_token ()->get_locus ();
8280 skip_token (MATCH_KW);
8281 }
8282
8283 /* parse scrutinee expression, which is required (and HACK to prevent struct
8284 * expr) */
8285 ParseRestrictions no_struct_expr;
8286 no_struct_expr.can_be_struct_expr = false;
8287 std::unique_ptr<AST::Expr> scrutinee = parse_expr ({}, no_struct_expr);
8288 if (scrutinee == nullptr)
8289 {
8290 Error error (lexer.peek_token ()->get_locus (),
8291 "failed to parse scrutinee expression in match expression");
8292 add_error (std::move (error));
8293
8294 // skip somewhere?
8295 return nullptr;
8296 }
8297 /* TODO: check for scrutinee expr not being struct expr? or do so in
8298 * semantic analysis */
8299
8300 if (!skip_token (LEFT_CURLY))
8301 {
8302 // skip somewhere?
8303 return nullptr;
8304 }
8305
8306 // parse inner attributes (if they exist)
8307 AST::AttrVec inner_attrs = parse_inner_attributes ();
8308
8309 // parse match arms (if they exist)
8310 // std::vector<std::unique_ptr<AST::MatchCase> > match_arms;
8311 std::vector<AST::MatchCase> match_arms;
8312
8313 // parse match cases
8314 while (lexer.peek_token ()->get_id () != RIGHT_CURLY)
8315 {
8316 // parse match arm itself, which is required
8317 AST::MatchArm arm = parse_match_arm ();
8318 if (arm.is_error ())
8319 {
8320 // TODO is this worth throwing everything away?
8321 Error error (lexer.peek_token ()->get_locus (),
8322 "failed to parse match arm in match arms");
8323 add_error (std::move (error));
8324
8325 return nullptr;
8326 }
8327
8328 if (!skip_token (MATCH_ARROW))
8329 {
8330 // skip after somewhere?
8331 // TODO is returning here a good idea? or is break better?
8332 return nullptr;
8333 }
8334
8335 ParseRestrictions restrictions;
8336 restrictions.expr_can_be_stmt = true;
8337
8338 std::unique_ptr<AST::Expr> expr = parse_expr ({}, restrictions);
8339
8340 if (expr == nullptr)
8341 {
8342 Error error (lexer.peek_token ()->get_locus (),
8343 "failed to parse expr in match arm in match expr");
8344 add_error (std::move (error));
8345
8346 // skip somewhere?
8347 return nullptr;
8348 }
8349
8350 bool is_expr_without_block = expr->is_expr_without_block ();
8351
8352 match_arms.push_back (AST::MatchCase (std::move (arm), std::move (expr)));
8353
8354 // handle comma presence
8355 if (lexer.peek_token ()->get_id () != COMMA)
8356 {
8357 if (!is_expr_without_block)
8358 {
8359 // allowed even if not final case
8360 continue;
8361 }
8362 else if (is_expr_without_block
8363 && lexer.peek_token ()->get_id () != RIGHT_CURLY)
8364 {
8365 // not allowed if not final case
8366 Error error (lexer.peek_token ()->get_locus (),
8367 "exprwithoutblock requires comma after match case "
8368 "expression in match arm (if not final case)");
8369 add_error (std::move (error));
8370
8371 return nullptr;
8372 }
8373 else
8374 {
8375 // otherwise, must be final case, so fine
8376 break;
8377 }
8378 }
8379 lexer.skip_token ();
8380 }
8381
8382 if (!skip_token (RIGHT_CURLY))
8383 {
8384 // skip somewhere?
8385 return nullptr;
8386 }
8387
8388 match_arms.shrink_to_fit ();
8389
8390 return std::unique_ptr<AST::MatchExpr> (
8391 new AST::MatchExpr (std::move (scrutinee), std::move (match_arms),
8392 std::move (inner_attrs), std::move (outer_attrs),
8393 locus));
8394 }
8395
8396 // Parses the "pattern" part of the match arm (the 'case x:' equivalent).
8397 template <typename ManagedTokenSource>
8398 AST::MatchArm
8399 Parser<ManagedTokenSource>::parse_match_arm ()
8400 {
8401 // parse optional outer attributes
8402 AST::AttrVec outer_attrs = parse_outer_attributes ();
8403
8404 // DEBUG
8405 rust_debug ("about to start parsing match arm patterns");
8406
8407 // break early if find right curly
8408 if (lexer.peek_token ()->get_id () == RIGHT_CURLY)
8409 {
8410 // not an error
8411 return AST::MatchArm::create_error ();
8412 }
8413
8414 // parse match arm patterns - at least 1 is required
8415 std::vector<std::unique_ptr<AST::Pattern>> match_arm_patterns
8416 = parse_match_arm_patterns (RIGHT_CURLY);
8417 if (match_arm_patterns.empty ())
8418 {
8419 Error error (lexer.peek_token ()->get_locus (),
8420 "failed to parse any patterns in match arm");
8421 add_error (std::move (error));
8422
8423 // skip somewhere?
8424 return AST::MatchArm::create_error ();
8425 }
8426
8427 // DEBUG
8428 rust_debug ("successfully parsed match arm patterns");
8429
8430 // parse match arm guard expr if it exists
8431 std::unique_ptr<AST::Expr> guard_expr = nullptr;
8432 if (lexer.peek_token ()->get_id () == IF)
8433 {
8434 lexer.skip_token ();
8435
8436 guard_expr = parse_expr ();
8437 if (guard_expr == nullptr)
8438 {
8439 Error error (lexer.peek_token ()->get_locus (),
8440 "failed to parse guard expression in match arm");
8441 add_error (std::move (error));
8442
8443 // skip somewhere?
8444 return AST::MatchArm::create_error ();
8445 }
8446 }
8447
8448 // DEBUG
8449 rust_debug ("successfully parsed match arm");
8450
8451 return AST::MatchArm (std::move (match_arm_patterns),
8452 lexer.peek_token ()->get_locus (),
8453 std::move (guard_expr), std::move (outer_attrs));
8454 }
8455
8456 /* Parses the patterns used in a match arm. End token id is the id of the
8457 * token that would exist after the patterns are done (e.g. '}' for match
8458 * expr, '=' for if let and while let). */
8459 template <typename ManagedTokenSource>
8460 std::vector<std::unique_ptr<AST::Pattern>>
8461 Parser<ManagedTokenSource>::parse_match_arm_patterns (TokenId end_token_id)
8462 {
8463 // skip optional leading '|'
8464 if (lexer.peek_token ()->get_id () == PIPE)
8465 lexer.skip_token ();
8466 /* TODO: do I even need to store the result of this? can't be used.
8467 * If semantically different, I need a wrapped "match arm patterns" object
8468 * for this. */
8469
8470 std::vector<std::unique_ptr<AST::Pattern>> patterns;
8471
8472 // quick break out if end_token_id
8473 if (lexer.peek_token ()->get_id () == end_token_id)
8474 return patterns;
8475
8476 // parse required pattern - if doesn't exist, return empty
8477 std::unique_ptr<AST::Pattern> initial_pattern = parse_pattern ();
8478 if (initial_pattern == nullptr)
8479 {
8480 // FIXME: should this be an error?
8481 return patterns;
8482 }
8483 patterns.push_back (std::move (initial_pattern));
8484
8485 // DEBUG
8486 rust_debug ("successfully parsed initial match arm pattern");
8487
8488 // parse new patterns as long as next char is '|'
8489 const_TokenPtr t = lexer.peek_token ();
8490 while (t->get_id () == PIPE)
8491 {
8492 // skip pipe token
8493 lexer.skip_token ();
8494
8495 // break if hit end token id
8496 if (lexer.peek_token ()->get_id () == end_token_id)
8497 break;
8498
8499 // parse pattern
8500 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
8501 if (pattern == nullptr)
8502 {
8503 // this is an error
8504 Error error (lexer.peek_token ()->get_locus (),
8505 "failed to parse pattern in match arm patterns");
8506 add_error (std::move (error));
8507
8508 // skip somewhere?
8509 return {};
8510 }
8511
8512 patterns.push_back (std::move (pattern));
8513
8514 t = lexer.peek_token ();
8515 }
8516
8517 patterns.shrink_to_fit ();
8518
8519 return patterns;
8520 }
8521
8522 // Parses an async block expression.
8523 template <typename ManagedTokenSource>
8524 std::unique_ptr<AST::AsyncBlockExpr>
8525 Parser<ManagedTokenSource>::parse_async_block_expr (AST::AttrVec outer_attrs)
8526 {
8527 location_t locus = lexer.peek_token ()->get_locus ();
8528 skip_token (ASYNC);
8529
8530 // detect optional move token
8531 bool has_move = false;
8532 if (lexer.peek_token ()->get_id () == MOVE)
8533 {
8534 lexer.skip_token ();
8535 has_move = true;
8536 }
8537
8538 // parse block expression (required)
8539 std::unique_ptr<AST::BlockExpr> block_expr = parse_block_expr ();
8540 if (block_expr == nullptr)
8541 {
8542 Error error (
8543 lexer.peek_token ()->get_locus (),
8544 "failed to parse block expression of async block expression");
8545 add_error (std::move (error));
8546
8547 // skip somewhere?
8548 return nullptr;
8549 }
8550
8551 return std::unique_ptr<AST::AsyncBlockExpr> (
8552 new AST::AsyncBlockExpr (std::move (block_expr), has_move,
8553 std::move (outer_attrs), locus));
8554 }
8555
8556 // Parses an unsafe block expression.
8557 template <typename ManagedTokenSource>
8558 std::unique_ptr<AST::UnsafeBlockExpr>
8559 Parser<ManagedTokenSource>::parse_unsafe_block_expr (
8560 AST::AttrVec outer_attrs, location_t pratt_parsed_loc)
8561 {
8562 location_t locus = pratt_parsed_loc;
8563 if (locus == UNKNOWN_LOCATION)
8564 {
8565 locus = lexer.peek_token ()->get_locus ();
8566 skip_token (UNSAFE);
8567 }
8568
8569 // parse block expression (required)
8570 std::unique_ptr<AST::BlockExpr> block_expr = parse_block_expr ();
8571 if (block_expr == nullptr)
8572 {
8573 Error error (
8574 lexer.peek_token ()->get_locus (),
8575 "failed to parse block expression of unsafe block expression");
8576 add_error (std::move (error));
8577
8578 // skip somewhere?
8579 return nullptr;
8580 }
8581
8582 return std::unique_ptr<AST::UnsafeBlockExpr> (
8583 new AST::UnsafeBlockExpr (std::move (block_expr), std::move (outer_attrs),
8584 locus));
8585 }
8586
8587 // Parses an array definition expression.
8588 template <typename ManagedTokenSource>
8589 std::unique_ptr<AST::ArrayExpr>
8590 Parser<ManagedTokenSource>::parse_array_expr (AST::AttrVec outer_attrs,
8591 location_t pratt_parsed_loc)
8592 {
8593 location_t locus = pratt_parsed_loc;
8594 if (locus == UNKNOWN_LOCATION)
8595 {
8596 locus = lexer.peek_token ()->get_locus ();
8597 skip_token (LEFT_SQUARE);
8598 }
8599
8600 // parse optional inner attributes
8601 AST::AttrVec inner_attrs = parse_inner_attributes ();
8602
8603 // parse the "array elements" section, which is optional
8604 if (lexer.peek_token ()->get_id () == RIGHT_SQUARE)
8605 {
8606 // no array elements
8607 lexer.skip_token ();
8608
8609 std::vector<std::unique_ptr<AST::Expr>> exprs;
8610 auto array_elems
8611 = std::make_unique<AST::ArrayElemsValues> (std::move (exprs), locus);
8612 return std::make_unique<AST::ArrayExpr> (std::move (array_elems),
8613 std::move (inner_attrs),
8614 std::move (outer_attrs), locus);
8615 }
8616 else
8617 {
8618 // should have array elements
8619 // parse initial expression, which is required for either
8620 std::unique_ptr<AST::Expr> initial_expr = parse_expr ();
8621 if (initial_expr == nullptr)
8622 {
8623 Error error (lexer.peek_token ()->get_locus (),
8624 "could not parse expression in array expression "
8625 "(even though arrayelems seems to be present)");
8626 add_error (std::move (error));
8627
8628 // skip somewhere?
8629 return nullptr;
8630 }
8631
8632 if (lexer.peek_token ()->get_id () == SEMICOLON)
8633 {
8634 // copy array elems
8635 lexer.skip_token ();
8636
8637 // parse copy amount expression (required)
8638 std::unique_ptr<AST::Expr> copy_amount = parse_expr ();
8639 if (copy_amount == nullptr)
8640 {
8641 Error error (lexer.peek_token ()->get_locus (),
8642 "could not parse copy amount expression in array "
8643 "expression (arrayelems)");
8644 add_error (std::move (error));
8645
8646 // skip somewhere?
8647 return nullptr;
8648 }
8649
8650 skip_token (RIGHT_SQUARE);
8651
8652 std::unique_ptr<AST::ArrayElemsCopied> copied_array_elems (
8653 new AST::ArrayElemsCopied (std::move (initial_expr),
8654 std::move (copy_amount), locus));
8655 return std::unique_ptr<AST::ArrayExpr> (
8656 new AST::ArrayExpr (std::move (copied_array_elems),
8657 std::move (inner_attrs),
8658 std::move (outer_attrs), locus));
8659 }
8660 else if (lexer.peek_token ()->get_id () == RIGHT_SQUARE)
8661 {
8662 // single-element array expression
8663 std::vector<std::unique_ptr<AST::Expr>> exprs;
8664 exprs.reserve (1);
8665 exprs.push_back (std::move (initial_expr));
8666 exprs.shrink_to_fit ();
8667
8668 skip_token (RIGHT_SQUARE);
8669
8670 std::unique_ptr<AST::ArrayElemsValues> array_elems (
8671 new AST::ArrayElemsValues (std::move (exprs), locus));
8672 return std::unique_ptr<AST::ArrayExpr> (
8673 new AST::ArrayExpr (std::move (array_elems),
8674 std::move (inner_attrs),
8675 std::move (outer_attrs), locus));
8676 }
8677 else if (lexer.peek_token ()->get_id () == COMMA)
8678 {
8679 // multi-element array expression (or trailing comma)
8680 std::vector<std::unique_ptr<AST::Expr>> exprs;
8681 exprs.push_back (std::move (initial_expr));
8682
8683 const_TokenPtr t = lexer.peek_token ();
8684 while (t->get_id () == COMMA)
8685 {
8686 lexer.skip_token ();
8687
8688 // quick break if right square bracket
8689 if (lexer.peek_token ()->get_id () == RIGHT_SQUARE)
8690 break;
8691
8692 // parse expression (required)
8693 std::unique_ptr<AST::Expr> expr = parse_expr ();
8694 if (expr == nullptr)
8695 {
8696 Error error (lexer.peek_token ()->get_locus (),
8697 "failed to parse element in array expression");
8698 add_error (std::move (error));
8699
8700 // skip somewhere?
8701 return nullptr;
8702 }
8703 exprs.push_back (std::move (expr));
8704
8705 t = lexer.peek_token ();
8706 }
8707
8708 skip_token (RIGHT_SQUARE);
8709
8710 exprs.shrink_to_fit ();
8711
8712 std::unique_ptr<AST::ArrayElemsValues> array_elems (
8713 new AST::ArrayElemsValues (std::move (exprs), locus));
8714 return std::unique_ptr<AST::ArrayExpr> (
8715 new AST::ArrayExpr (std::move (array_elems),
8716 std::move (inner_attrs),
8717 std::move (outer_attrs), locus));
8718 }
8719 else
8720 {
8721 // error
8722 Error error (lexer.peek_token ()->get_locus (),
8723 "unexpected token %qs in array expression (arrayelems)",
8724 lexer.peek_token ()->get_token_description ());
8725 add_error (std::move (error));
8726
8727 // skip somewhere?
8728 return nullptr;
8729 }
8730 }
8731 }
8732
8733 // Parses a single parameter used in a closure definition.
8734 template <typename ManagedTokenSource>
8735 AST::ClosureParam
8736 Parser<ManagedTokenSource>::parse_closure_param ()
8737 {
8738 AST::AttrVec outer_attrs = parse_outer_attributes ();
8739
8740 // parse pattern (which is required)
8741 std::unique_ptr<AST::Pattern> pattern = parse_pattern_no_alt ();
8742 if (pattern == nullptr)
8743 {
8744 // not necessarily an error
8745 return AST::ClosureParam::create_error ();
8746 }
8747
8748 // parse optional type of param
8749 std::unique_ptr<AST::Type> type = nullptr;
8750 if (lexer.peek_token ()->get_id () == COLON)
8751 {
8752 lexer.skip_token ();
8753
8754 // parse type, which is now required
8755 type = parse_type ();
8756 if (type == nullptr)
8757 {
8758 Error error (lexer.peek_token ()->get_locus (),
8759 "failed to parse type in closure parameter");
8760 add_error (std::move (error));
8761
8762 // skip somewhere?
8763 return AST::ClosureParam::create_error ();
8764 }
8765 }
8766
8767 location_t loc = pattern->get_locus ();
8768 return AST::ClosureParam (std::move (pattern), loc, std::move (type),
8769 std::move (outer_attrs));
8770 }
8771
8772 // Parses a grouped or tuple expression (disambiguates).
8773 template <typename ManagedTokenSource>
8774 std::unique_ptr<AST::ExprWithoutBlock>
8775 Parser<ManagedTokenSource>::parse_grouped_or_tuple_expr (
8776 AST::AttrVec outer_attrs, location_t pratt_parsed_loc)
8777 {
8778 // adjustment to allow Pratt parsing to reuse function without copy-paste
8779 location_t locus = pratt_parsed_loc;
8780 if (locus == UNKNOWN_LOCATION)
8781 {
8782 locus = lexer.peek_token ()->get_locus ();
8783 skip_token (LEFT_PAREN);
8784 }
8785
8786 // parse optional inner attributes
8787 AST::AttrVec inner_attrs = parse_inner_attributes ();
8788
8789 if (lexer.peek_token ()->get_id () == RIGHT_PAREN)
8790 {
8791 // must be empty tuple
8792 lexer.skip_token ();
8793
8794 // create tuple with empty tuple elems
8795 return std::unique_ptr<AST::TupleExpr> (
8796 new AST::TupleExpr (std::vector<std::unique_ptr<AST::Expr>> (),
8797 std::move (inner_attrs), std::move (outer_attrs),
8798 locus));
8799 }
8800
8801 // parse first expression (required)
8802 std::unique_ptr<AST::Expr> first_expr = parse_expr ();
8803 if (first_expr == nullptr)
8804 {
8805 Error error (lexer.peek_token ()->get_locus (),
8806 "failed to parse expression in grouped or tuple expression");
8807 add_error (std::move (error));
8808
8809 // skip after somewhere?
8810 return nullptr;
8811 }
8812
8813 // detect whether grouped expression with right parentheses as next token
8814 if (lexer.peek_token ()->get_id () == RIGHT_PAREN)
8815 {
8816 // must be grouped expr
8817 lexer.skip_token ();
8818
8819 // create grouped expr
8820 return std::unique_ptr<AST::GroupedExpr> (
8821 new AST::GroupedExpr (std::move (first_expr), std::move (inner_attrs),
8822 std::move (outer_attrs), locus));
8823 }
8824 else if (lexer.peek_token ()->get_id () == COMMA)
8825 {
8826 // tuple expr
8827 std::vector<std::unique_ptr<AST::Expr>> exprs;
8828 exprs.push_back (std::move (first_expr));
8829
8830 // parse potential other tuple exprs
8831 const_TokenPtr t = lexer.peek_token ();
8832 while (t->get_id () == COMMA)
8833 {
8834 lexer.skip_token ();
8835
8836 // break out if right paren
8837 if (lexer.peek_token ()->get_id () == RIGHT_PAREN)
8838 break;
8839
8840 // parse expr, which is now required
8841 std::unique_ptr<AST::Expr> expr = parse_expr ();
8842 if (expr == nullptr)
8843 {
8844 Error error (lexer.peek_token ()->get_locus (),
8845 "failed to parse expr in tuple expr");
8846 add_error (std::move (error));
8847
8848 // skip somewhere?
8849 return nullptr;
8850 }
8851 exprs.push_back (std::move (expr));
8852
8853 t = lexer.peek_token ();
8854 }
8855
8856 // skip right paren
8857 skip_token (RIGHT_PAREN);
8858
8859 return std::unique_ptr<AST::TupleExpr> (
8860 new AST::TupleExpr (std::move (exprs), std::move (inner_attrs),
8861 std::move (outer_attrs), locus));
8862 }
8863 else
8864 {
8865 // error
8866 const_TokenPtr t = lexer.peek_token ();
8867 Error error (t->get_locus (),
8868 "unexpected token %qs in grouped or tuple expression "
8869 "(parenthesised expression) - expected %<)%> for grouped "
8870 "expr and %<,%> for tuple expr",
8871 t->get_token_description ());
8872 add_error (std::move (error));
8873
8874 // skip somewhere?
8875 return nullptr;
8876 }
8877 }
8878
8879 // Parses a type (will further disambiguate any type).
8880 template <typename ManagedTokenSource>
8881 std::unique_ptr<AST::Type>
8882 Parser<ManagedTokenSource>::parse_type (bool save_errors)
8883 {
8884 /* rules for all types:
8885 * NeverType: '!'
8886 * SliceType: '[' Type ']'
8887 * InferredType: '_'
8888 * MacroInvocation: SimplePath '!' DelimTokenTree
8889 * ParenthesisedType: '(' Type ')'
8890 * ImplTraitType: 'impl' TypeParamBounds
8891 * TypeParamBounds (not type) TypeParamBound ( '+' TypeParamBound )* '+'?
8892 * TypeParamBound Lifetime | TraitBound
8893 * ImplTraitTypeOneBound: 'impl' TraitBound
8894 * TraitObjectType: 'dyn'? TypeParamBounds
8895 * TraitObjectTypeOneBound: 'dyn'? TraitBound
8896 * TraitBound '?'? ForLifetimes? TypePath | '(' '?'?
8897 * ForLifetimes? TypePath ')' BareFunctionType: ForLifetimes?
8898 * FunctionQualifiers 'fn' etc. ForLifetimes (not type) 'for' '<'
8899 * LifetimeParams '>' FunctionQualifiers ( 'async' | 'const' )?
8900 * 'unsafe'?
8901 * ('extern' abi?)? QualifiedPathInType: '<' Type ( 'as' TypePath )? '>'
8902 * (
8903 * '::' TypePathSegment )+ TypePath: '::'? TypePathSegment (
8904 * '::' TypePathSegment)* ArrayType: '[' Type ';' Expr ']'
8905 * ReferenceType: '&' Lifetime? 'mut'? TypeNoBounds
8906 * RawPointerType: '*' ( 'mut' | 'const' ) TypeNoBounds
8907 * TupleType: '(' Type etc. - regular tuple stuff. Also
8908 * regular tuple vs parenthesised precedence
8909 *
8910 * Disambiguate between macro and type path via type path being parsed, and
8911 * then if '!' found, convert type path to simple path for macro. Usual
8912 * disambiguation for tuple vs parenthesised. For ImplTraitType and
8913 * TraitObjectType individual disambiguations, they seem more like "special
8914 * cases", so probably just try to parse the more general ImplTraitType or
8915 * TraitObjectType and return OneBound versions if they satisfy those
8916 * criteria. */
8917
8918 const_TokenPtr t = lexer.peek_token ();
8919 switch (t->get_id ())
8920 {
8921 case EXCLAM:
8922 // never type - can't be macro as no path beforehand
8923 lexer.skip_token ();
8924 return std::unique_ptr<AST::NeverType> (
8925 new AST::NeverType (t->get_locus ()));
8926 case LEFT_SQUARE:
8927 // slice type or array type - requires further disambiguation
8928 return parse_slice_or_array_type ();
8929 case LEFT_SHIFT:
8930 case LEFT_ANGLE: {
8931 // qualified path in type
8932 AST::QualifiedPathInType path = parse_qualified_path_in_type ();
8933 if (path.is_error ())
8934 {
8935 if (save_errors)
8936 {
8937 Error error (t->get_locus (),
8938 "failed to parse qualified path in type");
8939 add_error (std::move (error));
8940 }
8941
8942 return nullptr;
8943 }
8944 return std::unique_ptr<AST::QualifiedPathInType> (
8945 new AST::QualifiedPathInType (std::move (path)));
8946 }
8947 case UNDERSCORE:
8948 // inferred type
8949 lexer.skip_token ();
8950 return std::unique_ptr<AST::InferredType> (
8951 new AST::InferredType (t->get_locus ()));
8952 case ASTERISK:
8953 // raw pointer type
8954 return parse_raw_pointer_type ();
8955 case AMP: // does this also include AMP_AMP?
8956 case LOGICAL_AND:
8957 // reference type
8958 return parse_reference_type ();
8959 case LIFETIME: {
8960 /* probably a lifetime bound, so probably type param bounds in
8961 * TraitObjectType */
8962 std::vector<std::unique_ptr<AST::TypeParamBound>> bounds
8963 = parse_type_param_bounds ();
8964
8965 return std::unique_ptr<AST::TraitObjectType> (
8966 new AST::TraitObjectType (std::move (bounds), t->get_locus (),
8967 false));
8968 }
8969 case IDENTIFIER:
8970 case SUPER:
8971 case SELF:
8972 case SELF_ALIAS:
8973 case CRATE:
8974 case DOLLAR_SIGN:
8975 case SCOPE_RESOLUTION: {
8976 // macro invocation or type path - requires further disambiguation.
8977 /* for parsing path component of each rule, perhaps parse it as a
8978 * typepath and attempt conversion to simplepath if a trailing '!' is
8979 * found */
8980 /* Type path also includes TraitObjectTypeOneBound BUT if it starts
8981 * with it, it is exactly the same as a TypePath syntactically, so
8982 * this is a syntactical ambiguity. As such, the parser will parse it
8983 * as a TypePath. This, however, does not prevent TraitObjectType from
8984 * starting with a typepath. */
8985
8986 // parse path as type path
8987 AST::TypePath path = parse_type_path ();
8988 if (path.is_error ())
8989 {
8990 if (save_errors)
8991 {
8992 Error error (t->get_locus (),
8993 "failed to parse path as first component of type");
8994 add_error (std::move (error));
8995 }
8996
8997 return nullptr;
8998 }
8999 location_t locus = path.get_locus ();
9000
9001 // branch on next token
9002 t = lexer.peek_token ();
9003 switch (t->get_id ())
9004 {
9005 case EXCLAM: {
9006 // macro invocation
9007 // convert to simple path
9008 AST::SimplePath macro_path = path.as_simple_path ();
9009 if (macro_path.is_empty ())
9010 {
9011 if (save_errors)
9012 {
9013 Error error (t->get_locus (),
9014 "failed to parse simple path in macro "
9015 "invocation (for type)");
9016 add_error (std::move (error));
9017 }
9018
9019 return nullptr;
9020 }
9021
9022 lexer.skip_token ();
9023
9024 AST::DelimTokenTree tok_tree = parse_delim_token_tree ();
9025
9026 return AST::MacroInvocation::Regular (
9027 AST::MacroInvocData (std::move (macro_path),
9028 std::move (tok_tree)),
9029 {}, locus);
9030 }
9031 case PLUS: {
9032 // type param bounds
9033 std::vector<std::unique_ptr<AST::TypeParamBound>> bounds;
9034
9035 // convert type path to trait bound
9036 std::unique_ptr<AST::TraitBound> path_bound (
9037 new AST::TraitBound (std::move (path), locus, false, false));
9038 bounds.push_back (std::move (path_bound));
9039
9040 /* parse rest of bounds - FIXME: better way to find when to stop
9041 * parsing */
9042 while (t->get_id () == PLUS)
9043 {
9044 lexer.skip_token ();
9045
9046 // parse bound if it exists - if not, assume end of sequence
9047 std::unique_ptr<AST::TypeParamBound> bound
9048 = parse_type_param_bound ();
9049 if (bound == nullptr)
9050 {
9051 break;
9052 }
9053 bounds.push_back (std::move (bound));
9054
9055 t = lexer.peek_token ();
9056 }
9057
9058 return std::unique_ptr<AST::TraitObjectType> (
9059 new AST::TraitObjectType (std::move (bounds), locus, false));
9060 }
9061 default:
9062 // assume that this is a type path and not an error
9063 return std::unique_ptr<AST::TypePath> (
9064 new AST::TypePath (std::move (path)));
9065 }
9066 }
9067 case LEFT_PAREN:
9068 /* tuple type or parenthesised type - requires further disambiguation
9069 * (the usual). ok apparently can be a parenthesised TraitBound too, so
9070 * could be TraitObjectTypeOneBound or TraitObjectType */
9071 return parse_paren_prefixed_type ();
9072 case FOR:
9073 // TraitObjectTypeOneBound or BareFunctionType
9074 return parse_for_prefixed_type ();
9075 case ASYNC:
9076 case CONST:
9077 case UNSAFE:
9078 case EXTERN_KW:
9079 case FN_KW:
9080 // bare function type (with no for lifetimes)
9081 return parse_bare_function_type (std::vector<AST::LifetimeParam> ());
9082 case IMPL:
9083 lexer.skip_token ();
9084 if (lexer.peek_token ()->get_id () == LIFETIME)
9085 {
9086 /* cannot be one bound because lifetime prevents it from being
9087 * traitbound */
9088 std::vector<std::unique_ptr<AST::TypeParamBound>> bounds
9089 = parse_type_param_bounds ();
9090
9091 return std::unique_ptr<AST::ImplTraitType> (
9092 new AST::ImplTraitType (std::move (bounds), t->get_locus ()));
9093 }
9094 else
9095 {
9096 // should be trait bound, so parse trait bound
9097 std::unique_ptr<AST::TraitBound> initial_bound = parse_trait_bound ();
9098 if (initial_bound == nullptr)
9099 {
9100 if (save_errors)
9101 {
9102 Error error (lexer.peek_token ()->get_locus (),
9103 "failed to parse ImplTraitType initial bound");
9104 add_error (std::move (error));
9105 }
9106
9107 return nullptr;
9108 }
9109
9110 location_t locus = t->get_locus ();
9111
9112 // short cut if next token isn't '+'
9113 t = lexer.peek_token ();
9114 if (t->get_id () != PLUS)
9115 {
9116 // convert trait bound to value object
9117 AST::TraitBound value_bound (*initial_bound);
9118
9119 // DEBUG: removed as unique ptr, so should auto-delete
9120 // delete initial_bound;
9121
9122 return std::unique_ptr<AST::ImplTraitTypeOneBound> (
9123 new AST::ImplTraitTypeOneBound (std::move (value_bound),
9124 locus));
9125 }
9126
9127 // parse additional type param bounds
9128 std::vector<std::unique_ptr<AST::TypeParamBound>> bounds;
9129 bounds.push_back (std::move (initial_bound));
9130 while (t->get_id () == PLUS)
9131 {
9132 lexer.skip_token ();
9133
9134 // parse bound if it exists
9135 std::unique_ptr<AST::TypeParamBound> bound
9136 = parse_type_param_bound ();
9137 if (bound == nullptr)
9138 {
9139 // not an error as trailing plus may exist
9140 break;
9141 }
9142 bounds.push_back (std::move (bound));
9143
9144 t = lexer.peek_token ();
9145 }
9146
9147 return std::unique_ptr<AST::ImplTraitType> (
9148 new AST::ImplTraitType (std::move (bounds), locus));
9149 }
9150 case DYN:
9151 case QUESTION_MARK: {
9152 // either TraitObjectType or TraitObjectTypeOneBound
9153 bool has_dyn = false;
9154 if (t->get_id () == DYN)
9155 {
9156 lexer.skip_token ();
9157 has_dyn = true;
9158 }
9159
9160 if (lexer.peek_token ()->get_id () == LIFETIME)
9161 {
9162 /* cannot be one bound because lifetime prevents it from being
9163 * traitbound */
9164 std::vector<std::unique_ptr<AST::TypeParamBound>> bounds
9165 = parse_type_param_bounds ();
9166
9167 return std::unique_ptr<AST::TraitObjectType> (
9168 new AST::TraitObjectType (std::move (bounds), t->get_locus (),
9169 has_dyn));
9170 }
9171 else
9172 {
9173 // should be trait bound, so parse trait bound
9174 std::unique_ptr<AST::TraitBound> initial_bound
9175 = parse_trait_bound ();
9176 if (initial_bound == nullptr)
9177 {
9178 if (save_errors)
9179 {
9180 Error error (
9181 lexer.peek_token ()->get_locus (),
9182 "failed to parse TraitObjectType initial bound");
9183 add_error (std::move (error));
9184 }
9185
9186 return nullptr;
9187 }
9188
9189 // short cut if next token isn't '+'
9190 t = lexer.peek_token ();
9191 if (t->get_id () != PLUS)
9192 {
9193 // convert trait bound to value object
9194 AST::TraitBound value_bound (*initial_bound);
9195
9196 // DEBUG: removed as unique ptr, so should auto delete
9197 // delete initial_bound;
9198
9199 return std::unique_ptr<AST::TraitObjectTypeOneBound> (
9200 new AST::TraitObjectTypeOneBound (std::move (value_bound),
9201 t->get_locus (), has_dyn));
9202 }
9203
9204 // parse additional type param bounds
9205 std::vector<std::unique_ptr<AST::TypeParamBound>> bounds;
9206 bounds.push_back (std::move (initial_bound));
9207 while (t->get_id () == PLUS)
9208 {
9209 lexer.skip_token ();
9210
9211 // parse bound if it exists
9212 std::unique_ptr<AST::TypeParamBound> bound
9213 = parse_type_param_bound ();
9214 if (bound == nullptr)
9215 {
9216 // not an error as trailing plus may exist
9217 break;
9218 }
9219 bounds.push_back (std::move (bound));
9220
9221 t = lexer.peek_token ();
9222 }
9223
9224 return std::unique_ptr<AST::TraitObjectType> (
9225 new AST::TraitObjectType (std::move (bounds), t->get_locus (),
9226 has_dyn));
9227 }
9228 }
9229 default:
9230 if (save_errors)
9231 add_error (Error (t->get_locus (), "unrecognised token %qs in type",
9232 t->get_token_description ()));
9233
9234 return nullptr;
9235 }
9236 }
9237
9238 /* Parses a type that has '(' as its first character. Returns a tuple type,
9239 * parenthesised type, TraitObjectTypeOneBound, or TraitObjectType depending
9240 * on following characters. */
9241 template <typename ManagedTokenSource>
9242 std::unique_ptr<AST::Type>
9243 Parser<ManagedTokenSource>::parse_paren_prefixed_type ()
9244 {
9245 /* NOTE: Syntactical ambiguity of a parenthesised trait bound is considered
9246 * a trait bound, not a parenthesised type, so that it can still be used in
9247 * type param bounds. */
9248
9249 /* NOTE: this implementation is really shit but I couldn't think of a better
9250 * one. It requires essentially breaking polymorphism and downcasting via
9251 * virtual method abuse, as it was copied from the rustc implementation (in
9252 * which types are reified due to tagged union), after a more OOP attempt by
9253 * me failed. */
9254 location_t left_delim_locus = lexer.peek_token ()->get_locus ();
9255
9256 // skip left delim
9257 lexer.skip_token ();
9258 /* while next token isn't close delim, parse comma-separated types, saving
9259 * whether trailing comma happens */
9260 const_TokenPtr t = lexer.peek_token ();
9261 bool trailing_comma = true;
9262 std::vector<std::unique_ptr<AST::Type>> types;
9263
9264 while (t->get_id () != RIGHT_PAREN)
9265 {
9266 std::unique_ptr<AST::Type> type = parse_type ();
9267 if (type == nullptr)
9268 {
9269 Error error (t->get_locus (),
9270 "failed to parse type inside parentheses (probably "
9271 "tuple or parenthesised)");
9272 add_error (std::move (error));
9273
9274 return nullptr;
9275 }
9276 types.push_back (std::move (type));
9277
9278 t = lexer.peek_token ();
9279 if (t->get_id () != COMMA)
9280 {
9281 trailing_comma = false;
9282 break;
9283 }
9284 lexer.skip_token ();
9285
9286 t = lexer.peek_token ();
9287 }
9288
9289 if (!skip_token (RIGHT_PAREN))
9290 {
9291 return nullptr;
9292 }
9293
9294 // if only one type and no trailing comma, then not a tuple type
9295 if (types.size () == 1 && !trailing_comma)
9296 {
9297 // must be a TraitObjectType (with more than one bound)
9298 if (lexer.peek_token ()->get_id () == PLUS)
9299 {
9300 // create type param bounds vector
9301 std::vector<std::unique_ptr<AST::TypeParamBound>> bounds;
9302
9303 // HACK: convert type to traitbound and add to bounds
9304 std::unique_ptr<AST::Type> released_ptr = std::move (types[0]);
9305 std::unique_ptr<AST::TraitBound> converted_bound (
9306 released_ptr->to_trait_bound (true));
9307 if (converted_bound == nullptr)
9308 {
9309 Error error (
9310 lexer.peek_token ()->get_locus (),
9311 "failed to hackily converted parsed type to trait bound");
9312 add_error (std::move (error));
9313
9314 return nullptr;
9315 }
9316 bounds.push_back (std::move (converted_bound));
9317
9318 t = lexer.peek_token ();
9319 while (t->get_id () == PLUS)
9320 {
9321 lexer.skip_token ();
9322
9323 // attempt to parse typeparambound
9324 std::unique_ptr<AST::TypeParamBound> bound
9325 = parse_type_param_bound ();
9326 if (bound == nullptr)
9327 {
9328 // not an error if null
9329 break;
9330 }
9331 bounds.push_back (std::move (bound));
9332
9333 t = lexer.peek_token ();
9334 }
9335
9336 return std::unique_ptr<AST::TraitObjectType> (
9337 new AST::TraitObjectType (std::move (bounds), left_delim_locus,
9338 false));
9339 }
9340 else
9341 {
9342 // release vector pointer
9343 std::unique_ptr<AST::Type> released_ptr = std::move (types[0]);
9344 /* HACK: attempt to convert to trait bound. if fails, parenthesised
9345 * type */
9346 std::unique_ptr<AST::TraitBound> converted_bound (
9347 released_ptr->to_trait_bound (true));
9348 if (converted_bound == nullptr)
9349 {
9350 // parenthesised type
9351 return std::unique_ptr<AST::ParenthesisedType> (
9352 new AST::ParenthesisedType (std::move (released_ptr),
9353 left_delim_locus));
9354 }
9355 else
9356 {
9357 // trait object type (one bound)
9358
9359 // get value semantics trait bound
9360 AST::TraitBound value_bound (*converted_bound);
9361
9362 return std::unique_ptr<AST::TraitObjectTypeOneBound> (
9363 new AST::TraitObjectTypeOneBound (value_bound,
9364 left_delim_locus));
9365 }
9366 }
9367 }
9368 else
9369 {
9370 return std::unique_ptr<AST::TupleType> (
9371 new AST::TupleType (std::move (types), left_delim_locus));
9372 }
9373 /* TODO: ensure that this ensures that dynamic dispatch for traits is not
9374 * lost somehow */
9375 }
9376
9377 /* Parses a type that has 'for' as its first character. This means it has a
9378 * "for lifetimes", so returns either a BareFunctionType, TraitObjectType, or
9379 * TraitObjectTypeOneBound depending on following characters. */
9380 template <typename ManagedTokenSource>
9381 std::unique_ptr<AST::Type>
9382 Parser<ManagedTokenSource>::parse_for_prefixed_type ()
9383 {
9384 location_t for_locus = lexer.peek_token ()->get_locus ();
9385 // parse for lifetimes in type
9386 std::vector<AST::LifetimeParam> for_lifetimes = parse_for_lifetimes ();
9387
9388 // branch on next token - either function or a trait type
9389 const_TokenPtr t = lexer.peek_token ();
9390 switch (t->get_id ())
9391 {
9392 case ASYNC:
9393 case CONST:
9394 case UNSAFE:
9395 case EXTERN_KW:
9396 case FN_KW:
9397 return parse_bare_function_type (std::move (for_lifetimes));
9398 case SCOPE_RESOLUTION:
9399 case IDENTIFIER:
9400 case SUPER:
9401 case SELF:
9402 case SELF_ALIAS:
9403 case CRATE:
9404 case DOLLAR_SIGN: {
9405 // path, so trait type
9406
9407 // parse type path to finish parsing trait bound
9408 AST::TypePath path = parse_type_path ();
9409
9410 t = lexer.peek_token ();
9411 if (t->get_id () != PLUS)
9412 {
9413 // must be one-bound trait type
9414 // create trait bound value object
9415 AST::TraitBound bound (std::move (path), for_locus, false, false,
9416 std::move (for_lifetimes));
9417
9418 return std::unique_ptr<AST::TraitObjectTypeOneBound> (
9419 new AST::TraitObjectTypeOneBound (std::move (bound), for_locus));
9420 }
9421
9422 /* more than one bound trait type (or at least parsed as it - could be
9423 * trailing '+') create trait bound pointer and bounds */
9424 std::unique_ptr<AST::TraitBound> initial_bound (
9425 new AST::TraitBound (std::move (path), for_locus, false, false,
9426 std::move (for_lifetimes)));
9427 std::vector<std::unique_ptr<AST::TypeParamBound>> bounds;
9428 bounds.push_back (std::move (initial_bound));
9429
9430 while (t->get_id () == PLUS)
9431 {
9432 lexer.skip_token ();
9433
9434 // parse type param bound if it exists
9435 std::unique_ptr<AST::TypeParamBound> bound
9436 = parse_type_param_bound ();
9437 if (bound == nullptr)
9438 {
9439 // not an error - e.g. trailing plus
9440 return nullptr;
9441 }
9442 bounds.push_back (std::move (bound));
9443
9444 t = lexer.peek_token ();
9445 }
9446
9447 return std::unique_ptr<AST::TraitObjectType> (
9448 new AST::TraitObjectType (std::move (bounds), for_locus, false));
9449 }
9450 default:
9451 // error
9452 add_error (Error (t->get_locus (),
9453 "unrecognised token %qs in bare function type or trait "
9454 "object type or trait object type one bound",
9455 t->get_token_description ()));
9456
9457 return nullptr;
9458 }
9459 }
9460
9461 // Parses a maybe named param used in bare function types.
9462 template <typename ManagedTokenSource>
9463 AST::MaybeNamedParam
9464 Parser<ManagedTokenSource>::parse_maybe_named_param (AST::AttrVec outer_attrs)
9465 {
9466 /* Basically guess that param is named if first token is identifier or
9467 * underscore and second token is semicolon. This should probably have no
9468 * exceptions. rustc uses backtracking to parse these, but at the time of
9469 * writing gccrs has no backtracking capabilities. */
9470 const_TokenPtr current = lexer.peek_token ();
9471 const_TokenPtr next = lexer.peek_token (1);
9472
9473 Identifier name;
9474 AST::MaybeNamedParam::ParamKind kind = AST::MaybeNamedParam::UNNAMED;
9475
9476 if (current->get_id () == IDENTIFIER && next->get_id () == COLON)
9477 {
9478 // named param
9479 name = {current};
9480 kind = AST::MaybeNamedParam::IDENTIFIER;
9481 lexer.skip_token (1);
9482 }
9483 else if (current->get_id () == UNDERSCORE && next->get_id () == COLON)
9484 {
9485 // wildcard param
9486 name = {Values::Keywords::UNDERSCORE, current->get_locus ()};
9487 kind = AST::MaybeNamedParam::WILDCARD;
9488 lexer.skip_token (1);
9489 }
9490
9491 // parse type (required)
9492 std::unique_ptr<AST::Type> type = parse_type ();
9493 if (type == nullptr)
9494 {
9495 Error error (lexer.peek_token ()->get_locus (),
9496 "failed to parse type in maybe named param");
9497 add_error (std::move (error));
9498
9499 return AST::MaybeNamedParam::create_error ();
9500 }
9501
9502 return AST::MaybeNamedParam (std::move (name), kind, std::move (type),
9503 std::move (outer_attrs), current->get_locus ());
9504 }
9505
9506 /* Parses a bare function type (with the given for lifetimes for convenience -
9507 * does not parse them itself). */
9508 template <typename ManagedTokenSource>
9509 std::unique_ptr<AST::BareFunctionType>
9510 Parser<ManagedTokenSource>::parse_bare_function_type (
9511 std::vector<AST::LifetimeParam> for_lifetimes)
9512 {
9513 // TODO: pass in for lifetime location as param
9514 location_t best_try_locus = lexer.peek_token ()->get_locus ();
9515
9516 AST::FunctionQualifiers qualifiers = parse_function_qualifiers ();
9517
9518 if (!skip_token (FN_KW))
9519 return nullptr;
9520
9521 if (!skip_token (LEFT_PAREN))
9522 return nullptr;
9523
9524 // parse function params, if they exist
9525 std::vector<AST::MaybeNamedParam> params;
9526 bool is_variadic = false;
9527 AST::AttrVec variadic_attrs;
9528
9529 const_TokenPtr t = lexer.peek_token ();
9530 while (t->get_id () != RIGHT_PAREN)
9531 {
9532 AST::AttrVec temp_attrs = parse_outer_attributes ();
9533
9534 if (lexer.peek_token ()->get_id () == ELLIPSIS)
9535 {
9536 lexer.skip_token ();
9537 is_variadic = true;
9538 variadic_attrs = std::move (temp_attrs);
9539
9540 t = lexer.peek_token ();
9541
9542 if (t->get_id () != RIGHT_PAREN)
9543 {
9544 Error error (t->get_locus (),
9545 "expected right parentheses after variadic in maybe "
9546 "named function "
9547 "parameters, found %qs",
9548 t->get_token_description ());
9549 add_error (std::move (error));
9550
9551 return nullptr;
9552 }
9553
9554 break;
9555 }
9556
9557 AST::MaybeNamedParam param
9558 = parse_maybe_named_param (std::move (temp_attrs));
9559 if (param.is_error ())
9560 {
9561 Error error (
9562 lexer.peek_token ()->get_locus (),
9563 "failed to parse maybe named param in bare function type");
9564 add_error (std::move (error));
9565
9566 return nullptr;
9567 }
9568 params.push_back (std::move (param));
9569
9570 if (lexer.peek_token ()->get_id () != COMMA)
9571 break;
9572
9573 lexer.skip_token ();
9574 t = lexer.peek_token ();
9575 }
9576
9577 if (!skip_token (RIGHT_PAREN))
9578 return nullptr;
9579
9580 // bare function return type, if exists
9581 std::unique_ptr<AST::TypeNoBounds> return_type = nullptr;
9582 if (lexer.peek_token ()->get_id () == RETURN_TYPE)
9583 {
9584 lexer.skip_token ();
9585
9586 // parse required TypeNoBounds
9587 return_type = parse_type_no_bounds ();
9588 if (return_type == nullptr)
9589 {
9590 Error error (lexer.peek_token ()->get_locus (),
9591 "failed to parse return type (type no bounds) in bare "
9592 "function type");
9593 add_error (std::move (error));
9594
9595 return nullptr;
9596 }
9597 }
9598
9599 return std::unique_ptr<AST::BareFunctionType> (
9600 new AST::BareFunctionType (std::move (for_lifetimes),
9601 std::move (qualifiers), std::move (params),
9602 is_variadic, std::move (variadic_attrs),
9603 std::move (return_type), best_try_locus));
9604 }
9605
9606 template <typename ManagedTokenSource>
9607 std::unique_ptr<AST::ReferenceType>
9608 Parser<ManagedTokenSource>::parse_reference_type_inner (location_t locus)
9609 {
9610 // parse optional lifetime
9611 AST::Lifetime lifetime = AST::Lifetime::elided ();
9612 if (lexer.peek_token ()->get_id () == LIFETIME)
9613 {
9614 auto parsed_lifetime = parse_lifetime (true);
9615 if (parsed_lifetime)
9616 {
9617 lifetime = parsed_lifetime.value ();
9618 }
9619 else
9620 {
9621 Error error (lexer.peek_token ()->get_locus (),
9622 "failed to parse lifetime in reference type");
9623 add_error (std::move (error));
9624
9625 return nullptr;
9626 }
9627 }
9628
9629 bool is_mut = false;
9630 if (lexer.peek_token ()->get_id () == MUT)
9631 {
9632 lexer.skip_token ();
9633 is_mut = true;
9634 }
9635
9636 // parse type no bounds, which is required
9637 std::unique_ptr<AST::TypeNoBounds> type = parse_type_no_bounds ();
9638 if (type == nullptr)
9639 {
9640 Error error (lexer.peek_token ()->get_locus (),
9641 "failed to parse referenced type in reference type");
9642 add_error (std::move (error));
9643
9644 return nullptr;
9645 }
9646
9647 return std::unique_ptr<AST::ReferenceType> (
9648 new AST::ReferenceType (is_mut, std::move (type), locus,
9649 std::move (lifetime)));
9650 }
9651
9652 // Parses a reference type (mutable or immutable, with given lifetime).
9653 template <typename ManagedTokenSource>
9654 std::unique_ptr<AST::ReferenceType>
9655 Parser<ManagedTokenSource>::parse_reference_type ()
9656 {
9657 auto t = lexer.peek_token ();
9658 auto locus = t->get_locus ();
9659
9660 switch (t->get_id ())
9661 {
9662 case AMP:
9663 skip_token (AMP);
9664 return parse_reference_type_inner (locus);
9665 case LOGICAL_AND:
9666 skip_token (LOGICAL_AND);
9667 return std::unique_ptr<AST::ReferenceType> (
9668 new AST::ReferenceType (false, parse_reference_type_inner (locus),
9669 locus));
9670 default:
9671 rust_unreachable ();
9672 }
9673 }
9674
9675 // Parses a raw (unsafe) pointer type.
9676 template <typename ManagedTokenSource>
9677 std::unique_ptr<AST::RawPointerType>
9678 Parser<ManagedTokenSource>::parse_raw_pointer_type ()
9679 {
9680 location_t locus = lexer.peek_token ()->get_locus ();
9681 skip_token (ASTERISK);
9682
9683 AST::RawPointerType::PointerType kind = AST::RawPointerType::CONST;
9684
9685 // branch on next token for pointer kind info
9686 const_TokenPtr t = lexer.peek_token ();
9687 switch (t->get_id ())
9688 {
9689 case MUT:
9690 kind = AST::RawPointerType::MUT;
9691 lexer.skip_token ();
9692 break;
9693 case CONST:
9694 kind = AST::RawPointerType::CONST;
9695 lexer.skip_token ();
9696 break;
9697 default:
9698 add_error (Error (t->get_locus (),
9699 "unrecognised token %qs in raw pointer type",
9700 t->get_token_description ()));
9701
9702 return nullptr;
9703 }
9704
9705 // parse type no bounds (required)
9706 std::unique_ptr<AST::TypeNoBounds> type = parse_type_no_bounds ();
9707 if (type == nullptr)
9708 {
9709 Error error (lexer.peek_token ()->get_locus (),
9710 "failed to parse pointed type of raw pointer type");
9711 add_error (std::move (error));
9712
9713 return nullptr;
9714 }
9715
9716 return std::unique_ptr<AST::RawPointerType> (
9717 new AST::RawPointerType (kind, std::move (type), locus));
9718 }
9719
9720 /* Parses a slice or array type, depending on following arguments (as
9721 * lookahead is not possible). */
9722 template <typename ManagedTokenSource>
9723 std::unique_ptr<AST::TypeNoBounds>
9724 Parser<ManagedTokenSource>::parse_slice_or_array_type ()
9725 {
9726 location_t locus = lexer.peek_token ()->get_locus ();
9727 skip_token (LEFT_SQUARE);
9728
9729 // parse inner type (required)
9730 std::unique_ptr<AST::Type> inner_type = parse_type ();
9731 if (inner_type == nullptr)
9732 {
9733 Error error (lexer.peek_token ()->get_locus (),
9734 "failed to parse inner type in slice or array type");
9735 add_error (std::move (error));
9736
9737 return nullptr;
9738 }
9739
9740 // branch on next token
9741 const_TokenPtr t = lexer.peek_token ();
9742 switch (t->get_id ())
9743 {
9744 case RIGHT_SQUARE:
9745 // slice type
9746 lexer.skip_token ();
9747
9748 return std::unique_ptr<AST::SliceType> (
9749 new AST::SliceType (std::move (inner_type), locus));
9750 case SEMICOLON: {
9751 // array type
9752 lexer.skip_token ();
9753
9754 // parse required array size expression
9755 std::unique_ptr<AST::Expr> size = parse_expr ();
9756 if (size == nullptr)
9757 {
9758 Error error (lexer.peek_token ()->get_locus (),
9759 "failed to parse size expression in array type");
9760 add_error (std::move (error));
9761
9762 return nullptr;
9763 }
9764
9765 if (!skip_token (RIGHT_SQUARE))
9766 {
9767 return nullptr;
9768 }
9769
9770 return std::unique_ptr<AST::ArrayType> (
9771 new AST::ArrayType (std::move (inner_type), std::move (size), locus));
9772 }
9773 default:
9774 // error
9775 add_error (
9776 Error (t->get_locus (),
9777 "unrecognised token %qs in slice or array type after inner type",
9778 t->get_token_description ()));
9779
9780 return nullptr;
9781 }
9782 }
9783
9784 // Parses a type, taking into account type boundary disambiguation.
9785 template <typename ManagedTokenSource>
9786 std::unique_ptr<AST::TypeNoBounds>
9787 Parser<ManagedTokenSource>::parse_type_no_bounds ()
9788 {
9789 const_TokenPtr t = lexer.peek_token ();
9790 switch (t->get_id ())
9791 {
9792 case EXCLAM:
9793 // never type - can't be macro as no path beforehand
9794 lexer.skip_token ();
9795 return std::unique_ptr<AST::NeverType> (
9796 new AST::NeverType (t->get_locus ()));
9797 case LEFT_SQUARE:
9798 // slice type or array type - requires further disambiguation
9799 return parse_slice_or_array_type ();
9800 case LEFT_SHIFT:
9801 case LEFT_ANGLE: {
9802 // qualified path in type
9803 AST::QualifiedPathInType path = parse_qualified_path_in_type ();
9804 if (path.is_error ())
9805 {
9806 Error error (t->get_locus (),
9807 "failed to parse qualified path in type");
9808 add_error (std::move (error));
9809
9810 return nullptr;
9811 }
9812 return std::unique_ptr<AST::QualifiedPathInType> (
9813 new AST::QualifiedPathInType (std::move (path)));
9814 }
9815 case UNDERSCORE:
9816 // inferred type
9817 lexer.skip_token ();
9818 return std::unique_ptr<AST::InferredType> (
9819 new AST::InferredType (t->get_locus ()));
9820 case ASTERISK:
9821 // raw pointer type
9822 return parse_raw_pointer_type ();
9823 case AMP: // does this also include AMP_AMP? Yes! Which is... LOGICAL_AND?
9824 case LOGICAL_AND:
9825 // reference type
9826 return parse_reference_type ();
9827 case LIFETIME:
9828 /* probably a lifetime bound, so probably type param bounds in
9829 * TraitObjectType. this is not allowed, but detection here for error
9830 * message */
9831 add_error (Error (t->get_locus (),
9832 "lifetime bounds (i.e. in type param bounds, in "
9833 "TraitObjectType) are not allowed as TypeNoBounds"));
9834
9835 return nullptr;
9836 case IDENTIFIER:
9837 case SUPER:
9838 case SELF:
9839 case SELF_ALIAS:
9840 case CRATE:
9841 case DOLLAR_SIGN:
9842 case SCOPE_RESOLUTION: {
9843 // macro invocation or type path - requires further disambiguation.
9844 /* for parsing path component of each rule, perhaps parse it as a
9845 * typepath and attempt conversion to simplepath if a trailing '!' is
9846 * found */
9847 /* Type path also includes TraitObjectTypeOneBound BUT if it starts
9848 * with it, it is exactly the same as a TypePath syntactically, so
9849 * this is a syntactical ambiguity. As such, the parser will parse it
9850 * as a TypePath. This, however, does not prevent TraitObjectType from
9851 * starting with a typepath. */
9852
9853 // parse path as type path
9854 AST::TypePath path = parse_type_path ();
9855 if (path.is_error ())
9856 {
9857 Error error (
9858 t->get_locus (),
9859 "failed to parse path as first component of type no bounds");
9860 add_error (std::move (error));
9861
9862 return nullptr;
9863 }
9864 location_t locus = path.get_locus ();
9865
9866 // branch on next token
9867 t = lexer.peek_token ();
9868 switch (t->get_id ())
9869 {
9870 case EXCLAM: {
9871 // macro invocation
9872 // convert to simple path
9873 AST::SimplePath macro_path = path.as_simple_path ();
9874 if (macro_path.is_empty ())
9875 {
9876 Error error (t->get_locus (),
9877 "failed to parse simple path in macro "
9878 "invocation (for type)");
9879 add_error (std::move (error));
9880
9881 return nullptr;
9882 }
9883
9884 lexer.skip_token ();
9885
9886 AST::DelimTokenTree tok_tree = parse_delim_token_tree ();
9887
9888 return AST::MacroInvocation::Regular (
9889 AST::MacroInvocData (std::move (macro_path),
9890 std::move (tok_tree)),
9891 {}, locus);
9892 }
9893 default:
9894 // assume that this is a type path and not an error
9895 return std::unique_ptr<AST::TypePath> (
9896 new AST::TypePath (std::move (path)));
9897 }
9898 }
9899 case LEFT_PAREN:
9900 /* tuple type or parenthesised type - requires further disambiguation
9901 * (the usual). ok apparently can be a parenthesised TraitBound too, so
9902 * could be TraitObjectTypeOneBound */
9903 return parse_paren_prefixed_type_no_bounds ();
9904 case FOR:
9905 case ASYNC:
9906 case CONST:
9907 case UNSAFE:
9908 case EXTERN_KW:
9909 case FN_KW:
9910 // bare function type (with no for lifetimes)
9911 return parse_bare_function_type (std::vector<AST::LifetimeParam> ());
9912 case IMPL:
9913 lexer.skip_token ();
9914 if (lexer.peek_token ()->get_id () == LIFETIME)
9915 {
9916 /* cannot be one bound because lifetime prevents it from being
9917 * traitbound not allowed as type no bounds, only here for error
9918 * message */
9919 Error error (
9920 lexer.peek_token ()->get_locus (),
9921 "lifetime (probably lifetime bound, in type param "
9922 "bounds, in ImplTraitType) is not allowed in TypeNoBounds");
9923 add_error (std::move (error));
9924
9925 return nullptr;
9926 }
9927 else
9928 {
9929 // should be trait bound, so parse trait bound
9930 std::unique_ptr<AST::TraitBound> initial_bound = parse_trait_bound ();
9931 if (initial_bound == nullptr)
9932 {
9933 Error error (lexer.peek_token ()->get_locus (),
9934 "failed to parse ImplTraitTypeOneBound bound");
9935 add_error (std::move (error));
9936
9937 return nullptr;
9938 }
9939
9940 location_t locus = t->get_locus ();
9941
9942 // ensure not a trait with multiple bounds
9943 t = lexer.peek_token ();
9944 if (t->get_id () == PLUS)
9945 {
9946 Error error (t->get_locus (),
9947 "plus after trait bound means an ImplTraitType, "
9948 "which is not allowed as a TypeNoBounds");
9949 add_error (std::move (error));
9950
9951 return nullptr;
9952 }
9953
9954 // convert trait bound to value object
9955 AST::TraitBound value_bound (*initial_bound);
9956
9957 return std::unique_ptr<AST::ImplTraitTypeOneBound> (
9958 new AST::ImplTraitTypeOneBound (std::move (value_bound), locus));
9959 }
9960 case DYN:
9961 case QUESTION_MARK: {
9962 // either TraitObjectTypeOneBound
9963 bool has_dyn = false;
9964 if (t->get_id () == DYN)
9965 {
9966 lexer.skip_token ();
9967 has_dyn = true;
9968 }
9969
9970 if (lexer.peek_token ()->get_id () == LIFETIME)
9971 {
9972 /* means that cannot be TraitObjectTypeOneBound - so here for
9973 * error message */
9974 Error error (lexer.peek_token ()->get_locus (),
9975 "lifetime as bound in TraitObjectTypeOneBound "
9976 "is not allowed, so cannot be TypeNoBounds");
9977 add_error (std::move (error));
9978
9979 return nullptr;
9980 }
9981
9982 // should be trait bound, so parse trait bound
9983 std::unique_ptr<AST::TraitBound> initial_bound = parse_trait_bound ();
9984 if (initial_bound == nullptr)
9985 {
9986 Error error (
9987 lexer.peek_token ()->get_locus (),
9988 "failed to parse TraitObjectTypeOneBound initial bound");
9989 add_error (std::move (error));
9990
9991 return nullptr;
9992 }
9993
9994 location_t locus = t->get_locus ();
9995
9996 // detect error with plus as next token
9997 t = lexer.peek_token ();
9998 if (t->get_id () == PLUS)
9999 {
10000 Error error (t->get_locus (),
10001 "plus after trait bound means a TraitObjectType, "
10002 "which is not allowed as a TypeNoBounds");
10003 add_error (std::move (error));
10004
10005 return nullptr;
10006 }
10007
10008 // convert trait bound to value object
10009 AST::TraitBound value_bound (*initial_bound);
10010
10011 return std::unique_ptr<AST::TraitObjectTypeOneBound> (
10012 new AST::TraitObjectTypeOneBound (std::move (value_bound), locus,
10013 has_dyn));
10014 }
10015 default:
10016 add_error (Error (t->get_locus (),
10017 "unrecognised token %qs in type no bounds",
10018 t->get_token_description ()));
10019
10020 return nullptr;
10021 }
10022 }
10023
10024 // Parses a type no bounds beginning with '('.
10025 template <typename ManagedTokenSource>
10026 std::unique_ptr<AST::TypeNoBounds>
10027 Parser<ManagedTokenSource>::parse_paren_prefixed_type_no_bounds ()
10028 {
10029 /* NOTE: this could probably be parsed without the HACK solution of
10030 * parse_paren_prefixed_type, but I was lazy. So FIXME for future.*/
10031
10032 /* NOTE: again, syntactical ambiguity of a parenthesised trait bound is
10033 * considered a trait bound, not a parenthesised type, so that it can still
10034 * be used in type param bounds. */
10035
10036 location_t left_paren_locus = lexer.peek_token ()->get_locus ();
10037
10038 // skip left delim
10039 lexer.skip_token ();
10040 /* while next token isn't close delim, parse comma-separated types, saving
10041 * whether trailing comma happens */
10042 const_TokenPtr t = lexer.peek_token ();
10043 bool trailing_comma = true;
10044 std::vector<std::unique_ptr<AST::Type>> types;
10045
10046 while (t->get_id () != RIGHT_PAREN)
10047 {
10048 std::unique_ptr<AST::Type> type = parse_type ();
10049 if (type == nullptr)
10050 {
10051 Error error (t->get_locus (),
10052 "failed to parse type inside parentheses (probably "
10053 "tuple or parenthesised)");
10054 add_error (std::move (error));
10055
10056 return nullptr;
10057 }
10058 types.push_back (std::move (type));
10059
10060 t = lexer.peek_token ();
10061 if (t->get_id () != COMMA)
10062 {
10063 trailing_comma = false;
10064 break;
10065 }
10066 lexer.skip_token ();
10067
10068 t = lexer.peek_token ();
10069 }
10070
10071 if (!skip_token (RIGHT_PAREN))
10072 {
10073 return nullptr;
10074 }
10075
10076 // if only one type and no trailing comma, then not a tuple type
10077 if (types.size () == 1 && !trailing_comma)
10078 {
10079 // must be a TraitObjectType (with more than one bound)
10080 if (lexer.peek_token ()->get_id () == PLUS)
10081 {
10082 // error - this is not allowed for type no bounds
10083 Error error (lexer.peek_token ()->get_locus (),
10084 "plus (implying TraitObjectType as type param "
10085 "bounds) is not allowed in type no bounds");
10086 add_error (std::move (error));
10087
10088 return nullptr;
10089 }
10090 else
10091 {
10092 // release vector pointer
10093 std::unique_ptr<AST::Type> released_ptr = std::move (types[0]);
10094 /* HACK: attempt to convert to trait bound. if fails, parenthesised
10095 * type */
10096 std::unique_ptr<AST::TraitBound> converted_bound (
10097 released_ptr->to_trait_bound (true));
10098 if (converted_bound == nullptr)
10099 {
10100 // parenthesised type
10101 return std::unique_ptr<AST::ParenthesisedType> (
10102 new AST::ParenthesisedType (std::move (released_ptr),
10103 left_paren_locus));
10104 }
10105 else
10106 {
10107 // trait object type (one bound)
10108
10109 // get value semantics trait bound
10110 AST::TraitBound value_bound (*converted_bound);
10111
10112 return std::unique_ptr<AST::TraitObjectTypeOneBound> (
10113 new AST::TraitObjectTypeOneBound (value_bound,
10114 left_paren_locus));
10115 }
10116 }
10117 }
10118 else
10119 {
10120 return std::unique_ptr<AST::TupleType> (
10121 new AST::TupleType (std::move (types), left_paren_locus));
10122 }
10123 /* TODO: ensure that this ensures that dynamic dispatch for traits is not
10124 * lost somehow */
10125 }
10126
10127 /* Parses a literal pattern or range pattern. Assumes that literals passed in
10128 * are valid range pattern bounds. Do not pass in paths in expressions, for
10129 * instance. */
10130 template <typename ManagedTokenSource>
10131 std::unique_ptr<AST::Pattern>
10132 Parser<ManagedTokenSource>::parse_literal_or_range_pattern ()
10133 {
10134 const_TokenPtr range_lower = lexer.peek_token ();
10135 AST::Literal::LitType type = AST::Literal::STRING;
10136 bool has_minus = false;
10137
10138 // get lit type
10139 switch (range_lower->get_id ())
10140 {
10141 case CHAR_LITERAL:
10142 type = AST::Literal::CHAR;
10143 lexer.skip_token ();
10144 break;
10145 case BYTE_CHAR_LITERAL:
10146 type = AST::Literal::BYTE;
10147 lexer.skip_token ();
10148 break;
10149 case INT_LITERAL:
10150 type = AST::Literal::INT;
10151 lexer.skip_token ();
10152 break;
10153 case FLOAT_LITERAL:
10154 type = AST::Literal::FLOAT;
10155 lexer.skip_token ();
10156 break;
10157 case MINUS:
10158 // branch on next token
10159 range_lower = lexer.peek_token (1);
10160 switch (range_lower->get_id ())
10161 {
10162 case INT_LITERAL:
10163 type = AST::Literal::INT;
10164 has_minus = true;
10165 lexer.skip_token (1);
10166 break;
10167 case FLOAT_LITERAL:
10168 type = AST::Literal::FLOAT;
10169 has_minus = true;
10170 lexer.skip_token (1);
10171 break;
10172 default:
10173 add_error (Error (range_lower->get_locus (),
10174 "token type %qs cannot be parsed as range pattern "
10175 "bound or literal after minus symbol",
10176 range_lower->get_token_description ()));
10177
10178 return nullptr;
10179 }
10180 break;
10181 default:
10182 add_error (
10183 Error (range_lower->get_locus (),
10184 "token type %qs cannot be parsed as range pattern bound",
10185 range_lower->get_token_description ()));
10186
10187 return nullptr;
10188 }
10189
10190 const_TokenPtr next = lexer.peek_token ();
10191 if (next->get_id () == DOT_DOT_EQ || next->get_id () == ELLIPSIS
10192 || next->get_id () == DOT_DOT)
10193 {
10194 AST::RangeKind kind = AST::tokenid_to_rangekind (next->get_id ());
10195 // range pattern
10196 lexer.skip_token ();
10197 std::unique_ptr<AST::RangePatternBound> lower (
10198 new AST::RangePatternBoundLiteral (
10199 AST::Literal (range_lower->get_str (), type,
10200 PrimitiveCoreType::CORETYPE_UNKNOWN),
10201 range_lower->get_locus (), has_minus));
10202
10203 std::unique_ptr<AST::RangePatternBound> upper
10204 = parse_range_pattern_bound ();
10205 if (upper == nullptr)
10206 {
10207 Error error (next->get_locus (),
10208 "failed to parse range pattern bound in range pattern");
10209 add_error (std::move (error));
10210
10211 return nullptr;
10212 }
10213
10214 return std::unique_ptr<AST::RangePattern> (
10215 new AST::RangePattern (std::move (lower), std::move (upper), kind,
10216 range_lower->get_locus ()));
10217 }
10218 else
10219 {
10220 // literal pattern
10221 return std::unique_ptr<AST::LiteralPattern> (
10222 new AST::LiteralPattern (range_lower->get_str (), type,
10223 range_lower->get_locus (),
10224 range_lower->get_type_hint ()));
10225 }
10226 }
10227
10228 // Parses a range pattern bound (value only).
10229 template <typename ManagedTokenSource>
10230 std::unique_ptr<AST::RangePatternBound>
10231 Parser<ManagedTokenSource>::parse_range_pattern_bound ()
10232 {
10233 const_TokenPtr range_lower = lexer.peek_token ();
10234 location_t range_lower_locus = range_lower->get_locus ();
10235
10236 // get lit type
10237 switch (range_lower->get_id ())
10238 {
10239 case CHAR_LITERAL:
10240 lexer.skip_token ();
10241 return std::unique_ptr<AST::RangePatternBoundLiteral> (
10242 new AST::RangePatternBoundLiteral (
10243 AST::Literal (range_lower->get_str (), AST::Literal::CHAR,
10244 range_lower->get_type_hint ()),
10245 range_lower_locus));
10246 case BYTE_CHAR_LITERAL:
10247 lexer.skip_token ();
10248 return std::unique_ptr<AST::RangePatternBoundLiteral> (
10249 new AST::RangePatternBoundLiteral (
10250 AST::Literal (range_lower->get_str (), AST::Literal::BYTE,
10251 range_lower->get_type_hint ()),
10252 range_lower_locus));
10253 case INT_LITERAL:
10254 lexer.skip_token ();
10255 return std::unique_ptr<AST::RangePatternBoundLiteral> (
10256 new AST::RangePatternBoundLiteral (
10257 AST::Literal (range_lower->get_str (), AST::Literal::INT,
10258 range_lower->get_type_hint ()),
10259 range_lower_locus));
10260 case FLOAT_LITERAL:
10261 lexer.skip_token ();
10262 rust_debug ("warning: used deprecated float range pattern bound");
10263 return std::unique_ptr<AST::RangePatternBoundLiteral> (
10264 new AST::RangePatternBoundLiteral (
10265 AST::Literal (range_lower->get_str (), AST::Literal::FLOAT,
10266 range_lower->get_type_hint ()),
10267 range_lower_locus));
10268 case MINUS:
10269 // branch on next token
10270 range_lower = lexer.peek_token (1);
10271 switch (range_lower->get_id ())
10272 {
10273 case INT_LITERAL:
10274 lexer.skip_token (1);
10275 return std::unique_ptr<AST::RangePatternBoundLiteral> (
10276 new AST::RangePatternBoundLiteral (
10277 AST::Literal (range_lower->get_str (), AST::Literal::INT,
10278 range_lower->get_type_hint ()),
10279 range_lower_locus, true));
10280 case FLOAT_LITERAL:
10281 lexer.skip_token (1);
10282 rust_debug ("warning: used deprecated float range pattern bound");
10283 return std::unique_ptr<AST::RangePatternBoundLiteral> (
10284 new AST::RangePatternBoundLiteral (
10285 AST::Literal (range_lower->get_str (), AST::Literal::FLOAT,
10286 range_lower->get_type_hint ()),
10287 range_lower_locus, true));
10288 default:
10289 add_error (Error (range_lower->get_locus (),
10290 "token type %qs cannot be parsed as range pattern "
10291 "bound after minus symbol",
10292 range_lower->get_token_description ()));
10293
10294 return nullptr;
10295 }
10296 case IDENTIFIER:
10297 case SUPER:
10298 case SELF:
10299 case SELF_ALIAS:
10300 case CRATE:
10301 case SCOPE_RESOLUTION:
10302 case DOLLAR_SIGN: {
10303 // path in expression
10304 AST::PathInExpression path = parse_path_in_expression ();
10305 if (path.is_error ())
10306 {
10307 Error error (
10308 range_lower->get_locus (),
10309 "failed to parse path in expression range pattern bound");
10310 add_error (std::move (error));
10311
10312 return nullptr;
10313 }
10314 return std::unique_ptr<AST::RangePatternBoundPath> (
10315 new AST::RangePatternBoundPath (std::move (path)));
10316 }
10317 case LEFT_SHIFT:
10318 case LEFT_ANGLE: {
10319 // qualified path in expression
10320 AST::QualifiedPathInExpression path
10321 = parse_qualified_path_in_expression ();
10322 if (path.is_error ())
10323 {
10324 Error error (range_lower->get_locus (),
10325 "failed to parse qualified path in expression range "
10326 "pattern bound");
10327 add_error (std::move (error));
10328
10329 return nullptr;
10330 }
10331 return std::unique_ptr<AST::RangePatternBoundQualPath> (
10332 new AST::RangePatternBoundQualPath (std::move (path)));
10333 }
10334 default:
10335 add_error (
10336 Error (range_lower->get_locus (),
10337 "token type %qs cannot be parsed as range pattern bound",
10338 range_lower->get_token_description ()));
10339
10340 return nullptr;
10341 }
10342 }
10343
10344 template <typename ManagedTokenSource>
10345 std::unique_ptr<AST::Pattern>
10346 Parser<ManagedTokenSource>::parse_pattern ()
10347 {
10348 location_t start_locus = lexer.peek_token ()->get_locus ();
10349
10350 /* skip optional starting pipe */
10351 maybe_skip_token (PIPE);
10352
10353 auto first = parse_pattern_no_alt ();
10354
10355 if (lexer.peek_token ()->get_id () != PIPE)
10356 /* no alternates */
10357 return first;
10358
10359 std::vector<std::unique_ptr<AST::Pattern>> alts;
10360 alts.push_back (std::move (first));
10361
10362 do
10363 {
10364 lexer.skip_token ();
10365 alts.push_back (parse_pattern_no_alt ());
10366 }
10367
10368 while (lexer.peek_token ()->get_id () == PIPE);
10369
10370 /* alternates */
10371 return std::unique_ptr<AST::Pattern> (
10372 new AST::AltPattern (std::move (alts), start_locus));
10373 }
10374
10375 // Parses a pattern without alternates ('|')
10376 // (will further disambiguate any pattern).
10377 template <typename ManagedTokenSource>
10378 std::unique_ptr<AST::Pattern>
10379 Parser<ManagedTokenSource>::parse_pattern_no_alt ()
10380 {
10381 const_TokenPtr t = lexer.peek_token ();
10382 switch (t->get_id ())
10383 {
10384 case TRUE_LITERAL:
10385 lexer.skip_token ();
10386 return std::unique_ptr<AST::LiteralPattern> (
10387 new AST::LiteralPattern (Values::Keywords::TRUE_LITERAL,
10388 AST::Literal::BOOL, t->get_locus (),
10389 t->get_type_hint ()));
10390 case FALSE_LITERAL:
10391 lexer.skip_token ();
10392 return std::unique_ptr<AST::LiteralPattern> (
10393 new AST::LiteralPattern (Values::Keywords::FALSE_LITERAL,
10394 AST::Literal::BOOL, t->get_locus (),
10395 t->get_type_hint ()));
10396 case CHAR_LITERAL:
10397 case BYTE_CHAR_LITERAL:
10398 case INT_LITERAL:
10399 case FLOAT_LITERAL:
10400 return parse_literal_or_range_pattern ();
10401 case STRING_LITERAL:
10402 lexer.skip_token ();
10403 return std::unique_ptr<AST::LiteralPattern> (
10404 new AST::LiteralPattern (t->get_str (), AST::Literal::STRING,
10405 t->get_locus (), t->get_type_hint ()));
10406 case BYTE_STRING_LITERAL:
10407 lexer.skip_token ();
10408 return std::unique_ptr<AST::LiteralPattern> (
10409 new AST::LiteralPattern (t->get_str (), AST::Literal::BYTE_STRING,
10410 t->get_locus (), t->get_type_hint ()));
10411 case RAW_STRING_LITERAL:
10412 lexer.skip_token ();
10413 return std::unique_ptr<AST::LiteralPattern> (
10414 new AST::LiteralPattern (t->get_str (), AST::Literal::RAW_STRING,
10415 t->get_locus (), t->get_type_hint ()));
10416 // raw string and raw byte string literals too if they are readded to
10417 // lexer
10418 case MINUS:
10419 if (lexer.peek_token (1)->get_id () == INT_LITERAL)
10420 {
10421 return parse_literal_or_range_pattern ();
10422 }
10423 else if (lexer.peek_token (1)->get_id () == FLOAT_LITERAL)
10424 {
10425 return parse_literal_or_range_pattern ();
10426 }
10427 else
10428 {
10429 Error error (t->get_locus (), "unexpected token %<-%> in pattern - "
10430 "did you forget an integer literal");
10431 add_error (std::move (error));
10432
10433 return nullptr;
10434 }
10435 case UNDERSCORE:
10436 lexer.skip_token ();
10437 return std::unique_ptr<AST::WildcardPattern> (
10438 new AST::WildcardPattern (t->get_locus ()));
10439 case DOT_DOT:
10440 lexer.skip_token ();
10441 return std::unique_ptr<AST::RestPattern> (
10442 new AST::RestPattern (t->get_locus ()));
10443 case REF:
10444 case MUT:
10445 return parse_identifier_pattern ();
10446 case IDENTIFIER:
10447 /* if identifier with no scope resolution afterwards, identifier
10448 * pattern. if scope resolution afterwards, path pattern (or range
10449 * pattern or struct pattern or tuple struct pattern) or macro
10450 * invocation */
10451 return parse_ident_leading_pattern ();
10452 case AMP:
10453 case LOGICAL_AND:
10454 // reference pattern
10455 return parse_reference_pattern ();
10456 case LEFT_PAREN:
10457 // tuple pattern or grouped pattern
10458 return parse_grouped_or_tuple_pattern ();
10459 case LEFT_SQUARE:
10460 // slice pattern
10461 return parse_slice_pattern ();
10462 case LEFT_SHIFT:
10463 case LEFT_ANGLE: {
10464 // qualified path in expression or qualified range pattern bound
10465 AST::QualifiedPathInExpression path
10466 = parse_qualified_path_in_expression ();
10467
10468 if (lexer.peek_token ()->get_id () == DOT_DOT_EQ
10469 || lexer.peek_token ()->get_id () == ELLIPSIS
10470 || lexer.peek_token ()->get_id () == DOT_DOT)
10471 {
10472 // qualified range pattern bound, so parse rest of range pattern
10473 AST::RangeKind kind
10474 = AST::tokenid_to_rangekind (lexer.peek_token ()->get_id ());
10475 lexer.skip_token ();
10476
10477 std::unique_ptr<AST::RangePatternBoundQualPath> lower_bound (
10478 new AST::RangePatternBoundQualPath (std::move (path)));
10479 std::unique_ptr<AST::RangePatternBound> upper_bound
10480 = parse_range_pattern_bound ();
10481
10482 return std::unique_ptr<AST::RangePattern> (
10483 new AST::RangePattern (std::move (lower_bound),
10484 std::move (upper_bound), kind,
10485 t->get_locus ()));
10486 }
10487 else
10488 {
10489 // just qualified path in expression
10490 return std::unique_ptr<AST::QualifiedPathInExpression> (
10491 new AST::QualifiedPathInExpression (std::move (path)));
10492 }
10493 }
10494 case SUPER:
10495 case SELF:
10496 case SELF_ALIAS:
10497 case CRATE:
10498 case SCOPE_RESOLUTION:
10499 case DOLLAR_SIGN: {
10500 // path in expression or range pattern bound
10501 AST::PathInExpression path = parse_path_in_expression ();
10502
10503 const_TokenPtr next = lexer.peek_token ();
10504 switch (next->get_id ())
10505 {
10506 case DOT_DOT_EQ:
10507 case DOT_DOT:
10508 case ELLIPSIS: {
10509 // qualified range pattern bound, so parse rest of range pattern
10510 AST::RangeKind kind = AST::tokenid_to_rangekind (next->get_id ());
10511 lexer.skip_token ();
10512
10513 std::unique_ptr<AST::RangePatternBoundPath> lower_bound (
10514 new AST::RangePatternBoundPath (std::move (path)));
10515 std::unique_ptr<AST::RangePatternBound> upper_bound
10516 = parse_range_pattern_bound ();
10517
10518 return std::unique_ptr<AST::RangePattern> (
10519 new AST::RangePattern (std::move (lower_bound),
10520 std::move (upper_bound), kind,
10521 next->get_locus ()));
10522 }
10523 case EXCLAM:
10524 return parse_macro_invocation_partial (std::move (path),
10525 AST::AttrVec ());
10526 case LEFT_PAREN: {
10527 // tuple struct
10528 lexer.skip_token ();
10529
10530 // parse items
10531 std::unique_ptr<AST::TupleStructItems> items
10532 = parse_tuple_struct_items ();
10533 if (items == nullptr)
10534 {
10535 Error error (lexer.peek_token ()->get_locus (),
10536 "failed to parse tuple struct items");
10537 add_error (std::move (error));
10538
10539 return nullptr;
10540 }
10541
10542 if (!skip_token (RIGHT_PAREN))
10543 {
10544 return nullptr;
10545 }
10546
10547 return std::unique_ptr<AST::TupleStructPattern> (
10548 new AST::TupleStructPattern (std::move (path),
10549 std::move (items)));
10550 }
10551 case LEFT_CURLY: {
10552 // struct
10553 lexer.skip_token ();
10554
10555 // parse elements (optional)
10556 AST::StructPatternElements elems = parse_struct_pattern_elems ();
10557
10558 if (!skip_token (RIGHT_CURLY))
10559 {
10560 return nullptr;
10561 }
10562
10563 return std::unique_ptr<AST::StructPattern> (
10564 new AST::StructPattern (std::move (path), t->get_locus (),
10565 std::move (elems)));
10566 }
10567 default:
10568 // assume path in expression
10569 return std::unique_ptr<AST::PathInExpression> (
10570 new AST::PathInExpression (std::move (path)));
10571 }
10572 }
10573 default:
10574 add_error (Error (t->get_locus (), "unexpected token %qs in pattern",
10575 t->get_token_description ()));
10576
10577 return nullptr;
10578 }
10579 }
10580
10581 // Parses a single or double reference pattern.
10582 template <typename ManagedTokenSource>
10583 std::unique_ptr<AST::ReferencePattern>
10584 Parser<ManagedTokenSource>::parse_reference_pattern ()
10585 {
10586 // parse double or single ref
10587 bool is_double_ref = false;
10588 const_TokenPtr t = lexer.peek_token ();
10589 switch (t->get_id ())
10590 {
10591 case AMP:
10592 // still false
10593 lexer.skip_token ();
10594 break;
10595 case LOGICAL_AND:
10596 is_double_ref = true;
10597 lexer.skip_token ();
10598 break;
10599 default:
10600 add_error (Error (t->get_locus (),
10601 "unexpected token %qs in reference pattern",
10602 t->get_token_description ()));
10603
10604 return nullptr;
10605 }
10606
10607 // parse mut (if it exists)
10608 bool is_mut = false;
10609 if (lexer.peek_token ()->get_id () == MUT)
10610 {
10611 is_mut = true;
10612 lexer.skip_token ();
10613 }
10614
10615 // parse pattern to get reference of (required)
10616 std::unique_ptr<AST::Pattern> pattern = parse_pattern_no_alt ();
10617 if (pattern == nullptr)
10618 {
10619 Error error (lexer.peek_token ()->get_locus (),
10620 "failed to parse pattern in reference pattern");
10621 add_error (std::move (error));
10622
10623 // skip somewhere?
10624 return nullptr;
10625 }
10626
10627 return std::unique_ptr<AST::ReferencePattern> (
10628 new AST::ReferencePattern (std::move (pattern), is_mut, is_double_ref,
10629 t->get_locus ()));
10630 }
10631
10632 /* Parses a grouped pattern or tuple pattern. Prefers grouped over tuple if
10633 * only a single element with no commas. */
10634 template <typename ManagedTokenSource>
10635 std::unique_ptr<AST::Pattern>
10636 Parser<ManagedTokenSource>::parse_grouped_or_tuple_pattern ()
10637 {
10638 location_t paren_locus = lexer.peek_token ()->get_locus ();
10639 skip_token (LEFT_PAREN);
10640
10641 // detect '..' token (ranged with no lower range)
10642 if (lexer.peek_token ()->get_id () == DOT_DOT)
10643 {
10644 lexer.skip_token ();
10645
10646 // parse new patterns while next token is a comma
10647 std::vector<std::unique_ptr<AST::Pattern>> patterns;
10648
10649 const_TokenPtr t = lexer.peek_token ();
10650 while (t->get_id () == COMMA)
10651 {
10652 lexer.skip_token ();
10653
10654 // break if next token is ')'
10655 if (lexer.peek_token ()->get_id () == RIGHT_PAREN)
10656 {
10657 break;
10658 }
10659
10660 // parse pattern, which is required
10661 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
10662 if (pattern == nullptr)
10663 {
10664 Error error (
10665 lexer.peek_token ()->get_locus (),
10666 "failed to parse pattern inside ranged tuple pattern");
10667 add_error (std::move (error));
10668
10669 // skip somewhere?
10670 return nullptr;
10671 }
10672 patterns.push_back (std::move (pattern));
10673
10674 t = lexer.peek_token ();
10675 }
10676
10677 if (!skip_token (RIGHT_PAREN))
10678 {
10679 // skip somewhere?
10680 return nullptr;
10681 }
10682
10683 // create ranged tuple pattern items with only upper items
10684 std::unique_ptr<AST::TuplePatternItemsRanged> items (
10685 new AST::TuplePatternItemsRanged (
10686 std::vector<std::unique_ptr<AST::Pattern>> (), std::move (patterns)));
10687 return std::unique_ptr<AST::TuplePattern> (
10688 new AST::TuplePattern (std::move (items), paren_locus));
10689 }
10690 else if (lexer.peek_token ()->get_id () == RIGHT_PAREN)
10691 {
10692 skip_token (RIGHT_PAREN);
10693 auto items = std::unique_ptr<AST::TuplePatternItemsMultiple> (
10694 new AST::TuplePatternItemsMultiple (
10695 std::vector<std::unique_ptr<AST::Pattern>> ()));
10696 return std::unique_ptr<AST::TuplePattern> (
10697 new AST::TuplePattern (std::move (items), paren_locus));
10698 }
10699
10700 // parse initial pattern (required)
10701 std::unique_ptr<AST::Pattern> initial_pattern = parse_pattern ();
10702 if (initial_pattern == nullptr)
10703 {
10704 Error error (lexer.peek_token ()->get_locus (),
10705 "failed to parse pattern in grouped or tuple pattern");
10706 add_error (std::move (error));
10707
10708 return nullptr;
10709 }
10710
10711 // branch on whether next token is a comma or not
10712 const_TokenPtr t = lexer.peek_token ();
10713 switch (t->get_id ())
10714 {
10715 case RIGHT_PAREN:
10716 // grouped pattern
10717 lexer.skip_token ();
10718
10719 return std::unique_ptr<AST::GroupedPattern> (
10720 new AST::GroupedPattern (std::move (initial_pattern), paren_locus));
10721 case COMMA: {
10722 // tuple pattern
10723 lexer.skip_token ();
10724
10725 // create vector of patterns
10726 std::vector<std::unique_ptr<AST::Pattern>> patterns;
10727 patterns.push_back (std::move (initial_pattern));
10728
10729 t = lexer.peek_token ();
10730 while (t->get_id () != RIGHT_PAREN && t->get_id () != DOT_DOT)
10731 {
10732 // parse pattern (required)
10733 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
10734 if (pattern == nullptr)
10735 {
10736 Error error (t->get_locus (),
10737 "failed to parse pattern in tuple pattern");
10738 add_error (std::move (error));
10739
10740 return nullptr;
10741 }
10742 patterns.push_back (std::move (pattern));
10743
10744 if (lexer.peek_token ()->get_id () != COMMA)
10745 break;
10746
10747 lexer.skip_token ();
10748 t = lexer.peek_token ();
10749 }
10750
10751 t = lexer.peek_token ();
10752 if (t->get_id () == RIGHT_PAREN)
10753 {
10754 // non-ranged tuple pattern
10755 lexer.skip_token ();
10756
10757 std::unique_ptr<AST::TuplePatternItemsMultiple> items (
10758 new AST::TuplePatternItemsMultiple (std::move (patterns)));
10759 return std::unique_ptr<AST::TuplePattern> (
10760 new AST::TuplePattern (std::move (items), paren_locus));
10761 }
10762 else if (t->get_id () == DOT_DOT)
10763 {
10764 // ranged tuple pattern
10765 lexer.skip_token ();
10766
10767 // parse upper patterns
10768 std::vector<std::unique_ptr<AST::Pattern>> upper_patterns;
10769 t = lexer.peek_token ();
10770 while (t->get_id () == COMMA)
10771 {
10772 lexer.skip_token ();
10773
10774 // break if end
10775 if (lexer.peek_token ()->get_id () == RIGHT_PAREN)
10776 break;
10777
10778 // parse pattern (required)
10779 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
10780 if (pattern == nullptr)
10781 {
10782 Error error (lexer.peek_token ()->get_locus (),
10783 "failed to parse pattern in tuple pattern");
10784 add_error (std::move (error));
10785
10786 return nullptr;
10787 }
10788 upper_patterns.push_back (std::move (pattern));
10789
10790 t = lexer.peek_token ();
10791 }
10792
10793 if (!skip_token (RIGHT_PAREN))
10794 {
10795 return nullptr;
10796 }
10797
10798 std::unique_ptr<AST::TuplePatternItemsRanged> items (
10799 new AST::TuplePatternItemsRanged (std::move (patterns),
10800 std::move (upper_patterns)));
10801 return std::unique_ptr<AST::TuplePattern> (
10802 new AST::TuplePattern (std::move (items), paren_locus));
10803 }
10804 else
10805 {
10806 // some kind of error
10807 Error error (t->get_locus (),
10808 "failed to parse tuple pattern (probably) or maybe "
10809 "grouped pattern");
10810 add_error (std::move (error));
10811
10812 return nullptr;
10813 }
10814 }
10815 default:
10816 // error
10817 add_error (Error (t->get_locus (),
10818 "unrecognised token %qs in grouped or tuple pattern "
10819 "after first pattern",
10820 t->get_token_description ()));
10821
10822 return nullptr;
10823 }
10824 }
10825
10826 /* Parses a slice pattern that can match arrays or slices. Parses the square
10827 * brackets too. */
10828 template <typename ManagedTokenSource>
10829 std::unique_ptr<AST::SlicePattern>
10830 Parser<ManagedTokenSource>::parse_slice_pattern ()
10831 {
10832 location_t square_locus = lexer.peek_token ()->get_locus ();
10833 std::vector<std::unique_ptr<AST::Pattern>> patterns;
10834 skip_token (LEFT_SQUARE);
10835
10836 if (lexer.peek_token ()->get_id () == RIGHT_SQUARE)
10837 {
10838 skip_token (RIGHT_SQUARE);
10839 return std::unique_ptr<AST::SlicePattern> (
10840 new AST::SlicePattern (std::move (patterns), square_locus));
10841 }
10842
10843 // parse initial pattern (required)
10844 std::unique_ptr<AST::Pattern> initial_pattern = parse_pattern ();
10845 if (initial_pattern == nullptr)
10846 {
10847 Error error (lexer.peek_token ()->get_locus (),
10848 "failed to parse initial pattern in slice pattern");
10849 add_error (std::move (error));
10850
10851 return nullptr;
10852 }
10853
10854 patterns.push_back (std::move (initial_pattern));
10855
10856 const_TokenPtr t = lexer.peek_token ();
10857 while (t->get_id () == COMMA)
10858 {
10859 lexer.skip_token ();
10860
10861 // break if end bracket
10862 if (lexer.peek_token ()->get_id () == RIGHT_SQUARE)
10863 break;
10864
10865 // parse pattern (required)
10866 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
10867 if (pattern == nullptr)
10868 {
10869 Error error (lexer.peek_token ()->get_locus (),
10870 "failed to parse pattern in slice pattern");
10871 add_error (std::move (error));
10872
10873 return nullptr;
10874 }
10875 patterns.push_back (std::move (pattern));
10876
10877 t = lexer.peek_token ();
10878 }
10879
10880 if (!skip_token (RIGHT_SQUARE))
10881 {
10882 return nullptr;
10883 }
10884
10885 return std::unique_ptr<AST::SlicePattern> (
10886 new AST::SlicePattern (std::move (patterns), square_locus));
10887 }
10888
10889 /* Parses an identifier pattern (pattern that binds a value matched to a
10890 * variable). */
10891 template <typename ManagedTokenSource>
10892 std::unique_ptr<AST::IdentifierPattern>
10893 Parser<ManagedTokenSource>::parse_identifier_pattern ()
10894 {
10895 location_t locus = lexer.peek_token ()->get_locus ();
10896
10897 bool has_ref = false;
10898 if (lexer.peek_token ()->get_id () == REF)
10899 {
10900 has_ref = true;
10901 lexer.skip_token ();
10902
10903 // DEBUG
10904 rust_debug ("parsed ref in identifier pattern");
10905 }
10906
10907 bool has_mut = false;
10908 if (lexer.peek_token ()->get_id () == MUT)
10909 {
10910 has_mut = true;
10911 lexer.skip_token ();
10912 }
10913
10914 // parse identifier (required)
10915 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
10916 if (ident_tok == nullptr)
10917 {
10918 // skip somewhere?
10919 return nullptr;
10920 }
10921 Identifier ident{ident_tok};
10922
10923 // DEBUG
10924 rust_debug ("parsed identifier in identifier pattern");
10925
10926 // parse optional pattern binding thing
10927 std::unique_ptr<AST::Pattern> bind_pattern = nullptr;
10928 if (lexer.peek_token ()->get_id () == PATTERN_BIND)
10929 {
10930 lexer.skip_token ();
10931
10932 // parse required pattern to bind
10933 bind_pattern = parse_pattern ();
10934 if (bind_pattern == nullptr)
10935 {
10936 Error error (lexer.peek_token ()->get_locus (),
10937 "failed to parse pattern to bind in identifier pattern");
10938 add_error (std::move (error));
10939
10940 return nullptr;
10941 }
10942 }
10943
10944 // DEBUG
10945 rust_debug ("about to return identifier pattern");
10946
10947 return std::unique_ptr<AST::IdentifierPattern> (
10948 new AST::IdentifierPattern (std::move (ident), locus, has_ref, has_mut,
10949 std::move (bind_pattern)));
10950 }
10951
10952 /* Parses a pattern that opens with an identifier. This includes identifier
10953 * patterns, path patterns (and derivatives such as struct patterns, tuple
10954 * struct patterns, and macro invocations), and ranges. */
10955 template <typename ManagedTokenSource>
10956 std::unique_ptr<AST::Pattern>
10957 Parser<ManagedTokenSource>::parse_ident_leading_pattern ()
10958 {
10959 // ensure first token is actually identifier
10960 const_TokenPtr initial_tok = lexer.peek_token ();
10961 if (initial_tok->get_id () != IDENTIFIER)
10962 {
10963 return nullptr;
10964 }
10965
10966 // save initial identifier as it may be useful (but don't skip)
10967 std::string initial_ident = initial_tok->get_str ();
10968
10969 // parse next tokens as a PathInExpression
10970 AST::PathInExpression path = parse_path_in_expression ();
10971
10972 // branch on next token
10973 const_TokenPtr t = lexer.peek_token ();
10974 switch (t->get_id ())
10975 {
10976 case EXCLAM:
10977 return parse_macro_invocation_partial (std::move (path), AST::AttrVec ());
10978 case LEFT_PAREN: {
10979 // tuple struct
10980 lexer.skip_token ();
10981
10982 // DEBUG
10983 rust_debug ("parsing tuple struct pattern");
10984
10985 // parse items
10986 std::unique_ptr<AST::TupleStructItems> items
10987 = parse_tuple_struct_items ();
10988 if (items == nullptr)
10989 {
10990 Error error (lexer.peek_token ()->get_locus (),
10991 "failed to parse tuple struct items");
10992 add_error (std::move (error));
10993
10994 return nullptr;
10995 }
10996
10997 // DEBUG
10998 rust_debug ("successfully parsed tuple struct items");
10999
11000 if (!skip_token (RIGHT_PAREN))
11001 {
11002 return nullptr;
11003 }
11004
11005 // DEBUG
11006 rust_debug ("successfully parsed tuple struct pattern");
11007
11008 return std::unique_ptr<AST::TupleStructPattern> (
11009 new AST::TupleStructPattern (std::move (path), std::move (items)));
11010 }
11011 case LEFT_CURLY: {
11012 // struct
11013 lexer.skip_token ();
11014
11015 // parse elements (optional)
11016 AST::StructPatternElements elems = parse_struct_pattern_elems ();
11017
11018 if (!skip_token (RIGHT_CURLY))
11019 {
11020 return nullptr;
11021 }
11022
11023 // DEBUG
11024 rust_debug ("successfully parsed struct pattern");
11025
11026 return std::unique_ptr<AST::StructPattern> (
11027 new AST::StructPattern (std::move (path), initial_tok->get_locus (),
11028 std::move (elems)));
11029 }
11030 case DOT_DOT_EQ:
11031 case DOT_DOT:
11032 case ELLIPSIS: {
11033 // range
11034 AST::RangeKind kind
11035 = AST::tokenid_to_rangekind (lexer.peek_token ()->get_id ());
11036
11037 lexer.skip_token ();
11038
11039 std::unique_ptr<AST::RangePatternBoundPath> lower_bound (
11040 new AST::RangePatternBoundPath (std::move (path)));
11041 std::unique_ptr<AST::RangePatternBound> upper_bound
11042 = parse_range_pattern_bound ();
11043
11044 return std::unique_ptr<AST::RangePattern> (
11045 new AST::RangePattern (std::move (lower_bound),
11046 std::move (upper_bound), kind,
11047 t->get_locus ()));
11048 }
11049 case PATTERN_BIND: {
11050 // only allow on single-segment paths
11051 if (path.is_single_segment ())
11052 {
11053 // identifier with pattern bind
11054 lexer.skip_token ();
11055
11056 std::unique_ptr<AST::Pattern> bind_pattern = parse_pattern ();
11057 if (bind_pattern == nullptr)
11058 {
11059 Error error (
11060 t->get_locus (),
11061 "failed to parse pattern to bind to identifier pattern");
11062 add_error (std::move (error));
11063
11064 return nullptr;
11065 }
11066 return std::unique_ptr<AST::IdentifierPattern> (
11067 new AST::IdentifierPattern (std::move (initial_ident),
11068 initial_tok->get_locus (), false,
11069 false, std::move (bind_pattern)));
11070 }
11071 Error error (
11072 t->get_locus (),
11073 "failed to parse pattern bind to a path, not an identifier");
11074 add_error (std::move (error));
11075
11076 return nullptr;
11077 }
11078 default:
11079 // assume identifier if single segment
11080 if (path.is_single_segment ())
11081 {
11082 return std::unique_ptr<AST::IdentifierPattern> (
11083 new AST::IdentifierPattern (std::move (initial_ident),
11084 initial_tok->get_locus ()));
11085 }
11086 // return path otherwise
11087 return std::unique_ptr<AST::PathInExpression> (
11088 new AST::PathInExpression (std::move (path)));
11089 }
11090 }
11091
11092 // Parses tuple struct items if they exist. Does not parse parentheses.
11093 template <typename ManagedTokenSource>
11094 std::unique_ptr<AST::TupleStructItems>
11095 Parser<ManagedTokenSource>::parse_tuple_struct_items ()
11096 {
11097 std::vector<std::unique_ptr<AST::Pattern>> lower_patterns;
11098
11099 // DEBUG
11100 rust_debug ("started parsing tuple struct items");
11101
11102 // check for '..' at front
11103 if (lexer.peek_token ()->get_id () == DOT_DOT)
11104 {
11105 // only parse upper patterns
11106 lexer.skip_token ();
11107
11108 // DEBUG
11109 rust_debug ("'..' at front in tuple struct items detected");
11110
11111 std::vector<std::unique_ptr<AST::Pattern>> upper_patterns;
11112
11113 const_TokenPtr t = lexer.peek_token ();
11114 while (t->get_id () == COMMA)
11115 {
11116 lexer.skip_token ();
11117
11118 // break if right paren
11119 if (lexer.peek_token ()->get_id () == RIGHT_PAREN)
11120 break;
11121
11122 // parse pattern, which is now required
11123 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
11124 if (pattern == nullptr)
11125 {
11126 Error error (lexer.peek_token ()->get_locus (),
11127 "failed to parse pattern in tuple struct items");
11128 add_error (std::move (error));
11129
11130 return nullptr;
11131 }
11132 upper_patterns.push_back (std::move (pattern));
11133
11134 t = lexer.peek_token ();
11135 }
11136
11137 // DEBUG
11138 rust_debug (
11139 "finished parsing tuple struct items ranged (upper/none only)");
11140
11141 return std::unique_ptr<AST::TupleStructItemsRange> (
11142 new AST::TupleStructItemsRange (std::move (lower_patterns),
11143 std::move (upper_patterns)));
11144 }
11145
11146 // has at least some lower patterns
11147 const_TokenPtr t = lexer.peek_token ();
11148 while (t->get_id () != RIGHT_PAREN && t->get_id () != DOT_DOT)
11149 {
11150 // DEBUG
11151 rust_debug ("about to parse pattern in tuple struct items");
11152
11153 // parse pattern, which is required
11154 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
11155 if (pattern == nullptr)
11156 {
11157 Error error (t->get_locus (),
11158 "failed to parse pattern in tuple struct items");
11159 add_error (std::move (error));
11160
11161 return nullptr;
11162 }
11163 lower_patterns.push_back (std::move (pattern));
11164
11165 // DEBUG
11166 rust_debug ("successfully parsed pattern in tuple struct items");
11167
11168 if (lexer.peek_token ()->get_id () != COMMA)
11169 {
11170 // DEBUG
11171 rust_debug ("broke out of parsing patterns in tuple struct "
11172 "items as no comma");
11173
11174 break;
11175 }
11176 lexer.skip_token ();
11177 t = lexer.peek_token ();
11178 }
11179
11180 // branch on next token
11181 t = lexer.peek_token ();
11182 switch (t->get_id ())
11183 {
11184 case RIGHT_PAREN:
11185 return std::unique_ptr<AST::TupleStructItemsNoRange> (
11186 new AST::TupleStructItemsNoRange (std::move (lower_patterns)));
11187 case DOT_DOT: {
11188 // has an upper range that must be parsed separately
11189 lexer.skip_token ();
11190
11191 std::vector<std::unique_ptr<AST::Pattern>> upper_patterns;
11192
11193 t = lexer.peek_token ();
11194 while (t->get_id () == COMMA)
11195 {
11196 lexer.skip_token ();
11197
11198 // break if next token is right paren
11199 if (lexer.peek_token ()->get_id () == RIGHT_PAREN)
11200 break;
11201
11202 // parse pattern, which is required
11203 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
11204 if (pattern == nullptr)
11205 {
11206 Error error (lexer.peek_token ()->get_locus (),
11207 "failed to parse pattern in tuple struct items");
11208 add_error (std::move (error));
11209
11210 return nullptr;
11211 }
11212 upper_patterns.push_back (std::move (pattern));
11213
11214 t = lexer.peek_token ();
11215 }
11216
11217 return std::unique_ptr<AST::TupleStructItemsRange> (
11218 new AST::TupleStructItemsRange (std::move (lower_patterns),
11219 std::move (upper_patterns)));
11220 }
11221 default:
11222 // error
11223 add_error (Error (t->get_locus (),
11224 "unexpected token %qs in tuple struct items",
11225 t->get_token_description ()));
11226
11227 return nullptr;
11228 }
11229 }
11230
11231 // Parses struct pattern elements if they exist.
11232 template <typename ManagedTokenSource>
11233 AST::StructPatternElements
11234 Parser<ManagedTokenSource>::parse_struct_pattern_elems ()
11235 {
11236 std::vector<std::unique_ptr<AST::StructPatternField>> fields;
11237
11238 AST::AttrVec etc_attrs;
11239 bool has_etc = false;
11240
11241 // try parsing struct pattern fields
11242 const_TokenPtr t = lexer.peek_token ();
11243 while (t->get_id () != RIGHT_CURLY)
11244 {
11245 AST::AttrVec outer_attrs = parse_outer_attributes ();
11246
11247 // parse etc (must be last in struct pattern, so breaks)
11248 if (lexer.peek_token ()->get_id () == DOT_DOT)
11249 {
11250 lexer.skip_token ();
11251 etc_attrs = std::move (outer_attrs);
11252 has_etc = true;
11253 break;
11254 }
11255
11256 std::unique_ptr<AST::StructPatternField> field
11257 = parse_struct_pattern_field_partial (std::move (outer_attrs));
11258 if (field == nullptr)
11259 {
11260 Error error (lexer.peek_token ()->get_locus (),
11261 "failed to parse struct pattern field");
11262 add_error (std::move (error));
11263
11264 // skip after somewhere?
11265 return AST::StructPatternElements::create_empty ();
11266 }
11267 fields.push_back (std::move (field));
11268
11269 if (lexer.peek_token ()->get_id () != COMMA)
11270 break;
11271
11272 // skip comma
11273 lexer.skip_token ();
11274 t = lexer.peek_token ();
11275 }
11276
11277 if (has_etc)
11278 return AST::StructPatternElements (std::move (fields),
11279 std::move (etc_attrs));
11280 else
11281 return AST::StructPatternElements (std::move (fields));
11282 }
11283
11284 /* Parses a struct pattern field (tuple index/pattern, identifier/pattern, or
11285 * identifier). */
11286 template <typename ManagedTokenSource>
11287 std::unique_ptr<AST::StructPatternField>
11288 Parser<ManagedTokenSource>::parse_struct_pattern_field ()
11289 {
11290 // parse outer attributes (if they exist)
11291 AST::AttrVec outer_attrs = parse_outer_attributes ();
11292
11293 return parse_struct_pattern_field_partial (std::move (outer_attrs));
11294 }
11295
11296 /* Parses a struct pattern field (tuple index/pattern, identifier/pattern, or
11297 * identifier), with outer attributes passed in. */
11298 template <typename ManagedTokenSource>
11299 std::unique_ptr<AST::StructPatternField>
11300 Parser<ManagedTokenSource>::parse_struct_pattern_field_partial (
11301 AST::AttrVec outer_attrs)
11302 {
11303 // branch based on next token
11304 const_TokenPtr t = lexer.peek_token ();
11305 switch (t->get_id ())
11306 {
11307 case INT_LITERAL: {
11308 // tuple index
11309 std::string index_str = t->get_str ();
11310 int index = atoi (index_str.c_str ());
11311
11312 lexer.skip_token ();
11313
11314 if (!skip_token (COLON))
11315 {
11316 return nullptr;
11317 }
11318
11319 // parse required pattern
11320 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
11321 if (pattern == nullptr)
11322 {
11323 Error error (
11324 t->get_locus (),
11325 "failed to parse pattern in tuple index struct pattern field");
11326 add_error (std::move (error));
11327
11328 return nullptr;
11329 }
11330
11331 return std::unique_ptr<AST::StructPatternFieldTuplePat> (
11332 new AST::StructPatternFieldTuplePat (index, std::move (pattern),
11333 std::move (outer_attrs),
11334 t->get_locus ()));
11335 }
11336 case IDENTIFIER:
11337 // identifier-pattern OR only identifier
11338 // branch on next token
11339 switch (lexer.peek_token (1)->get_id ())
11340 {
11341 case COLON: {
11342 // identifier-pattern
11343 Identifier ident{t};
11344 lexer.skip_token ();
11345
11346 skip_token (COLON);
11347
11348 // parse required pattern
11349 std::unique_ptr<AST::Pattern> pattern = parse_pattern ();
11350 if (pattern == nullptr)
11351 {
11352 Error error (t->get_locus (),
11353 "failed to parse pattern in struct pattern field");
11354 add_error (std::move (error));
11355
11356 return nullptr;
11357 }
11358
11359 return std::unique_ptr<AST::StructPatternFieldIdentPat> (
11360 new AST::StructPatternFieldIdentPat (std::move (ident),
11361 std::move (pattern),
11362 std::move (outer_attrs),
11363 t->get_locus ()));
11364 }
11365 case COMMA:
11366 case RIGHT_CURLY: {
11367 // identifier only
11368 Identifier ident = {t};
11369 lexer.skip_token ();
11370
11371 return std::unique_ptr<AST::StructPatternFieldIdent> (
11372 new AST::StructPatternFieldIdent (std::move (ident), false, false,
11373 std::move (outer_attrs),
11374 t->get_locus ()));
11375 }
11376 default:
11377 // error
11378 add_error (Error (t->get_locus (),
11379 "unrecognised token %qs in struct pattern field",
11380 t->get_token_description ()));
11381
11382 return nullptr;
11383 }
11384 case REF:
11385 case MUT: {
11386 // only identifier
11387 bool has_ref = false;
11388 if (t->get_id () == REF)
11389 {
11390 has_ref = true;
11391 lexer.skip_token ();
11392 }
11393
11394 bool has_mut = false;
11395 if (lexer.peek_token ()->get_id () == MUT)
11396 {
11397 has_mut = true;
11398 lexer.skip_token ();
11399 }
11400
11401 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
11402 if (ident_tok == nullptr)
11403 {
11404 return nullptr;
11405 }
11406 Identifier ident{ident_tok};
11407
11408 return std::unique_ptr<AST::StructPatternFieldIdent> (
11409 new AST::StructPatternFieldIdent (std::move (ident), has_ref, has_mut,
11410 std::move (outer_attrs),
11411 t->get_locus ()));
11412 }
11413 default:
11414 // not necessarily an error
11415 return nullptr;
11416 }
11417 }
11418
11419 /* Parses a statement or expression (depending on whether a trailing semicolon
11420 * exists). Useful for block expressions where it cannot be determined through
11421 * lookahead whether it is a statement or expression to be parsed. */
11422 template <typename ManagedTokenSource>
11423 ExprOrStmt
11424 Parser<ManagedTokenSource>::parse_stmt_or_expr ()
11425 {
11426 // quick exit for empty statement
11427 const_TokenPtr t = lexer.peek_token ();
11428 if (t->get_id () == SEMICOLON)
11429 {
11430 lexer.skip_token ();
11431 std::unique_ptr<AST::EmptyStmt> stmt (
11432 new AST::EmptyStmt (t->get_locus ()));
11433 return ExprOrStmt (std::move (stmt));
11434 }
11435
11436 // parse outer attributes
11437 AST::AttrVec outer_attrs = parse_outer_attributes ();
11438 ParseRestrictions restrictions;
11439 restrictions.expr_can_be_stmt = true;
11440 std::unique_ptr<AST::Expr> expr;
11441
11442 // parsing this will be annoying because of the many different possibilities
11443 /* best may be just to copy paste in parse_item switch, and failing that try
11444 * to parse outer attributes, and then pass them in to either a let
11445 * statement or (fallback) expression statement. */
11446 // FIXME: think of a way to do this without such a large switch?
11447
11448 /* FIXME: for expressions at least, the only way that they can really be
11449 * parsed properly in this way is if they don't support operators on them.
11450 * They must be pratt-parsed otherwise. As such due to composability, only
11451 * explicit statements will have special cases here. This should roughly
11452 * correspond to "expr-with-block", but this warning is here in case it
11453 * isn't the case. */
11454 t = lexer.peek_token ();
11455 switch (t->get_id ())
11456 {
11457 case LET: {
11458 // let statement
11459 std::unique_ptr<AST::LetStmt> stmt (
11460 parse_let_stmt (std::move (outer_attrs)));
11461 return ExprOrStmt (std::move (stmt));
11462 }
11463 case PUB:
11464 case MOD:
11465 case EXTERN_KW:
11466 case USE:
11467 case FN_KW:
11468 case TYPE:
11469 case STRUCT_KW:
11470 case ENUM_KW:
11471 case CONST:
11472 case STATIC_KW:
11473 case AUTO:
11474 case TRAIT:
11475 case IMPL: {
11476 std::unique_ptr<AST::VisItem> item (
11477 parse_vis_item (std::move (outer_attrs)));
11478 return ExprOrStmt (std::move (item));
11479 }
11480 /* TODO: implement union keyword but not really because of
11481 * context-dependence crappy hack way to parse a union written below to
11482 * separate it from the good code. */
11483 // case UNION:
11484 case UNSAFE: { // maybe - unsafe traits are a thing
11485 /* if any of these (should be all possible VisItem prefixes), parse a
11486 * VisItem - can't parse item because would require reparsing outer
11487 * attributes */
11488 const_TokenPtr t2 = lexer.peek_token (1);
11489 switch (t2->get_id ())
11490 {
11491 case LEFT_CURLY: {
11492 // unsafe block: parse as expression
11493 expr = parse_expr (std::move (outer_attrs), restrictions);
11494 break;
11495 }
11496 case AUTO:
11497 case TRAIT: {
11498 // unsafe trait
11499 std::unique_ptr<AST::VisItem> item (
11500 parse_vis_item (std::move (outer_attrs)));
11501 return ExprOrStmt (std::move (item));
11502 }
11503 case EXTERN_KW:
11504 case FN_KW: {
11505 // unsafe function
11506 std::unique_ptr<AST::VisItem> item (
11507 parse_vis_item (std::move (outer_attrs)));
11508 return ExprOrStmt (std::move (item));
11509 }
11510 case IMPL: {
11511 // unsafe trait impl
11512 std::unique_ptr<AST::VisItem> item (
11513 parse_vis_item (std::move (outer_attrs)));
11514 return ExprOrStmt (std::move (item));
11515 }
11516 default:
11517 add_error (Error (t2->get_locus (),
11518 "unrecognised token %qs after parsing unsafe - "
11519 "expected beginning of expression or statement",
11520 t->get_token_description ()));
11521
11522 // skip somewhere?
11523 return ExprOrStmt::create_error ();
11524 }
11525 break;
11526 }
11527 /* FIXME: this is either a macro invocation or macro invocation semi.
11528 * start parsing to determine which one it is. */
11529 // FIXME: old code there
11530
11531 // crappy hack to do union "keyword"
11532 case IDENTIFIER:
11533 if (t->get_str () == Values::WeakKeywords::UNION
11534 && lexer.peek_token (1)->get_id () == IDENTIFIER)
11535 {
11536 std::unique_ptr<AST::VisItem> item (
11537 parse_vis_item (std::move (outer_attrs)));
11538 return ExprOrStmt (std::move (item));
11539 // or should this go straight to parsing union?
11540 }
11541 else if (t->get_str () == Values::WeakKeywords::MACRO_RULES
11542 && lexer.peek_token (1)->get_id () == EXCLAM)
11543 {
11544 // macro_rules! macro item
11545 std::unique_ptr<AST::Item> item (
11546 parse_macro_rules_def (std::move (outer_attrs)));
11547 return ExprOrStmt (std::move (item));
11548 }
11549 gcc_fallthrough ();
11550 case SUPER:
11551 case SELF:
11552 case SELF_ALIAS:
11553 case CRATE:
11554 case SCOPE_RESOLUTION:
11555 case DOLLAR_SIGN: {
11556 AST::PathInExpression path = parse_path_in_expression ();
11557 std::unique_ptr<AST::Expr> null_denotation;
11558
11559 if (lexer.peek_token ()->get_id () == EXCLAM)
11560 {
11561 std::unique_ptr<AST::MacroInvocation> invoc
11562 = parse_macro_invocation_partial (std::move (path),
11563 std::move (outer_attrs));
11564
11565 if (restrictions.consume_semi && maybe_skip_token (SEMICOLON))
11566 {
11567 invoc->add_semicolon ();
11568 // Macro invocation with semicolon.
11569 return ExprOrStmt (
11570 std::unique_ptr<AST::Stmt> (std::move (invoc)));
11571 }
11572
11573 TokenId after_macro = lexer.peek_token ()->get_id ();
11574
11575 if (invoc->get_invoc_data ().get_delim_tok_tree ().get_delim_type ()
11576 == AST::CURLY
11577 && after_macro != DOT && after_macro != QUESTION_MARK)
11578 {
11579 rust_debug ("braced macro statement");
11580 return ExprOrStmt (
11581 std::unique_ptr<AST::Stmt> (std::move (invoc)));
11582 }
11583
11584 null_denotation = std::move (invoc);
11585 }
11586 else
11587 {
11588 null_denotation
11589 = null_denotation_path (std::move (path), {}, restrictions);
11590 }
11591
11592 expr = left_denotations (std::move (null_denotation), LBP_LOWEST,
11593 std::move (outer_attrs), restrictions);
11594 break;
11595 }
11596 default:
11597 /* expression statement or expression itself - parse
11598 * expression then make it statement if semi afterwards */
11599 expr = parse_expr (std::move (outer_attrs), restrictions);
11600 break;
11601 }
11602
11603 const_TokenPtr after_expr = lexer.peek_token ();
11604 if (after_expr->get_id () == SEMICOLON)
11605 {
11606 // must be expression statement
11607 lexer.skip_token ();
11608
11609 if (expr)
11610 {
11611 std::unique_ptr<AST::ExprStmt> stmt (
11612 new AST::ExprStmt (std::move (expr), t->get_locus (), true));
11613 return ExprOrStmt (std::move (stmt));
11614 }
11615 else
11616 {
11617 return ExprOrStmt::create_error ();
11618 }
11619 }
11620
11621 if (expr && !expr->is_expr_without_block ()
11622 && after_expr->get_id () != RIGHT_CURLY)
11623 {
11624 // block expression statement.
11625 std::unique_ptr<AST::ExprStmt> stmt (
11626 new AST::ExprStmt (std::move (expr), t->get_locus (), false));
11627 return ExprOrStmt (std::move (stmt));
11628 }
11629
11630 // return expression
11631 return ExprOrStmt (std::move (expr));
11632 }
11633
11634 // Parses a struct expression field.
11635 template <typename ManagedTokenSource>
11636 std::unique_ptr<AST::StructExprField>
11637 Parser<ManagedTokenSource>::parse_struct_expr_field ()
11638 {
11639 AST::AttrVec outer_attrs = parse_outer_attributes ();
11640 const_TokenPtr t = lexer.peek_token ();
11641 switch (t->get_id ())
11642 {
11643 case IDENTIFIER:
11644 if (lexer.peek_token (1)->get_id () == COLON)
11645 {
11646 // struct expr field with identifier and expr
11647 Identifier ident = {t};
11648 lexer.skip_token (1);
11649
11650 // parse expression (required)
11651 std::unique_ptr<AST::Expr> expr = parse_expr ();
11652 if (expr == nullptr)
11653 {
11654 Error error (t->get_locus (),
11655 "failed to parse struct expression field with "
11656 "identifier and expression");
11657 add_error (std::move (error));
11658
11659 return nullptr;
11660 }
11661
11662 return std::unique_ptr<AST::StructExprFieldIdentifierValue> (
11663 new AST::StructExprFieldIdentifierValue (std::move (ident),
11664 std::move (expr),
11665 std::move (outer_attrs),
11666 t->get_locus ()));
11667 }
11668 else
11669 {
11670 // struct expr field with identifier only
11671 Identifier ident{t};
11672 lexer.skip_token ();
11673
11674 return std::unique_ptr<AST::StructExprFieldIdentifier> (
11675 new AST::StructExprFieldIdentifier (std::move (ident),
11676 std::move (outer_attrs),
11677 t->get_locus ()));
11678 }
11679 case INT_LITERAL: {
11680 // parse tuple index field
11681 int index = atoi (t->get_str ().c_str ());
11682 lexer.skip_token ();
11683
11684 if (!skip_token (COLON))
11685 {
11686 // skip somewhere?
11687 return nullptr;
11688 }
11689
11690 // parse field expression (required)
11691 std::unique_ptr<AST::Expr> expr = parse_expr ();
11692 if (expr == nullptr)
11693 {
11694 Error error (t->get_locus (),
11695 "failed to parse expr in struct (or enum) expr "
11696 "field with tuple index");
11697 add_error (std::move (error));
11698
11699 return nullptr;
11700 }
11701
11702 return std::unique_ptr<AST::StructExprFieldIndexValue> (
11703 new AST::StructExprFieldIndexValue (index, std::move (expr),
11704 std::move (outer_attrs),
11705 t->get_locus ()));
11706 }
11707 case DOT_DOT:
11708 /* this is a struct base and can't be parsed here, so just return
11709 * nothing without erroring */
11710
11711 return nullptr;
11712 default:
11713 add_error (
11714 Error (t->get_locus (),
11715 "unrecognised token %qs as first token of struct expr field - "
11716 "expected identifier or integer literal",
11717 t->get_token_description ()));
11718
11719 return nullptr;
11720 }
11721 }
11722
11723 // "Unexpected token" panic mode - flags gcc error at unexpected token
11724 template <typename ManagedTokenSource>
11725 void
11726 Parser<ManagedTokenSource>::unexpected_token (const_TokenPtr t)
11727 {
11728 Error error (t->get_locus (), "unexpected token %qs\n",
11729 t->get_token_description ());
11730 add_error (std::move (error));
11731 }
11732
11733 /* Crappy "error recovery" performed after error by skipping tokens until a
11734 * semi-colon is found */
11735 template <typename ManagedTokenSource>
11736 void
11737 Parser<ManagedTokenSource>::skip_after_semicolon ()
11738 {
11739 const_TokenPtr t = lexer.peek_token ();
11740
11741 while (t->get_id () != END_OF_FILE && t->get_id () != SEMICOLON)
11742 {
11743 lexer.skip_token ();
11744 t = lexer.peek_token ();
11745 }
11746
11747 if (t->get_id () == SEMICOLON)
11748 lexer.skip_token ();
11749 }
11750
11751 /* Skips the current token */
11752 template <typename ManagedTokenSource>
11753 void
11754 Parser<ManagedTokenSource>::skip_token ()
11755 {
11756 lexer.skip_token ();
11757 }
11758
11759 /* Checks if current token has inputted id - skips it and returns true if so,
11760 * diagnoses an error and returns false otherwise. */
11761 template <typename ManagedTokenSource>
11762 bool
11763 Parser<ManagedTokenSource>::skip_token (TokenId token_id)
11764 {
11765 return expect_token (token_id) != const_TokenPtr ();
11766 }
11767
11768 /* Checks if current token is similar to inputted token - skips it and returns
11769 * true if so, diagnoses an error and returns false otherwise. */
11770 template <typename ManagedTokenSource>
11771 bool
11772 Parser<ManagedTokenSource>::skip_token (const_TokenPtr token)
11773 {
11774 return expect_token (token) != const_TokenPtr ();
11775 }
11776
11777 /* Checks if current token has inputted id - skips it and returns true if so,
11778 * returns false otherwise without diagnosing an error */
11779 template <typename ManagedTokenSource>
11780 bool
11781 Parser<ManagedTokenSource>::maybe_skip_token (TokenId token_id)
11782 {
11783 if (lexer.peek_token ()->get_id () != token_id)
11784 return false;
11785 else
11786 return skip_token (token_id);
11787 }
11788
11789 /* Checks the current token - if id is same as expected, skips and returns it,
11790 * otherwise diagnoses error and returns null. */
11791 template <typename ManagedTokenSource>
11792 const_TokenPtr
11793 Parser<ManagedTokenSource>::expect_token (TokenId token_id)
11794 {
11795 const_TokenPtr t = lexer.peek_token ();
11796 if (t->get_id () == token_id)
11797 {
11798 lexer.skip_token ();
11799 return t;
11800 }
11801 else
11802 {
11803 Error error (t->get_locus (), "expecting %qs but %qs found",
11804 get_token_description (token_id),
11805 t->get_token_description ());
11806 add_error (std::move (error));
11807
11808 return const_TokenPtr ();
11809 }
11810 }
11811
11812 /* Checks the current token - if same as expected, skips and returns it,
11813 * otherwise diagnoses error and returns null. */
11814 template <typename ManagedTokenSource>
11815 const_TokenPtr
11816 Parser<ManagedTokenSource>::expect_token (const_TokenPtr token_expect)
11817 {
11818 const_TokenPtr t = lexer.peek_token ();
11819 if (t->get_id () == token_expect->get_id ()
11820 && (!t->should_have_str () || t->get_str () == token_expect->get_str ()))
11821 {
11822 lexer.skip_token ();
11823 return t;
11824 }
11825 else
11826 {
11827 Error error (t->get_locus (), "expecting %qs but %qs found",
11828 token_expect->get_token_description (),
11829 t->get_token_description ());
11830 add_error (std::move (error));
11831
11832 return const_TokenPtr ();
11833 }
11834 }
11835
11836 // Skips all tokens until EOF or }. Don't use.
11837 template <typename ManagedTokenSource>
11838 void
11839 Parser<ManagedTokenSource>::skip_after_end ()
11840 {
11841 const_TokenPtr t = lexer.peek_token ();
11842
11843 while (t->get_id () != END_OF_FILE && t->get_id () != RIGHT_CURLY)
11844 {
11845 lexer.skip_token ();
11846 t = lexer.peek_token ();
11847 }
11848
11849 if (t->get_id () == RIGHT_CURLY)
11850 {
11851 lexer.skip_token ();
11852 }
11853 }
11854
11855 /* A slightly more aware error-handler that skips all tokens until it reaches
11856 * the end of the block scope (i.e. when left curly brackets = right curly
11857 * brackets). Note: assumes currently in the middle of a block. Use
11858 * skip_after_next_block to skip based on the assumption that the block
11859 * has not been entered yet. */
11860 template <typename ManagedTokenSource>
11861 void
11862 Parser<ManagedTokenSource>::skip_after_end_block ()
11863 {
11864 const_TokenPtr t = lexer.peek_token ();
11865 int curly_count = 1;
11866
11867 while (curly_count > 0 && t->get_id () != END_OF_FILE)
11868 {
11869 switch (t->get_id ())
11870 {
11871 case LEFT_CURLY:
11872 curly_count++;
11873 break;
11874 case RIGHT_CURLY:
11875 curly_count--;
11876 break;
11877 default:
11878 break;
11879 }
11880 lexer.skip_token ();
11881 t = lexer.peek_token ();
11882 }
11883 }
11884
11885 /* Skips tokens until the end of the next block. i.e. assumes that the block
11886 * has not been entered yet. */
11887 template <typename ManagedTokenSource>
11888 void
11889 Parser<ManagedTokenSource>::skip_after_next_block ()
11890 {
11891 const_TokenPtr t = lexer.peek_token ();
11892
11893 // initial loop - skip until EOF if no left curlies encountered
11894 while (t->get_id () != END_OF_FILE && t->get_id () != LEFT_CURLY)
11895 {
11896 lexer.skip_token ();
11897
11898 t = lexer.peek_token ();
11899 }
11900
11901 // if next token is left, skip it and then skip after the block ends
11902 if (t->get_id () == LEFT_CURLY)
11903 {
11904 lexer.skip_token ();
11905
11906 skip_after_end_block ();
11907 }
11908 // otherwise, do nothing as EOF
11909 }
11910
11911 /* Skips all tokens until ] (the end of an attribute) - does not skip the ]
11912 * (as designed for attribute body use) */
11913 template <typename ManagedTokenSource>
11914 void
11915 Parser<ManagedTokenSource>::skip_after_end_attribute ()
11916 {
11917 const_TokenPtr t = lexer.peek_token ();
11918
11919 while (t->get_id () != RIGHT_SQUARE)
11920 {
11921 lexer.skip_token ();
11922 t = lexer.peek_token ();
11923 }
11924
11925 // Don't skip the RIGHT_SQUARE token
11926 }
11927
11928 /* Pratt parser impl of parse_expr. FIXME: this is only provisional and
11929 * probably will be changed. */
11930 template <typename ManagedTokenSource>
11931 std::unique_ptr<AST::Expr>
11932 Parser<ManagedTokenSource>::parse_expr (int right_binding_power,
11933 AST::AttrVec outer_attrs,
11934 ParseRestrictions restrictions)
11935 {
11936 const_TokenPtr current_token = lexer.peek_token ();
11937 // Special hack because we are allowed to return nullptr, in that case we
11938 // don't want to skip the token, since we don't actually parse it. But if
11939 // null isn't allowed it indicates an error, and we want to skip past that.
11940 // So return early if it is one of the tokens that ends an expression
11941 // (or at least cannot start a new expression).
11942 if (restrictions.expr_can_be_null)
11943 {
11944 TokenId id = current_token->get_id ();
11945 if (id == SEMICOLON || id == RIGHT_PAREN || id == RIGHT_CURLY
11946 || id == RIGHT_SQUARE || id == COMMA || id == LEFT_CURLY)
11947 return nullptr;
11948 }
11949
11950 if (current_token->get_id () == LEFT_SHIFT)
11951 {
11952 lexer.split_current_token (LEFT_ANGLE, LEFT_ANGLE);
11953 current_token = lexer.peek_token ();
11954 }
11955
11956 lexer.skip_token ();
11957
11958 ParseRestrictions null_denotation_restrictions = restrictions;
11959 null_denotation_restrictions.expr_can_be_stmt = false;
11960
11961 // parse null denotation (unary part of expression)
11962 std::unique_ptr<AST::Expr> expr
11963 = null_denotation (current_token, {}, null_denotation_restrictions);
11964
11965 return left_denotations (std::move (expr), right_binding_power,
11966 std::move (outer_attrs), restrictions);
11967 }
11968
11969 template <typename ManagedTokenSource>
11970 std::unique_ptr<AST::Expr>
11971 Parser<ManagedTokenSource>::left_denotations (std::unique_ptr<AST::Expr> expr,
11972 int right_binding_power,
11973 AST::AttrVec outer_attrs,
11974 ParseRestrictions restrictions)
11975 {
11976 if (expr == nullptr)
11977 {
11978 // DEBUG
11979 rust_debug ("null denotation is null; returning null for parse_expr");
11980 return nullptr;
11981 }
11982
11983 const_TokenPtr current_token = lexer.peek_token ();
11984
11985 if (restrictions.expr_can_be_stmt && !expr->is_expr_without_block ()
11986 && current_token->get_id () != DOT
11987 && current_token->get_id () != QUESTION_MARK)
11988 {
11989 rust_debug ("statement expression with block");
11990 expr->set_outer_attrs (std::move (outer_attrs));
11991 return expr;
11992 }
11993
11994 restrictions.expr_can_be_stmt = false;
11995
11996 // stop parsing if find lower priority token - parse higher priority first
11997 while (right_binding_power < left_binding_power (current_token))
11998 {
11999 lexer.skip_token ();
12000
12001 // FIXME attributes should generally be applied to the null denotation.
12002 expr = left_denotation (current_token, std::move (expr),
12003 std::move (outer_attrs), restrictions);
12004
12005 if (expr == nullptr)
12006 {
12007 // DEBUG
12008 rust_debug ("left denotation is null; returning null for parse_expr");
12009
12010 return nullptr;
12011 }
12012
12013 current_token = lexer.peek_token ();
12014 }
12015
12016 return expr;
12017 }
12018
12019 // Parse expression with lowest left binding power.
12020 template <typename ManagedTokenSource>
12021 std::unique_ptr<AST::Expr>
12022 Parser<ManagedTokenSource>::parse_expr (AST::AttrVec outer_attrs,
12023 ParseRestrictions restrictions)
12024 {
12025 return parse_expr (LBP_LOWEST, std::move (outer_attrs), restrictions);
12026 }
12027
12028 /* Determines action to take when finding token at beginning of expression. */
12029 template <typename ManagedTokenSource>
12030 std::unique_ptr<AST::Expr>
12031 Parser<ManagedTokenSource>::null_denotation (const_TokenPtr tok,
12032 AST::AttrVec outer_attrs,
12033 ParseRestrictions restrictions)
12034 {
12035 /* note: tok is previous character in input stream, not current one, as
12036 * parse_expr skips it before passing it in */
12037
12038 /* as a Pratt parser (which works by decomposing expressions into a null
12039 * denotation and then a left denotation), null denotations handle primaries
12040 * and unary operands (but only prefix unary operands) */
12041
12042 switch (tok->get_id ())
12043 {
12044 case IDENTIFIER:
12045 case SELF:
12046 case SELF_ALIAS:
12047 case DOLLAR_SIGN:
12048 case CRATE:
12049 case SUPER: {
12050 // DEBUG
12051 rust_debug ("beginning null denotation identifier handling");
12052
12053 /* best option: parse as path, then extract identifier, macro,
12054 * struct/enum, or just path info from it */
12055 AST::PathInExpression path = parse_path_in_expression_pratt (tok);
12056
12057 return null_denotation_path (std::move (path), std::move (outer_attrs),
12058 restrictions);
12059 }
12060 case SCOPE_RESOLUTION: {
12061 // TODO: fix: this is for global paths, i.e. std::string::whatever
12062 Error error (tok->get_locus (),
12063 "found null denotation scope resolution operator, and "
12064 "have not written handling for it");
12065 add_error (std::move (error));
12066
12067 return nullptr;
12068 }
12069 default:
12070 return null_denotation_not_path (std::move (tok), std::move (outer_attrs),
12071 restrictions);
12072 }
12073 }
12074
12075 // Handling of expresions that start with a path for `null_denotation`.
12076 template <typename ManagedTokenSource>
12077 std::unique_ptr<AST::Expr>
12078 Parser<ManagedTokenSource>::null_denotation_path (
12079 AST::PathInExpression path, AST::AttrVec outer_attrs,
12080 ParseRestrictions restrictions)
12081 {
12082 rust_debug ("parsing null denotation after path");
12083
12084 // HACK: always make "self" by itself a path (regardless of next
12085 // tokens)
12086 if (path.is_single_segment () && path.get_segments ()[0].is_lower_self_seg ())
12087 {
12088 // HACK: add outer attrs to path
12089 path.set_outer_attrs (std::move (outer_attrs));
12090 return std::unique_ptr<AST::PathInExpression> (
12091 new AST::PathInExpression (std::move (path)));
12092 }
12093
12094 // branch on next token
12095 const_TokenPtr t = lexer.peek_token ();
12096 switch (t->get_id ())
12097 {
12098 case EXCLAM:
12099 // macro
12100 return parse_macro_invocation_partial (std::move (path),
12101 std::move (outer_attrs));
12102 case LEFT_CURLY: {
12103 bool not_a_block = lexer.peek_token (1)->get_id () == IDENTIFIER
12104 && (lexer.peek_token (2)->get_id () == COMMA
12105 || (lexer.peek_token (2)->get_id () == COLON
12106 && (lexer.peek_token (4)->get_id () == COMMA
12107 || !can_tok_start_type (
12108 lexer.peek_token (3)->get_id ()))));
12109
12110 /* definitely not a block:
12111 * path '{' ident ','
12112 * path '{' ident ':' [anything] ','
12113 * path '{' ident ':' [not a type]
12114 * otherwise, assume block expr and thus path */
12115 // DEBUG
12116 rust_debug ("values of lookahead: '%s' '%s' '%s' '%s' ",
12117 lexer.peek_token (1)->get_token_description (),
12118 lexer.peek_token (2)->get_token_description (),
12119 lexer.peek_token (3)->get_token_description (),
12120 lexer.peek_token (4)->get_token_description ());
12121
12122 rust_debug ("can be struct expr: '%s', not a block: '%s'",
12123 restrictions.can_be_struct_expr ? "true" : "false",
12124 not_a_block ? "true" : "false");
12125
12126 // struct/enum expr struct
12127 if (!restrictions.can_be_struct_expr && !not_a_block)
12128 {
12129 // HACK: add outer attrs to path
12130 path.set_outer_attrs (std::move (outer_attrs));
12131 return std::unique_ptr<AST::PathInExpression> (
12132 new AST::PathInExpression (std::move (path)));
12133 }
12134 return parse_struct_expr_struct_partial (std::move (path),
12135 std::move (outer_attrs));
12136 }
12137 case LEFT_PAREN:
12138 // struct/enum expr tuple
12139 if (!restrictions.can_be_struct_expr)
12140 {
12141 // assume path is returned
12142 // HACK: add outer attributes to path
12143 path.set_outer_attrs (std::move (outer_attrs));
12144 return std::unique_ptr<AST::PathInExpression> (
12145 new AST::PathInExpression (std::move (path)));
12146 }
12147 return parse_struct_expr_tuple_partial (std::move (path),
12148 std::move (outer_attrs));
12149 default:
12150 // assume path is returned if not single segment
12151 if (path.is_single_segment ())
12152 {
12153 // FIXME: This should probably be returned as a path.
12154 /* HACK: may have to become permanent, but this is my current
12155 * identifier expression */
12156 return std::unique_ptr<AST::IdentifierExpr> (new AST::IdentifierExpr (
12157 path.get_segments ()[0].get_ident_segment ().as_string (), {},
12158 path.get_locus ()));
12159 }
12160 // HACK: add outer attrs to path
12161 path.set_outer_attrs (std::move (outer_attrs));
12162 return std::unique_ptr<AST::PathInExpression> (
12163 new AST::PathInExpression (std::move (path)));
12164 }
12165 rust_unreachable ();
12166 }
12167
12168 // Handling of expresions that do not start with a path for `null_denotation`.
12169 template <typename ManagedTokenSource>
12170 std::unique_ptr<AST::Expr>
12171 Parser<ManagedTokenSource>::null_denotation_not_path (
12172 const_TokenPtr tok, AST::AttrVec outer_attrs, ParseRestrictions restrictions)
12173 {
12174 switch (tok->get_id ())
12175 {
12176 // FIXME: Handle in null_denotation_path?
12177 case LEFT_SHIFT:
12178 case LEFT_ANGLE: {
12179 // qualified path
12180 // HACK: add outer attrs to path
12181 AST::QualifiedPathInExpression path
12182 = parse_qualified_path_in_expression (tok->get_locus ());
12183 path.set_outer_attrs (std::move (outer_attrs));
12184 return std::unique_ptr<AST::QualifiedPathInExpression> (
12185 new AST::QualifiedPathInExpression (std::move (path)));
12186 }
12187 // FIXME: delegate to parse_literal_expr instead? would have to rejig
12188 // tokens and whatever.
12189 // FIXME: for literal exprs, outer attrs should be passed in, and later
12190 // error if it does not make up the entire statement.
12191 case INT_LITERAL:
12192 // we should check the range, but ignore for now
12193 // encode as int?
12194 return std::unique_ptr<AST::LiteralExpr> (
12195 new AST::LiteralExpr (tok->get_str (), AST::Literal::INT,
12196 tok->get_type_hint (), {}, tok->get_locus ()));
12197 case FLOAT_LITERAL:
12198 // encode as float?
12199 return std::unique_ptr<AST::LiteralExpr> (
12200 new AST::LiteralExpr (tok->get_str (), AST::Literal::FLOAT,
12201 tok->get_type_hint (), {}, tok->get_locus ()));
12202 case STRING_LITERAL:
12203 return std::unique_ptr<AST::LiteralExpr> (
12204 new AST::LiteralExpr (tok->get_str (), AST::Literal::STRING,
12205 tok->get_type_hint (), {}, tok->get_locus ()));
12206 case BYTE_STRING_LITERAL:
12207 return std::unique_ptr<AST::LiteralExpr> (
12208 new AST::LiteralExpr (tok->get_str (), AST::Literal::BYTE_STRING,
12209 tok->get_type_hint (), {}, tok->get_locus ()));
12210 case RAW_STRING_LITERAL:
12211 return std::unique_ptr<AST::LiteralExpr> (
12212 new AST::LiteralExpr (tok->get_str (), AST::Literal::RAW_STRING,
12213 tok->get_type_hint (), {}, tok->get_locus ()));
12214 case CHAR_LITERAL:
12215 return std::unique_ptr<AST::LiteralExpr> (
12216 new AST::LiteralExpr (tok->get_str (), AST::Literal::CHAR,
12217 tok->get_type_hint (), {}, tok->get_locus ()));
12218 case BYTE_CHAR_LITERAL:
12219 return std::unique_ptr<AST::LiteralExpr> (
12220 new AST::LiteralExpr (tok->get_str (), AST::Literal::BYTE,
12221 tok->get_type_hint (), {}, tok->get_locus ()));
12222 case TRUE_LITERAL:
12223 return std::unique_ptr<AST::LiteralExpr> (
12224 new AST::LiteralExpr (Values::Keywords::TRUE_LITERAL,
12225 AST::Literal::BOOL, tok->get_type_hint (), {},
12226 tok->get_locus ()));
12227 case FALSE_LITERAL:
12228 return std::unique_ptr<AST::LiteralExpr> (
12229 new AST::LiteralExpr (Values::Keywords::FALSE_LITERAL,
12230 AST::Literal::BOOL, tok->get_type_hint (), {},
12231 tok->get_locus ()));
12232 case LEFT_PAREN:
12233 return parse_grouped_or_tuple_expr (std::move (outer_attrs),
12234 tok->get_locus ());
12235
12236 /*case PLUS: { // unary plus operator
12237 // invoke parse_expr recursively with appropriate priority, etc. for
12238 below AST::Expr* expr = parse_expr(LBP_UNARY_PLUS);
12239
12240 if (expr == nullptr)
12241 return nullptr;
12242 // can only apply to integer and float expressions
12243 if (expr->get_type() != integer_type_node || expr->get_type() !=
12244 float_type_node) { rust_error_at(tok->get_locus(), "operand of unary
12245 plus must be int or float but it is %s", print_type(expr->get_type()));
12246 return nullptr;
12247 }
12248
12249 return Tree(expr, tok->get_locus());
12250 }*/
12251 // Rust has no unary plus operator
12252 case MINUS: { // unary minus
12253 ParseRestrictions entered_from_unary;
12254 entered_from_unary.entered_from_unary = true;
12255 if (!restrictions.can_be_struct_expr)
12256 entered_from_unary.can_be_struct_expr = false;
12257 std::unique_ptr<AST::Expr> expr
12258 = parse_expr (LBP_UNARY_MINUS, {}, entered_from_unary);
12259
12260 if (expr == nullptr)
12261 return nullptr;
12262 // can only apply to integer and float expressions
12263 /*if (expr.get_type() != integer_type_node || expr.get_type() !=
12264 float_type_node) { rust_error_at(tok->get_locus(), "operand of unary
12265 minus must be int or float but it is %s",
12266 print_type(expr.get_type())); return Tree::error();
12267 }*/
12268 /* FIXME: when implemented the "get type" method on expr, ensure it is
12269 * int or float type (except unsigned int). Actually, this would
12270 * probably have to be done in semantic analysis (as type checking).
12271 */
12272
12273 /* FIXME: allow outer attributes on these expressions by having an
12274 * outer attrs parameter in function*/
12275 return std::unique_ptr<AST::NegationExpr> (
12276 new AST::NegationExpr (std::move (expr), NegationOperator::NEGATE,
12277 std::move (outer_attrs), tok->get_locus ()));
12278 }
12279 case EXCLAM: { // logical or bitwise not
12280 ParseRestrictions entered_from_unary;
12281 entered_from_unary.entered_from_unary = true;
12282 if (!restrictions.can_be_struct_expr)
12283 entered_from_unary.can_be_struct_expr = false;
12284 std::unique_ptr<AST::Expr> expr
12285 = parse_expr (LBP_UNARY_EXCLAM, {}, entered_from_unary);
12286
12287 if (expr == nullptr)
12288 return nullptr;
12289 // can only apply to boolean expressions
12290 /*if (expr.get_type() != boolean_type_node) {
12291 rust_error_at(tok->get_locus(),
12292 "operand of logical not must be a boolean but it is %s",
12293 print_type(expr.get_type()));
12294 return Tree::error();
12295 }*/
12296 /* FIXME: type checking for boolean or integer expressions in semantic
12297 * analysis */
12298
12299 // FIXME: allow outer attributes on these expressions
12300 return std::unique_ptr<AST::NegationExpr> (
12301 new AST::NegationExpr (std::move (expr), NegationOperator::NOT,
12302 std::move (outer_attrs), tok->get_locus ()));
12303 }
12304 case ASTERISK: {
12305 /* pointer dereference only - HACK: as struct expressions should
12306 * always be value expressions, cannot be dereferenced */
12307 ParseRestrictions entered_from_unary;
12308 entered_from_unary.entered_from_unary = true;
12309 entered_from_unary.can_be_struct_expr = false;
12310 std::unique_ptr<AST::Expr> expr
12311 = parse_expr (LBP_UNARY_ASTERISK, {}, entered_from_unary);
12312 // FIXME: allow outer attributes on expression
12313 return std::unique_ptr<AST::DereferenceExpr> (
12314 new AST::DereferenceExpr (std::move (expr), std::move (outer_attrs),
12315 tok->get_locus ()));
12316 }
12317 case AMP: {
12318 // (single) "borrow" expression - shared (mutable) or immutable
12319 std::unique_ptr<AST::Expr> expr = nullptr;
12320 Mutability mutability = Mutability::Imm;
12321 bool raw_borrow = false;
12322
12323 ParseRestrictions entered_from_unary;
12324 entered_from_unary.entered_from_unary = true;
12325 if (!restrictions.can_be_struct_expr)
12326 entered_from_unary.can_be_struct_expr = false;
12327
12328 auto is_mutability = [] (const_TokenPtr token) {
12329 return token->get_id () == CONST || token->get_id () == MUT;
12330 };
12331
12332 auto t = lexer.peek_token ();
12333 // Weak raw keyword, we look (1) ahead and treat it as an identifier if
12334 // there is no mut nor const.
12335 if (t->get_id () == IDENTIFIER
12336 && t->get_str () == Values::WeakKeywords::RAW
12337 && is_mutability (lexer.peek_token (1)))
12338 {
12339 lexer.skip_token ();
12340 switch (lexer.peek_token ()->get_id ())
12341 {
12342 case MUT:
12343 mutability = Mutability::Mut;
12344 break;
12345 case CONST:
12346 mutability = Mutability::Imm;
12347 break;
12348 default:
12349 rust_error_at (lexer.peek_token ()->get_locus (),
12350 "raw borrow should be either const or mut");
12351 }
12352 lexer.skip_token ();
12353 expr = parse_expr (LBP_UNARY_AMP_MUT, {}, entered_from_unary);
12354 raw_borrow = true;
12355 }
12356 else if (t->get_id () == MUT)
12357 {
12358 lexer.skip_token ();
12359 expr = parse_expr (LBP_UNARY_AMP_MUT, {}, entered_from_unary);
12360 mutability = Mutability::Mut;
12361 raw_borrow = false;
12362 }
12363 else
12364 {
12365 expr = parse_expr (LBP_UNARY_AMP, {}, entered_from_unary);
12366 raw_borrow = false;
12367 }
12368
12369 // FIXME: allow outer attributes on expression
12370 return std::unique_ptr<AST::BorrowExpr> (
12371 new AST::BorrowExpr (std::move (expr), mutability, raw_borrow, false,
12372 std::move (outer_attrs), tok->get_locus ()));
12373 }
12374 case LOGICAL_AND: {
12375 // (double) "borrow" expression - shared (mutable) or immutable
12376 std::unique_ptr<AST::Expr> expr = nullptr;
12377 Mutability mutability = Mutability::Imm;
12378
12379 ParseRestrictions entered_from_unary;
12380 entered_from_unary.entered_from_unary = true;
12381
12382 if (lexer.peek_token ()->get_id () == MUT)
12383 {
12384 lexer.skip_token ();
12385 expr = parse_expr (LBP_UNARY_AMP_MUT, {}, entered_from_unary);
12386 mutability = Mutability::Mut;
12387 }
12388 else
12389 {
12390 expr = parse_expr (LBP_UNARY_AMP, {}, entered_from_unary);
12391 mutability = Mutability::Imm;
12392 }
12393
12394 // FIXME: allow outer attributes on expression
12395 return std::unique_ptr<AST::BorrowExpr> (
12396 new AST::BorrowExpr (std::move (expr), mutability, false, true,
12397 std::move (outer_attrs), tok->get_locus ()));
12398 }
12399 case OR:
12400 case PIPE:
12401 case MOVE:
12402 // closure expression
12403 return parse_closure_expr_pratt (tok, std::move (outer_attrs));
12404 case DOT_DOT:
12405 // either "range to" or "range full" expressions
12406 return parse_nud_range_exclusive_expr (tok, std::move (outer_attrs));
12407 case DOT_DOT_EQ:
12408 // range to inclusive expr
12409 return parse_range_to_inclusive_expr (tok, std::move (outer_attrs));
12410 case RETURN_KW:
12411 // FIXME: is this really a null denotation expression?
12412 return parse_return_expr (std::move (outer_attrs), tok->get_locus ());
12413 case BREAK:
12414 // FIXME: is this really a null denotation expression?
12415 return parse_break_expr (std::move (outer_attrs), tok->get_locus ());
12416 case CONTINUE:
12417 return parse_continue_expr (std::move (outer_attrs), tok->get_locus ());
12418 case LEFT_CURLY:
12419 // ok - this is an expression with block for once.
12420 return parse_block_expr (std::move (outer_attrs), tl::nullopt,
12421 tok->get_locus ());
12422 case IF:
12423 // if or if let, so more lookahead to find out
12424 if (lexer.peek_token ()->get_id () == LET)
12425 {
12426 // if let expr
12427 return parse_if_let_expr (std::move (outer_attrs), tok->get_locus ());
12428 }
12429 else
12430 {
12431 // if expr
12432 return parse_if_expr (std::move (outer_attrs), tok->get_locus ());
12433 }
12434 case LIFETIME:
12435 return parse_labelled_loop_expr (tok, std::move (outer_attrs));
12436 case LOOP:
12437 return parse_loop_expr (std::move (outer_attrs), tl::nullopt,
12438 tok->get_locus ());
12439 case WHILE:
12440 if (lexer.peek_token ()->get_id () == LET)
12441 {
12442 return parse_while_let_loop_expr (std::move (outer_attrs));
12443 }
12444 else
12445 {
12446 return parse_while_loop_expr (std::move (outer_attrs), tl::nullopt,
12447 tok->get_locus ());
12448 }
12449 case FOR:
12450 return parse_for_loop_expr (std::move (outer_attrs), tl::nullopt);
12451 case MATCH_KW:
12452 // also an expression with block
12453 return parse_match_expr (std::move (outer_attrs), tok->get_locus ());
12454 case LEFT_SQUARE:
12455 // array definition expr (not indexing)
12456 return parse_array_expr (std::move (outer_attrs), tok->get_locus ());
12457 case UNSAFE:
12458 return parse_unsafe_block_expr (std::move (outer_attrs),
12459 tok->get_locus ());
12460 case BOX:
12461 return parse_box_expr (std::move (outer_attrs), tok->get_locus ());
12462 case UNDERSCORE:
12463 add_error (
12464 Error (tok->get_locus (),
12465 "use of %qs is not allowed on the right-side of an assignment",
12466 tok->get_token_description ()));
12467 return nullptr;
12468 default:
12469 if (!restrictions.expr_can_be_null)
12470 add_error (Error (tok->get_locus (),
12471 "found unexpected token %qs in null denotation",
12472 tok->get_token_description ()));
12473 return nullptr;
12474 }
12475 }
12476
12477 /* Called for each token that can appear in infix (between) position. Can be
12478 * operators or other punctuation. Returns a function pointer to member
12479 * function that implements the left denotation for the token given. */
12480 template <typename ManagedTokenSource>
12481 std::unique_ptr<AST::Expr>
12482 Parser<ManagedTokenSource>::left_denotation (const_TokenPtr tok,
12483 std::unique_ptr<AST::Expr> left,
12484 AST::AttrVec outer_attrs,
12485 ParseRestrictions restrictions)
12486 {
12487 // Token passed in has already been skipped, so peek gives "next" token
12488 switch (tok->get_id ())
12489 {
12490 // FIXME: allow for outer attributes to be applied
12491 case QUESTION_MARK: {
12492 location_t left_locus = left->get_locus ();
12493 // error propagation expression - unary postfix
12494 return std::unique_ptr<AST::ErrorPropagationExpr> (
12495 new AST::ErrorPropagationExpr (std::move (left),
12496 std::move (outer_attrs), left_locus));
12497 }
12498 case PLUS:
12499 // sum expression - binary infix
12500 /*return parse_binary_plus_expr (tok, std::move (left),
12501 std::move (outer_attrs), restrictions);*/
12502 return parse_arithmetic_or_logical_expr (tok, std::move (left),
12503 std::move (outer_attrs),
12504 ArithmeticOrLogicalOperator::ADD,
12505 restrictions);
12506 case MINUS:
12507 // difference expression - binary infix
12508 /*return parse_binary_minus_expr (tok, std::move (left),
12509 std::move (outer_attrs),
12510 restrictions);*/
12511 return parse_arithmetic_or_logical_expr (
12512 tok, std::move (left), std::move (outer_attrs),
12513 ArithmeticOrLogicalOperator::SUBTRACT, restrictions);
12514 case ASTERISK:
12515 // product expression - binary infix
12516 /*return parse_binary_mult_expr (tok, std::move (left),
12517 std::move (outer_attrs), restrictions);*/
12518 return parse_arithmetic_or_logical_expr (
12519 tok, std::move (left), std::move (outer_attrs),
12520 ArithmeticOrLogicalOperator::MULTIPLY, restrictions);
12521 case DIV:
12522 // quotient expression - binary infix
12523 /*return parse_binary_div_expr (tok, std::move (left),
12524 std::move (outer_attrs), restrictions);*/
12525 return parse_arithmetic_or_logical_expr (
12526 tok, std::move (left), std::move (outer_attrs),
12527 ArithmeticOrLogicalOperator::DIVIDE, restrictions);
12528 case PERCENT:
12529 // modulo expression - binary infix
12530 /*return parse_binary_mod_expr (tok, std::move (left),
12531 std::move (outer_attrs), restrictions);*/
12532 return parse_arithmetic_or_logical_expr (
12533 tok, std::move (left), std::move (outer_attrs),
12534 ArithmeticOrLogicalOperator::MODULUS, restrictions);
12535 case AMP:
12536 // logical or bitwise and expression - binary infix
12537 /*return parse_bitwise_and_expr (tok, std::move (left),
12538 std::move (outer_attrs), restrictions);*/
12539 return parse_arithmetic_or_logical_expr (
12540 tok, std::move (left), std::move (outer_attrs),
12541 ArithmeticOrLogicalOperator::BITWISE_AND, restrictions);
12542 case PIPE:
12543 // logical or bitwise or expression - binary infix
12544 /*return parse_bitwise_or_expr (tok, std::move (left),
12545 std::move (outer_attrs), restrictions);*/
12546 return parse_arithmetic_or_logical_expr (
12547 tok, std::move (left), std::move (outer_attrs),
12548 ArithmeticOrLogicalOperator::BITWISE_OR, restrictions);
12549 case CARET:
12550 // logical or bitwise xor expression - binary infix
12551 /*return parse_bitwise_xor_expr (tok, std::move (left),
12552 std::move (outer_attrs), restrictions);*/
12553 return parse_arithmetic_or_logical_expr (
12554 tok, std::move (left), std::move (outer_attrs),
12555 ArithmeticOrLogicalOperator::BITWISE_XOR, restrictions);
12556 case LEFT_SHIFT:
12557 // left shift expression - binary infix
12558 /*return parse_left_shift_expr (tok, std::move (left),
12559 std::move (outer_attrs), restrictions);*/
12560 return parse_arithmetic_or_logical_expr (
12561 tok, std::move (left), std::move (outer_attrs),
12562 ArithmeticOrLogicalOperator::LEFT_SHIFT, restrictions);
12563 case RIGHT_SHIFT:
12564 // right shift expression - binary infix
12565 /*return parse_right_shift_expr (tok, std::move (left),
12566 std::move (outer_attrs), restrictions);*/
12567 return parse_arithmetic_or_logical_expr (
12568 tok, std::move (left), std::move (outer_attrs),
12569 ArithmeticOrLogicalOperator::RIGHT_SHIFT, restrictions);
12570 case EQUAL_EQUAL:
12571 // equal to expression - binary infix (no associativity)
12572 /*return parse_binary_equal_expr (tok, std::move (left),
12573 std::move (outer_attrs),
12574 restrictions);*/
12575 return parse_comparison_expr (tok, std::move (left),
12576 std::move (outer_attrs),
12577 ComparisonOperator::EQUAL, restrictions);
12578 case NOT_EQUAL:
12579 // not equal to expression - binary infix (no associativity)
12580 /*return parse_binary_not_equal_expr (tok, std::move (left),
12581 std::move (outer_attrs),
12582 restrictions);*/
12583 return parse_comparison_expr (tok, std::move (left),
12584 std::move (outer_attrs),
12585 ComparisonOperator::NOT_EQUAL,
12586 restrictions);
12587 case RIGHT_ANGLE:
12588 // greater than expression - binary infix (no associativity)
12589 /*return parse_binary_greater_than_expr (tok, std::move (left),
12590 std::move (outer_attrs),
12591 restrictions);*/
12592 return parse_comparison_expr (tok, std::move (left),
12593 std::move (outer_attrs),
12594 ComparisonOperator::GREATER_THAN,
12595 restrictions);
12596 case LEFT_ANGLE:
12597 // less than expression - binary infix (no associativity)
12598 /*return parse_binary_less_than_expr (tok, std::move (left),
12599 std::move (outer_attrs),
12600 restrictions);*/
12601 return parse_comparison_expr (tok, std::move (left),
12602 std::move (outer_attrs),
12603 ComparisonOperator::LESS_THAN,
12604 restrictions);
12605 case GREATER_OR_EQUAL:
12606 // greater than or equal to expression - binary infix (no associativity)
12607 /*return parse_binary_greater_equal_expr (tok, std::move (left),
12608 std::move (outer_attrs),
12609 restrictions);*/
12610 return parse_comparison_expr (tok, std::move (left),
12611 std::move (outer_attrs),
12612 ComparisonOperator::GREATER_OR_EQUAL,
12613 restrictions);
12614 case LESS_OR_EQUAL:
12615 // less than or equal to expression - binary infix (no associativity)
12616 /*return parse_binary_less_equal_expr (tok, std::move (left),
12617 std::move (outer_attrs),
12618 restrictions);*/
12619 return parse_comparison_expr (tok, std::move (left),
12620 std::move (outer_attrs),
12621 ComparisonOperator::LESS_OR_EQUAL,
12622 restrictions);
12623 case OR:
12624 // lazy logical or expression - binary infix
12625 return parse_lazy_or_expr (tok, std::move (left), std::move (outer_attrs),
12626 restrictions);
12627 case LOGICAL_AND:
12628 // lazy logical and expression - binary infix
12629 return parse_lazy_and_expr (tok, std::move (left),
12630 std::move (outer_attrs), restrictions);
12631 case AS:
12632 /* type cast expression - kind of binary infix (RHS is actually a
12633 * TypeNoBounds) */
12634 return parse_type_cast_expr (tok, std::move (left),
12635 std::move (outer_attrs), restrictions);
12636 case EQUAL:
12637 // assignment expression - binary infix (note right-to-left
12638 // associativity)
12639 return parse_assig_expr (tok, std::move (left), std::move (outer_attrs),
12640 restrictions);
12641 case PLUS_EQ:
12642 /* plus-assignment expression - binary infix (note right-to-left
12643 * associativity) */
12644 /*return parse_plus_assig_expr (tok, std::move (left),
12645 std::move (outer_attrs), restrictions);*/
12646 return parse_compound_assignment_expr (tok, std::move (left),
12647 std::move (outer_attrs),
12648 CompoundAssignmentOperator::ADD,
12649 restrictions);
12650 case MINUS_EQ:
12651 /* minus-assignment expression - binary infix (note right-to-left
12652 * associativity) */
12653 /*return parse_minus_assig_expr (tok, std::move (left),
12654 std::move (outer_attrs), restrictions);*/
12655 return parse_compound_assignment_expr (
12656 tok, std::move (left), std::move (outer_attrs),
12657 CompoundAssignmentOperator::SUBTRACT, restrictions);
12658 case ASTERISK_EQ:
12659 /* multiply-assignment expression - binary infix (note right-to-left
12660 * associativity) */
12661 /*return parse_mult_assig_expr (tok, std::move (left),
12662 std::move (outer_attrs), restrictions);*/
12663 return parse_compound_assignment_expr (
12664 tok, std::move (left), std::move (outer_attrs),
12665 CompoundAssignmentOperator::MULTIPLY, restrictions);
12666 case DIV_EQ:
12667 /* division-assignment expression - binary infix (note right-to-left
12668 * associativity) */
12669 /*return parse_div_assig_expr (tok, std::move (left),
12670 std::move (outer_attrs), restrictions);*/
12671 return parse_compound_assignment_expr (tok, std::move (left),
12672 std::move (outer_attrs),
12673 CompoundAssignmentOperator::DIVIDE,
12674 restrictions);
12675 case PERCENT_EQ:
12676 /* modulo-assignment expression - binary infix (note right-to-left
12677 * associativity) */
12678 /*return parse_mod_assig_expr (tok, std::move (left),
12679 std::move (outer_attrs), restrictions);*/
12680 return parse_compound_assignment_expr (
12681 tok, std::move (left), std::move (outer_attrs),
12682 CompoundAssignmentOperator::MODULUS, restrictions);
12683 case AMP_EQ:
12684 /* bitwise and-assignment expression - binary infix (note right-to-left
12685 * associativity) */
12686 /*return parse_and_assig_expr (tok, std::move (left),
12687 std::move (outer_attrs), restrictions);*/
12688 return parse_compound_assignment_expr (
12689 tok, std::move (left), std::move (outer_attrs),
12690 CompoundAssignmentOperator::BITWISE_AND, restrictions);
12691 case PIPE_EQ:
12692 /* bitwise or-assignment expression - binary infix (note right-to-left
12693 * associativity) */
12694 /*return parse_or_assig_expr (tok, std::move (left),
12695 std::move (outer_attrs), restrictions);*/
12696 return parse_compound_assignment_expr (
12697 tok, std::move (left), std::move (outer_attrs),
12698 CompoundAssignmentOperator::BITWISE_OR, restrictions);
12699 case CARET_EQ:
12700 /* bitwise xor-assignment expression - binary infix (note right-to-left
12701 * associativity) */
12702 /*return parse_xor_assig_expr (tok, std::move (left),
12703 std::move (outer_attrs), restrictions);*/
12704 return parse_compound_assignment_expr (
12705 tok, std::move (left), std::move (outer_attrs),
12706 CompoundAssignmentOperator::BITWISE_XOR, restrictions);
12707 case LEFT_SHIFT_EQ:
12708 /* left shift-assignment expression - binary infix (note right-to-left
12709 * associativity) */
12710 /*return parse_left_shift_assig_expr (tok, std::move (left),
12711 std::move (outer_attrs),
12712 restrictions);*/
12713 return parse_compound_assignment_expr (
12714 tok, std::move (left), std::move (outer_attrs),
12715 CompoundAssignmentOperator::LEFT_SHIFT, restrictions);
12716 case RIGHT_SHIFT_EQ:
12717 /* right shift-assignment expression - binary infix (note right-to-left
12718 * associativity) */
12719 /*return parse_right_shift_assig_expr (tok, std::move (left),
12720 std::move (outer_attrs),
12721 restrictions);*/
12722 return parse_compound_assignment_expr (
12723 tok, std::move (left), std::move (outer_attrs),
12724 CompoundAssignmentOperator::RIGHT_SHIFT, restrictions);
12725 case DOT_DOT:
12726 /* range exclusive expression - binary infix (no associativity)
12727 * either "range" or "range from" */
12728 return parse_led_range_exclusive_expr (tok, std::move (left),
12729 std::move (outer_attrs),
12730 restrictions);
12731 case DOT_DOT_EQ:
12732 /* range inclusive expression - binary infix (no associativity)
12733 * unambiguously RangeInclusiveExpr */
12734 return parse_range_inclusive_expr (tok, std::move (left),
12735 std::move (outer_attrs), restrictions);
12736 case SCOPE_RESOLUTION:
12737 // path expression - binary infix? FIXME should this even be parsed
12738 // here?
12739 add_error (
12740 Error (tok->get_locus (),
12741 "found scope resolution operator in left denotation "
12742 "function - this should probably be handled elsewhere"));
12743
12744 return nullptr;
12745 case DOT: {
12746 /* field expression or method call - relies on parentheses after next
12747 * identifier or await if token after is "await" (unary postfix) or
12748 * tuple index if token after is a decimal int literal */
12749
12750 const_TokenPtr next_tok = lexer.peek_token ();
12751 if (next_tok->get_id () == IDENTIFIER
12752 && next_tok->get_str () == Values::Keywords::AWAIT)
12753 {
12754 // await expression
12755 return parse_await_expr (tok, std::move (left),
12756 std::move (outer_attrs));
12757 }
12758 else if (next_tok->get_id () == INT_LITERAL)
12759 {
12760 // tuple index expression - TODO check for decimal int literal
12761 return parse_tuple_index_expr (tok, std::move (left),
12762 std::move (outer_attrs),
12763 restrictions);
12764 }
12765 else if (next_tok->get_id () == FLOAT_LITERAL)
12766 {
12767 // Lexer has misidentified a tuple index as a float literal
12768 // eg: `(x, (y, z)).1.0` -> 1.0 has been identified as a float
12769 // literal. This means we should split it into three new separate
12770 // tokens, the first tuple index, the dot and the second tuple
12771 // index.
12772 auto current_loc = next_tok->get_locus ();
12773 auto str = next_tok->get_str ();
12774 auto dot_pos = str.find (".");
12775 auto prefix = str.substr (0, dot_pos);
12776 auto suffix = str.substr (dot_pos + 1);
12777 if (dot_pos == str.size () - 1)
12778 lexer.split_current_token (
12779 {Token::make_int (current_loc, std::move (prefix),
12780 CORETYPE_PURE_DECIMAL),
12781 Token::make (DOT, current_loc + 1)});
12782 else
12783 lexer.split_current_token (
12784 {Token::make_int (current_loc, std::move (prefix),
12785 CORETYPE_PURE_DECIMAL),
12786 Token::make (DOT, current_loc + 1),
12787 Token::make_int (current_loc + 2, std::move (suffix),
12788 CORETYPE_PURE_DECIMAL)});
12789 return parse_tuple_index_expr (tok, std::move (left),
12790 std::move (outer_attrs),
12791 restrictions);
12792 }
12793 else if (next_tok->get_id () == IDENTIFIER
12794 && lexer.peek_token (1)->get_id () != LEFT_PAREN
12795 && lexer.peek_token (1)->get_id () != SCOPE_RESOLUTION)
12796 {
12797 /* field expression (or should be) - FIXME: scope resolution right
12798 * after identifier should always be method, I'm pretty sure */
12799 return parse_field_access_expr (tok, std::move (left),
12800 std::move (outer_attrs),
12801 restrictions);
12802 }
12803 else
12804 {
12805 // method call (probably)
12806 return parse_method_call_expr (tok, std::move (left),
12807 std::move (outer_attrs),
12808 restrictions);
12809 }
12810 }
12811 case LEFT_PAREN:
12812 // function call - method call is based on dot notation first
12813 return parse_function_call_expr (tok, std::move (left),
12814 std::move (outer_attrs), restrictions);
12815 case LEFT_SQUARE:
12816 // array or slice index expression (pseudo binary infix)
12817 return parse_index_expr (tok, std::move (left), std::move (outer_attrs),
12818 restrictions);
12819 case FLOAT_LITERAL:
12820 /* HACK: get around lexer mis-identifying '.0' or '.1' or whatever as a
12821 * float literal - TODO does this happen anymore? It shouldn't. */
12822 return parse_tuple_index_expr_float (tok, std::move (left),
12823 std::move (outer_attrs),
12824 restrictions);
12825 default:
12826 add_error (Error (tok->get_locus (),
12827 "found unexpected token %qs in left denotation",
12828 tok->get_token_description ()));
12829
12830 return nullptr;
12831 }
12832 }
12833
12834 /* Returns the left binding power for the given ArithmeticOrLogicalExpr type.
12835 * TODO make constexpr? Would that even do anything useful? */
12836 inline binding_powers
12837 get_lbp_for_arithmetic_or_logical_expr (
12838 AST::ArithmeticOrLogicalExpr::ExprType expr_type)
12839 {
12840 switch (expr_type)
12841 {
12842 case ArithmeticOrLogicalOperator::ADD:
12843 return LBP_PLUS;
12844 case ArithmeticOrLogicalOperator::SUBTRACT:
12845 return LBP_MINUS;
12846 case ArithmeticOrLogicalOperator::MULTIPLY:
12847 return LBP_MUL;
12848 case ArithmeticOrLogicalOperator::DIVIDE:
12849 return LBP_DIV;
12850 case ArithmeticOrLogicalOperator::MODULUS:
12851 return LBP_MOD;
12852 case ArithmeticOrLogicalOperator::BITWISE_AND:
12853 return LBP_AMP;
12854 case ArithmeticOrLogicalOperator::BITWISE_OR:
12855 return LBP_PIPE;
12856 case ArithmeticOrLogicalOperator::BITWISE_XOR:
12857 return LBP_CARET;
12858 case ArithmeticOrLogicalOperator::LEFT_SHIFT:
12859 return LBP_L_SHIFT;
12860 case ArithmeticOrLogicalOperator::RIGHT_SHIFT:
12861 return LBP_R_SHIFT;
12862 default:
12863 // WTF? should not happen, this is an error
12864 rust_unreachable ();
12865
12866 return LBP_PLUS;
12867 }
12868 }
12869
12870 // Parses an arithmetic or logical expression (with Pratt parsing).
12871 template <typename ManagedTokenSource>
12872 std::unique_ptr<AST::ArithmeticOrLogicalExpr>
12873 Parser<ManagedTokenSource>::parse_arithmetic_or_logical_expr (
12874 const_TokenPtr, std::unique_ptr<AST::Expr> left, AST::AttrVec,
12875 AST::ArithmeticOrLogicalExpr::ExprType expr_type,
12876 ParseRestrictions restrictions)
12877 {
12878 // parse RHS (as tok has already been consumed in parse_expression)
12879 std::unique_ptr<AST::Expr> right
12880 = parse_expr (get_lbp_for_arithmetic_or_logical_expr (expr_type),
12881 AST::AttrVec (), restrictions);
12882 if (right == nullptr)
12883 return nullptr;
12884
12885 // TODO: check types. actually, do so during semantic analysis
12886 location_t locus = left->get_locus ();
12887
12888 return std::unique_ptr<AST::ArithmeticOrLogicalExpr> (
12889 new AST::ArithmeticOrLogicalExpr (std::move (left), std::move (right),
12890 expr_type, locus));
12891 }
12892
12893 // Parses a binary addition expression (with Pratt parsing).
12894 template <typename ManagedTokenSource>
12895 std::unique_ptr<AST::ArithmeticOrLogicalExpr>
12896 Parser<ManagedTokenSource>::parse_binary_plus_expr (
12897 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
12898 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
12899 {
12900 // parse RHS (as tok has already been consumed in parse_expression)
12901 std::unique_ptr<AST::Expr> right
12902 = parse_expr (LBP_PLUS, AST::AttrVec (), restrictions);
12903 if (right == nullptr)
12904 return nullptr;
12905
12906 // TODO: check types. actually, do so during semantic analysis
12907 location_t locus = left->get_locus ();
12908
12909 return std::unique_ptr<AST::ArithmeticOrLogicalExpr> (
12910 new AST::ArithmeticOrLogicalExpr (std::move (left), std::move (right),
12911 ArithmeticOrLogicalOperator::ADD, locus));
12912 }
12913
12914 // Parses a binary subtraction expression (with Pratt parsing).
12915 template <typename ManagedTokenSource>
12916 std::unique_ptr<AST::ArithmeticOrLogicalExpr>
12917 Parser<ManagedTokenSource>::parse_binary_minus_expr (
12918 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
12919 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
12920 {
12921 // parse RHS (as tok has already been consumed in parse_expression)
12922 std::unique_ptr<AST::Expr> right
12923 = parse_expr (LBP_MINUS, AST::AttrVec (), restrictions);
12924 if (right == nullptr)
12925 return nullptr;
12926
12927 // TODO: check types. actually, do so during semantic analysis
12928 location_t locus = left->get_locus ();
12929
12930 return std::unique_ptr<AST::ArithmeticOrLogicalExpr> (
12931 new AST::ArithmeticOrLogicalExpr (std::move (left), std::move (right),
12932 ArithmeticOrLogicalOperator::SUBTRACT,
12933 locus));
12934 }
12935
12936 // Parses a binary multiplication expression (with Pratt parsing).
12937 template <typename ManagedTokenSource>
12938 std::unique_ptr<AST::ArithmeticOrLogicalExpr>
12939 Parser<ManagedTokenSource>::parse_binary_mult_expr (
12940 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
12941 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
12942 {
12943 // parse RHS (as tok has already been consumed in parse_expression)
12944 std::unique_ptr<AST::Expr> right
12945 = parse_expr (LBP_MUL, AST::AttrVec (), restrictions);
12946 if (right == nullptr)
12947 return nullptr;
12948
12949 // TODO: check types. actually, do so during semantic analysis
12950 location_t locus = left->get_locus ();
12951
12952 return std::unique_ptr<AST::ArithmeticOrLogicalExpr> (
12953 new AST::ArithmeticOrLogicalExpr (std::move (left), std::move (right),
12954 ArithmeticOrLogicalOperator::MULTIPLY,
12955 locus));
12956 }
12957
12958 // Parses a binary division expression (with Pratt parsing).
12959 template <typename ManagedTokenSource>
12960 std::unique_ptr<AST::ArithmeticOrLogicalExpr>
12961 Parser<ManagedTokenSource>::parse_binary_div_expr (
12962 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
12963 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
12964 {
12965 // parse RHS (as tok has already been consumed in parse_expression)
12966 std::unique_ptr<AST::Expr> right
12967 = parse_expr (LBP_DIV, AST::AttrVec (), restrictions);
12968 if (right == nullptr)
12969 return nullptr;
12970
12971 // TODO: check types. actually, do so during semantic analysis
12972 location_t locus = left->get_locus ();
12973
12974 return std::unique_ptr<AST::ArithmeticOrLogicalExpr> (
12975 new AST::ArithmeticOrLogicalExpr (std::move (left), std::move (right),
12976 ArithmeticOrLogicalOperator::DIVIDE,
12977 locus));
12978 }
12979
12980 // Parses a binary modulo expression (with Pratt parsing).
12981 template <typename ManagedTokenSource>
12982 std::unique_ptr<AST::ArithmeticOrLogicalExpr>
12983 Parser<ManagedTokenSource>::parse_binary_mod_expr (
12984 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
12985 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
12986 {
12987 // parse RHS (as tok has already been consumed in parse_expression)
12988 std::unique_ptr<AST::Expr> right
12989 = parse_expr (LBP_MOD, AST::AttrVec (), restrictions);
12990 if (right == nullptr)
12991 return nullptr;
12992
12993 // TODO: check types. actually, do so during semantic analysis
12994 location_t locus = left->get_locus ();
12995
12996 return std::unique_ptr<AST::ArithmeticOrLogicalExpr> (
12997 new AST::ArithmeticOrLogicalExpr (std::move (left), std::move (right),
12998 ArithmeticOrLogicalOperator::MODULUS,
12999 locus));
13000 }
13001
13002 /* Parses a binary bitwise (or eager logical) and expression (with Pratt
13003 * parsing). */
13004 template <typename ManagedTokenSource>
13005 std::unique_ptr<AST::ArithmeticOrLogicalExpr>
13006 Parser<ManagedTokenSource>::parse_bitwise_and_expr (
13007 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13008 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13009 {
13010 // parse RHS (as tok has already been consumed in parse_expression)
13011 std::unique_ptr<AST::Expr> right
13012 = parse_expr (LBP_AMP, AST::AttrVec (), restrictions);
13013 if (right == nullptr)
13014 return nullptr;
13015
13016 // TODO: check types. actually, do so during semantic analysis
13017 location_t locus = left->get_locus ();
13018
13019 return std::unique_ptr<AST::ArithmeticOrLogicalExpr> (
13020 new AST::ArithmeticOrLogicalExpr (std::move (left), std::move (right),
13021 ArithmeticOrLogicalOperator::BITWISE_AND,
13022 locus));
13023 }
13024
13025 /* Parses a binary bitwise (or eager logical) or expression (with Pratt
13026 * parsing). */
13027 template <typename ManagedTokenSource>
13028 std::unique_ptr<AST::ArithmeticOrLogicalExpr>
13029 Parser<ManagedTokenSource>::parse_bitwise_or_expr (
13030 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13031 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13032 {
13033 // parse RHS (as tok has already been consumed in parse_expression)
13034 std::unique_ptr<AST::Expr> right
13035 = parse_expr (LBP_PIPE, AST::AttrVec (), restrictions);
13036 if (right == nullptr)
13037 return nullptr;
13038
13039 // TODO: check types. actually, do so during semantic analysis
13040 location_t locus = left->get_locus ();
13041
13042 return std::unique_ptr<AST::ArithmeticOrLogicalExpr> (
13043 new AST::ArithmeticOrLogicalExpr (std::move (left), std::move (right),
13044 ArithmeticOrLogicalOperator::BITWISE_OR,
13045 locus));
13046 }
13047
13048 /* Parses a binary bitwise (or eager logical) xor expression (with Pratt
13049 * parsing). */
13050 template <typename ManagedTokenSource>
13051 std::unique_ptr<AST::ArithmeticOrLogicalExpr>
13052 Parser<ManagedTokenSource>::parse_bitwise_xor_expr (
13053 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13054 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13055 {
13056 // parse RHS (as tok has already been consumed in parse_expression)
13057 std::unique_ptr<AST::Expr> right
13058 = parse_expr (LBP_CARET, AST::AttrVec (), restrictions);
13059 if (right == nullptr)
13060 return nullptr;
13061
13062 // TODO: check types. actually, do so during semantic analysis
13063 location_t locus = left->get_locus ();
13064
13065 return std::unique_ptr<AST::ArithmeticOrLogicalExpr> (
13066 new AST::ArithmeticOrLogicalExpr (std::move (left), std::move (right),
13067 ArithmeticOrLogicalOperator::BITWISE_XOR,
13068 locus));
13069 }
13070
13071 // Parses a binary left shift expression (with Pratt parsing).
13072 template <typename ManagedTokenSource>
13073 std::unique_ptr<AST::ArithmeticOrLogicalExpr>
13074 Parser<ManagedTokenSource>::parse_left_shift_expr (
13075 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13076 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13077 {
13078 // parse RHS (as tok has already been consumed in parse_expression)
13079 std::unique_ptr<AST::Expr> right
13080 = parse_expr (LBP_L_SHIFT, AST::AttrVec (), restrictions);
13081 if (right == nullptr)
13082 return nullptr;
13083
13084 // TODO: check types. actually, do so during semantic analysis
13085 location_t locus = left->get_locus ();
13086
13087 return std::unique_ptr<AST::ArithmeticOrLogicalExpr> (
13088 new AST::ArithmeticOrLogicalExpr (std::move (left), std::move (right),
13089 ArithmeticOrLogicalOperator::LEFT_SHIFT,
13090 locus));
13091 }
13092
13093 // Parses a binary right shift expression (with Pratt parsing).
13094 template <typename ManagedTokenSource>
13095 std::unique_ptr<AST::ArithmeticOrLogicalExpr>
13096 Parser<ManagedTokenSource>::parse_right_shift_expr (
13097 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13098 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13099 {
13100 // parse RHS (as tok has already been consumed in parse_expression)
13101 std::unique_ptr<AST::Expr> right
13102 = parse_expr (LBP_R_SHIFT, AST::AttrVec (), restrictions);
13103 if (right == nullptr)
13104 return nullptr;
13105
13106 // TODO: check types. actually, do so during semantic analysis
13107 location_t locus = left->get_locus ();
13108
13109 return std::unique_ptr<AST::ArithmeticOrLogicalExpr> (
13110 new AST::ArithmeticOrLogicalExpr (std::move (left), std::move (right),
13111 ArithmeticOrLogicalOperator::RIGHT_SHIFT,
13112 locus));
13113 }
13114
13115 /* Returns the left binding power for the given ComparisonExpr type.
13116 * TODO make constexpr? Would that even do anything useful? */
13117 inline binding_powers
13118 get_lbp_for_comparison_expr (AST::ComparisonExpr::ExprType expr_type)
13119 {
13120 switch (expr_type)
13121 {
13122 case ComparisonOperator::EQUAL:
13123 return LBP_EQUAL;
13124 case ComparisonOperator::NOT_EQUAL:
13125 return LBP_NOT_EQUAL;
13126 case ComparisonOperator::GREATER_THAN:
13127 return LBP_GREATER_THAN;
13128 case ComparisonOperator::LESS_THAN:
13129 return LBP_SMALLER_THAN;
13130 case ComparisonOperator::GREATER_OR_EQUAL:
13131 return LBP_GREATER_EQUAL;
13132 case ComparisonOperator::LESS_OR_EQUAL:
13133 return LBP_SMALLER_EQUAL;
13134 default:
13135 // WTF? should not happen, this is an error
13136 rust_unreachable ();
13137
13138 return LBP_EQUAL;
13139 }
13140 }
13141
13142 /* Parses a ComparisonExpr of given type and LBP. TODO find a way to only
13143 * specify one and have the other looked up - e.g. specify ExprType and
13144 * binding power is looked up? */
13145 template <typename ManagedTokenSource>
13146 std::unique_ptr<AST::ComparisonExpr>
13147 Parser<ManagedTokenSource>::parse_comparison_expr (
13148 const_TokenPtr, std::unique_ptr<AST::Expr> left, AST::AttrVec,
13149 AST::ComparisonExpr::ExprType expr_type, ParseRestrictions restrictions)
13150 {
13151 // parse RHS (as tok has already been consumed in parse_expression)
13152 std::unique_ptr<AST::Expr> right
13153 = parse_expr (get_lbp_for_comparison_expr (expr_type), AST::AttrVec (),
13154 restrictions);
13155 if (right == nullptr)
13156 return nullptr;
13157
13158 // TODO: check types. actually, do so during semantic analysis
13159 location_t locus = left->get_locus ();
13160
13161 return std::unique_ptr<AST::ComparisonExpr> (
13162 new AST::ComparisonExpr (std::move (left), std::move (right), expr_type,
13163 locus));
13164 }
13165
13166 // Parses a binary equal to expression (with Pratt parsing).
13167 template <typename ManagedTokenSource>
13168 std::unique_ptr<AST::ComparisonExpr>
13169 Parser<ManagedTokenSource>::parse_binary_equal_expr (
13170 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13171 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13172 {
13173 // parse RHS (as tok has already been consumed in parse_expression)
13174 std::unique_ptr<AST::Expr> right
13175 = parse_expr (LBP_EQUAL, AST::AttrVec (), restrictions);
13176 if (right == nullptr)
13177 return nullptr;
13178
13179 // TODO: check types. actually, do so during semantic analysis
13180 location_t locus = left->get_locus ();
13181
13182 return std::unique_ptr<AST::ComparisonExpr> (
13183 new AST::ComparisonExpr (std::move (left), std::move (right),
13184 ComparisonOperator::EQUAL, locus));
13185 }
13186
13187 // Parses a binary not equal to expression (with Pratt parsing).
13188 template <typename ManagedTokenSource>
13189 std::unique_ptr<AST::ComparisonExpr>
13190 Parser<ManagedTokenSource>::parse_binary_not_equal_expr (
13191 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13192 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13193 {
13194 // parse RHS (as tok has already been consumed in parse_expression)
13195 std::unique_ptr<AST::Expr> right
13196 = parse_expr (LBP_NOT_EQUAL, AST::AttrVec (), restrictions);
13197 if (right == nullptr)
13198 return nullptr;
13199
13200 // TODO: check types. actually, do so during semantic analysis
13201 location_t locus = left->get_locus ();
13202
13203 return std::unique_ptr<AST::ComparisonExpr> (
13204 new AST::ComparisonExpr (std::move (left), std::move (right),
13205 ComparisonOperator::NOT_EQUAL, locus));
13206 }
13207
13208 // Parses a binary greater than expression (with Pratt parsing).
13209 template <typename ManagedTokenSource>
13210 std::unique_ptr<AST::ComparisonExpr>
13211 Parser<ManagedTokenSource>::parse_binary_greater_than_expr (
13212 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13213 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13214 {
13215 // parse RHS (as tok has already been consumed in parse_expression)
13216 std::unique_ptr<AST::Expr> right
13217 = parse_expr (LBP_GREATER_THAN, AST::AttrVec (), restrictions);
13218 if (right == nullptr)
13219 return nullptr;
13220
13221 // TODO: check types. actually, do so during semantic analysis
13222 location_t locus = left->get_locus ();
13223
13224 return std::unique_ptr<AST::ComparisonExpr> (
13225 new AST::ComparisonExpr (std::move (left), std::move (right),
13226 ComparisonOperator::GREATER_THAN, locus));
13227 }
13228
13229 // Parses a binary less than expression (with Pratt parsing).
13230 template <typename ManagedTokenSource>
13231 std::unique_ptr<AST::ComparisonExpr>
13232 Parser<ManagedTokenSource>::parse_binary_less_than_expr (
13233 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13234 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13235 {
13236 // parse RHS (as tok has already been consumed in parse_expression)
13237 std::unique_ptr<AST::Expr> right
13238 = parse_expr (LBP_SMALLER_THAN, AST::AttrVec (), restrictions);
13239 if (right == nullptr)
13240 return nullptr;
13241
13242 // TODO: check types. actually, do so during semantic analysis
13243 location_t locus = left->get_locus ();
13244
13245 return std::unique_ptr<AST::ComparisonExpr> (
13246 new AST::ComparisonExpr (std::move (left), std::move (right),
13247 ComparisonOperator::LESS_THAN, locus));
13248 }
13249
13250 // Parses a binary greater than or equal to expression (with Pratt parsing).
13251 template <typename ManagedTokenSource>
13252 std::unique_ptr<AST::ComparisonExpr>
13253 Parser<ManagedTokenSource>::parse_binary_greater_equal_expr (
13254 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13255 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13256 {
13257 // parse RHS (as tok has already been consumed in parse_expression)
13258 std::unique_ptr<AST::Expr> right
13259 = parse_expr (LBP_GREATER_EQUAL, AST::AttrVec (), restrictions);
13260 if (right == nullptr)
13261 return nullptr;
13262
13263 // TODO: check types. actually, do so during semantic analysis
13264 location_t locus = left->get_locus ();
13265
13266 return std::unique_ptr<AST::ComparisonExpr> (
13267 new AST::ComparisonExpr (std::move (left), std::move (right),
13268 ComparisonOperator::GREATER_OR_EQUAL, locus));
13269 }
13270
13271 // Parses a binary less than or equal to expression (with Pratt parsing).
13272 template <typename ManagedTokenSource>
13273 std::unique_ptr<AST::ComparisonExpr>
13274 Parser<ManagedTokenSource>::parse_binary_less_equal_expr (
13275 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13276 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13277 {
13278 // parse RHS (as tok has already been consumed in parse_expression)
13279 std::unique_ptr<AST::Expr> right
13280 = parse_expr (LBP_SMALLER_EQUAL, AST::AttrVec (), restrictions);
13281 if (right == nullptr)
13282 return nullptr;
13283
13284 // TODO: check types. actually, do so during semantic analysis
13285 location_t locus = left->get_locus ();
13286
13287 return std::unique_ptr<AST::ComparisonExpr> (
13288 new AST::ComparisonExpr (std::move (left), std::move (right),
13289 ComparisonOperator::LESS_OR_EQUAL, locus));
13290 }
13291
13292 // Parses a binary lazy boolean or expression (with Pratt parsing).
13293 template <typename ManagedTokenSource>
13294 std::unique_ptr<AST::LazyBooleanExpr>
13295 Parser<ManagedTokenSource>::parse_lazy_or_expr (
13296 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13297 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13298 {
13299 // parse RHS (as tok has already been consumed in parse_expression)
13300 std::unique_ptr<AST::Expr> right
13301 = parse_expr (LBP_LOGICAL_OR, AST::AttrVec (), restrictions);
13302 if (right == nullptr)
13303 return nullptr;
13304
13305 // TODO: check types. actually, do so during semantic analysis
13306 location_t locus = left->get_locus ();
13307
13308 return std::unique_ptr<AST::LazyBooleanExpr> (
13309 new AST::LazyBooleanExpr (std::move (left), std::move (right),
13310 LazyBooleanOperator::LOGICAL_OR, locus));
13311 }
13312
13313 // Parses a binary lazy boolean and expression (with Pratt parsing).
13314 template <typename ManagedTokenSource>
13315 std::unique_ptr<AST::LazyBooleanExpr>
13316 Parser<ManagedTokenSource>::parse_lazy_and_expr (
13317 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13318 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13319 {
13320 // parse RHS (as tok has already been consumed in parse_expression)
13321 std::unique_ptr<AST::Expr> right
13322 = parse_expr (LBP_LOGICAL_AND, AST::AttrVec (), restrictions);
13323 if (right == nullptr)
13324 return nullptr;
13325
13326 // TODO: check types. actually, do so during semantic analysis
13327 location_t locus = left->get_locus ();
13328
13329 return std::unique_ptr<AST::LazyBooleanExpr> (
13330 new AST::LazyBooleanExpr (std::move (left), std::move (right),
13331 LazyBooleanOperator::LOGICAL_AND, locus));
13332 }
13333
13334 // Parses a pseudo-binary infix type cast expression (with Pratt parsing).
13335 template <typename ManagedTokenSource>
13336 std::unique_ptr<AST::TypeCastExpr>
13337 Parser<ManagedTokenSource>::parse_type_cast_expr (
13338 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> expr_to_cast,
13339 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED,
13340 ParseRestrictions restrictions ATTRIBUTE_UNUSED)
13341 {
13342 // parse RHS (as tok has already been consumed in parse_expression)
13343 std::unique_ptr<AST::TypeNoBounds> type = parse_type_no_bounds ();
13344 if (type == nullptr)
13345 return nullptr;
13346 // FIXME: how do I get precedence put in here?
13347
13348 // TODO: check types. actually, do so during semantic analysis
13349 location_t locus = expr_to_cast->get_locus ();
13350
13351 return std::unique_ptr<AST::TypeCastExpr> (
13352 new AST::TypeCastExpr (std::move (expr_to_cast), std::move (type), locus));
13353 }
13354
13355 // Parses a binary assignment expression (with Pratt parsing).
13356 template <typename ManagedTokenSource>
13357 std::unique_ptr<AST::AssignmentExpr>
13358 Parser<ManagedTokenSource>::parse_assig_expr (
13359 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13360 AST::AttrVec outer_attrs, ParseRestrictions restrictions)
13361 {
13362 // parse RHS (as tok has already been consumed in parse_expression)
13363 std::unique_ptr<AST::Expr> right
13364 = parse_expr (LBP_ASSIG - 1, AST::AttrVec (), restrictions);
13365 if (right == nullptr)
13366 return nullptr;
13367 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13368
13369 // TODO: check types. actually, do so during semantic analysis
13370 location_t locus = left->get_locus ();
13371
13372 return std::unique_ptr<AST::AssignmentExpr> (
13373 new AST::AssignmentExpr (std::move (left), std::move (right),
13374 std::move (outer_attrs), locus));
13375 }
13376
13377 /* Returns the left binding power for the given CompoundAssignmentExpr type.
13378 * TODO make constexpr? Would that even do anything useful? */
13379 inline binding_powers
13380 get_lbp_for_compound_assignment_expr (
13381 AST::CompoundAssignmentExpr::ExprType expr_type)
13382 {
13383 switch (expr_type)
13384 {
13385 case CompoundAssignmentOperator::ADD:
13386 return LBP_PLUS;
13387 case CompoundAssignmentOperator::SUBTRACT:
13388 return LBP_MINUS;
13389 case CompoundAssignmentOperator::MULTIPLY:
13390 return LBP_MUL;
13391 case CompoundAssignmentOperator::DIVIDE:
13392 return LBP_DIV;
13393 case CompoundAssignmentOperator::MODULUS:
13394 return LBP_MOD;
13395 case CompoundAssignmentOperator::BITWISE_AND:
13396 return LBP_AMP;
13397 case CompoundAssignmentOperator::BITWISE_OR:
13398 return LBP_PIPE;
13399 case CompoundAssignmentOperator::BITWISE_XOR:
13400 return LBP_CARET;
13401 case CompoundAssignmentOperator::LEFT_SHIFT:
13402 return LBP_L_SHIFT;
13403 case CompoundAssignmentOperator::RIGHT_SHIFT:
13404 return LBP_R_SHIFT;
13405 default:
13406 // WTF? should not happen, this is an error
13407 rust_unreachable ();
13408
13409 return LBP_PLUS;
13410 }
13411 }
13412
13413 // Parses a compound assignment expression (with Pratt parsing).
13414 template <typename ManagedTokenSource>
13415 std::unique_ptr<AST::CompoundAssignmentExpr>
13416 Parser<ManagedTokenSource>::parse_compound_assignment_expr (
13417 const_TokenPtr, std::unique_ptr<AST::Expr> left, AST::AttrVec,
13418 AST::CompoundAssignmentExpr::ExprType expr_type,
13419 ParseRestrictions restrictions)
13420 {
13421 // parse RHS (as tok has already been consumed in parse_expression)
13422 std::unique_ptr<AST::Expr> right
13423 = parse_expr (get_lbp_for_compound_assignment_expr (expr_type) - 1,
13424 AST::AttrVec (), restrictions);
13425 if (right == nullptr)
13426 return nullptr;
13427 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13428
13429 // TODO: check types. actually, do so during semantic analysis
13430 location_t locus = left->get_locus ();
13431
13432 return std::unique_ptr<AST::CompoundAssignmentExpr> (
13433 new AST::CompoundAssignmentExpr (std::move (left), std::move (right),
13434 expr_type, locus));
13435 }
13436
13437 // Parses a binary add-assignment expression (with Pratt parsing).
13438 template <typename ManagedTokenSource>
13439 std::unique_ptr<AST::CompoundAssignmentExpr>
13440 Parser<ManagedTokenSource>::parse_plus_assig_expr (
13441 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13442 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13443 {
13444 // parse RHS (as tok has already been consumed in parse_expression)
13445 std::unique_ptr<AST::Expr> right
13446 = parse_expr (LBP_PLUS_ASSIG - 1, AST::AttrVec (), restrictions);
13447 if (right == nullptr)
13448 return nullptr;
13449 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13450
13451 // TODO: check types. actually, do so during semantic analysis
13452 location_t locus = left->get_locus ();
13453
13454 return std::unique_ptr<AST::CompoundAssignmentExpr> (
13455 new AST::CompoundAssignmentExpr (std::move (left), std::move (right),
13456 CompoundAssignmentOperator::ADD, locus));
13457 }
13458
13459 // Parses a binary minus-assignment expression (with Pratt parsing).
13460 template <typename ManagedTokenSource>
13461 std::unique_ptr<AST::CompoundAssignmentExpr>
13462 Parser<ManagedTokenSource>::parse_minus_assig_expr (
13463 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13464 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13465 {
13466 // parse RHS (as tok has already been consumed in parse_expression)
13467 std::unique_ptr<AST::Expr> right
13468 = parse_expr (LBP_MINUS_ASSIG - 1, AST::AttrVec (), restrictions);
13469 if (right == nullptr)
13470 return nullptr;
13471 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13472
13473 // TODO: check types. actually, do so during semantic analysis
13474 location_t locus = left->get_locus ();
13475
13476 return std::unique_ptr<AST::CompoundAssignmentExpr> (
13477 new AST::CompoundAssignmentExpr (std::move (left), std::move (right),
13478 CompoundAssignmentOperator::SUBTRACT,
13479 locus));
13480 }
13481
13482 // Parses a binary multiplication-assignment expression (with Pratt parsing).
13483 template <typename ManagedTokenSource>
13484 std::unique_ptr<AST::CompoundAssignmentExpr>
13485 Parser<ManagedTokenSource>::parse_mult_assig_expr (
13486 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13487 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13488 {
13489 // parse RHS (as tok has already been consumed in parse_expression)
13490 std::unique_ptr<AST::Expr> right
13491 = parse_expr (LBP_MULT_ASSIG - 1, AST::AttrVec (), restrictions);
13492 if (right == nullptr)
13493 return nullptr;
13494 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13495
13496 // TODO: check types. actually, do so during semantic analysis
13497 location_t locus = left->get_locus ();
13498
13499 return std::unique_ptr<AST::CompoundAssignmentExpr> (
13500 new AST::CompoundAssignmentExpr (std::move (left), std::move (right),
13501 CompoundAssignmentOperator::MULTIPLY,
13502 locus));
13503 }
13504
13505 // Parses a binary division-assignment expression (with Pratt parsing).
13506 template <typename ManagedTokenSource>
13507 std::unique_ptr<AST::CompoundAssignmentExpr>
13508 Parser<ManagedTokenSource>::parse_div_assig_expr (
13509 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13510 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13511 {
13512 // parse RHS (as tok has already been consumed in parse_expression)
13513 std::unique_ptr<AST::Expr> right
13514 = parse_expr (LBP_DIV_ASSIG - 1, AST::AttrVec (), restrictions);
13515 if (right == nullptr)
13516 return nullptr;
13517 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13518
13519 // TODO: check types. actually, do so during semantic analysis
13520 location_t locus = left->get_locus ();
13521
13522 return std::unique_ptr<AST::CompoundAssignmentExpr> (
13523 new AST::CompoundAssignmentExpr (std::move (left), std::move (right),
13524 CompoundAssignmentOperator::DIVIDE,
13525 locus));
13526 }
13527
13528 // Parses a binary modulo-assignment expression (with Pratt parsing).
13529 template <typename ManagedTokenSource>
13530 std::unique_ptr<AST::CompoundAssignmentExpr>
13531 Parser<ManagedTokenSource>::parse_mod_assig_expr (
13532 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13533 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13534 {
13535 // parse RHS (as tok has already been consumed in parse_expression)
13536 std::unique_ptr<AST::Expr> right
13537 = parse_expr (LBP_MOD_ASSIG - 1, AST::AttrVec (), restrictions);
13538 if (right == nullptr)
13539 return nullptr;
13540 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13541
13542 // TODO: check types. actually, do so during semantic analysis
13543 location_t locus = left->get_locus ();
13544
13545 return std::unique_ptr<AST::CompoundAssignmentExpr> (
13546 new AST::CompoundAssignmentExpr (std::move (left), std::move (right),
13547 CompoundAssignmentOperator::MODULUS,
13548 locus));
13549 }
13550
13551 // Parses a binary and-assignment expression (with Pratt parsing).
13552 template <typename ManagedTokenSource>
13553 std::unique_ptr<AST::CompoundAssignmentExpr>
13554 Parser<ManagedTokenSource>::parse_and_assig_expr (
13555 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13556 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13557 {
13558 // parse RHS (as tok has already been consumed in parse_expression)
13559 std::unique_ptr<AST::Expr> right
13560 = parse_expr (LBP_AMP_ASSIG - 1, AST::AttrVec (), restrictions);
13561 if (right == nullptr)
13562 return nullptr;
13563 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13564
13565 // TODO: check types. actually, do so during semantic analysis
13566 location_t locus = left->get_locus ();
13567
13568 return std::unique_ptr<AST::CompoundAssignmentExpr> (
13569 new AST::CompoundAssignmentExpr (std::move (left), std::move (right),
13570 CompoundAssignmentOperator::BITWISE_AND,
13571 locus));
13572 }
13573
13574 // Parses a binary or-assignment expression (with Pratt parsing).
13575 template <typename ManagedTokenSource>
13576 std::unique_ptr<AST::CompoundAssignmentExpr>
13577 Parser<ManagedTokenSource>::parse_or_assig_expr (
13578 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13579 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13580 {
13581 // parse RHS (as tok has already been consumed in parse_expression)
13582 std::unique_ptr<AST::Expr> right
13583 = parse_expr (LBP_PIPE_ASSIG - 1, AST::AttrVec (), restrictions);
13584 if (right == nullptr)
13585 return nullptr;
13586 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13587
13588 // TODO: check types. actually, do so during semantic analysis
13589 location_t locus = left->get_locus ();
13590
13591 return std::unique_ptr<AST::CompoundAssignmentExpr> (
13592 new AST::CompoundAssignmentExpr (std::move (left), std::move (right),
13593 CompoundAssignmentOperator::BITWISE_OR,
13594 locus));
13595 }
13596
13597 // Parses a binary xor-assignment expression (with Pratt parsing).
13598 template <typename ManagedTokenSource>
13599 std::unique_ptr<AST::CompoundAssignmentExpr>
13600 Parser<ManagedTokenSource>::parse_xor_assig_expr (
13601 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13602 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13603 {
13604 // parse RHS (as tok has already been consumed in parse_expression)
13605 std::unique_ptr<AST::Expr> right
13606 = parse_expr (LBP_CARET_ASSIG - 1, AST::AttrVec (), restrictions);
13607 if (right == nullptr)
13608 return nullptr;
13609 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13610
13611 // TODO: check types. actually, do so during semantic analysis
13612 location_t locus = left->get_locus ();
13613
13614 return std::unique_ptr<AST::CompoundAssignmentExpr> (
13615 new AST::CompoundAssignmentExpr (std::move (left), std::move (right),
13616 CompoundAssignmentOperator::BITWISE_XOR,
13617 locus));
13618 }
13619
13620 // Parses a binary left shift-assignment expression (with Pratt parsing).
13621 template <typename ManagedTokenSource>
13622 std::unique_ptr<AST::CompoundAssignmentExpr>
13623 Parser<ManagedTokenSource>::parse_left_shift_assig_expr (
13624 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13625 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13626 {
13627 // parse RHS (as tok has already been consumed in parse_expression)
13628 std::unique_ptr<AST::Expr> right
13629 = parse_expr (LBP_L_SHIFT_ASSIG - 1, AST::AttrVec (), restrictions);
13630 if (right == nullptr)
13631 return nullptr;
13632 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13633
13634 // TODO: check types. actually, do so during semantic analysis
13635 location_t locus = left->get_locus ();
13636
13637 return std::unique_ptr<AST::CompoundAssignmentExpr> (
13638 new AST::CompoundAssignmentExpr (std::move (left), std::move (right),
13639 CompoundAssignmentOperator::LEFT_SHIFT,
13640 locus));
13641 }
13642
13643 // Parses a binary right shift-assignment expression (with Pratt parsing).
13644 template <typename ManagedTokenSource>
13645 std::unique_ptr<AST::CompoundAssignmentExpr>
13646 Parser<ManagedTokenSource>::parse_right_shift_assig_expr (
13647 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13648 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13649 {
13650 // parse RHS (as tok has already been consumed in parse_expression)
13651 std::unique_ptr<AST::Expr> right
13652 = parse_expr (LBP_R_SHIFT_ASSIG - 1, AST::AttrVec (), restrictions);
13653 if (right == nullptr)
13654 return nullptr;
13655 // FIXME: ensure right-associativity for this - 'LBP - 1' may do this?
13656
13657 // TODO: check types. actually, do so during semantic analysis
13658 location_t locus = left->get_locus ();
13659
13660 return std::unique_ptr<AST::CompoundAssignmentExpr> (
13661 new AST::CompoundAssignmentExpr (std::move (left), std::move (right),
13662 CompoundAssignmentOperator::RIGHT_SHIFT,
13663 locus));
13664 }
13665
13666 // Parses a postfix unary await expression (with Pratt parsing).
13667 template <typename ManagedTokenSource>
13668 std::unique_ptr<AST::AwaitExpr>
13669 Parser<ManagedTokenSource>::parse_await_expr (
13670 const_TokenPtr tok, std::unique_ptr<AST::Expr> expr_to_await,
13671 AST::AttrVec outer_attrs)
13672 {
13673 /* skip "await" identifier (as "." has already been consumed in
13674 * parse_expression) this assumes that the identifier was already identified
13675 * as await */
13676 if (!skip_token (IDENTIFIER))
13677 {
13678 Error error (tok->get_locus (), "failed to skip %<await%> in await expr "
13679 "- this is probably a deep issue");
13680 add_error (std::move (error));
13681
13682 // skip somewhere?
13683 return nullptr;
13684 }
13685
13686 // TODO: check inside async block in semantic analysis
13687 location_t locus = expr_to_await->get_locus ();
13688
13689 return std::unique_ptr<AST::AwaitExpr> (
13690 new AST::AwaitExpr (std::move (expr_to_await), std::move (outer_attrs),
13691 locus));
13692 }
13693
13694 /* Parses an exclusive range ('..') in left denotation position (i.e.
13695 * RangeFromExpr or RangeFromToExpr). */
13696 template <typename ManagedTokenSource>
13697 std::unique_ptr<AST::RangeExpr>
13698 Parser<ManagedTokenSource>::parse_led_range_exclusive_expr (
13699 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13700 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13701 {
13702 // FIXME: this probably parses expressions accidently or whatever
13703 // try parsing RHS (as tok has already been consumed in parse_expression)
13704 // Can be nullptr, in which case it is a RangeFromExpr, otherwise a
13705 // RangeFromToExpr.
13706 restrictions.expr_can_be_null = true;
13707 std::unique_ptr<AST::Expr> right
13708 = parse_expr (LBP_DOT_DOT, AST::AttrVec (), restrictions);
13709
13710 location_t locus = left->get_locus ();
13711
13712 if (right == nullptr)
13713 {
13714 // range from expr
13715 return std::unique_ptr<AST::RangeFromExpr> (
13716 new AST::RangeFromExpr (std::move (left), locus));
13717 }
13718 else
13719 {
13720 return std::unique_ptr<AST::RangeFromToExpr> (
13721 new AST::RangeFromToExpr (std::move (left), std::move (right), locus));
13722 }
13723 // FIXME: make non-associative
13724 }
13725
13726 /* Parses an exclusive range ('..') in null denotation position (i.e.
13727 * RangeToExpr or RangeFullExpr). */
13728 template <typename ManagedTokenSource>
13729 std::unique_ptr<AST::RangeExpr>
13730 Parser<ManagedTokenSource>::parse_nud_range_exclusive_expr (
13731 const_TokenPtr tok, AST::AttrVec outer_attrs ATTRIBUTE_UNUSED)
13732 {
13733 auto restrictions = ParseRestrictions ();
13734 restrictions.expr_can_be_null = true;
13735
13736 // FIXME: this probably parses expressions accidently or whatever
13737 // try parsing RHS (as tok has already been consumed in parse_expression)
13738 std::unique_ptr<AST::Expr> right
13739 = parse_expr (LBP_DOT_DOT, AST::AttrVec (), restrictions);
13740
13741 location_t locus = tok->get_locus ();
13742
13743 if (right == nullptr)
13744 {
13745 // range from expr
13746 return std::unique_ptr<AST::RangeFullExpr> (
13747 new AST::RangeFullExpr (locus));
13748 }
13749 else
13750 {
13751 return std::unique_ptr<AST::RangeToExpr> (
13752 new AST::RangeToExpr (std::move (right), locus));
13753 }
13754 // FIXME: make non-associative
13755 }
13756
13757 // Parses a full binary range inclusive expression.
13758 template <typename ManagedTokenSource>
13759 std::unique_ptr<AST::RangeFromToInclExpr>
13760 Parser<ManagedTokenSource>::parse_range_inclusive_expr (
13761 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> left,
13762 AST::AttrVec outer_attrs ATTRIBUTE_UNUSED, ParseRestrictions restrictions)
13763 {
13764 // parse RHS (as tok has already been consumed in parse_expression)
13765 std::unique_ptr<AST::Expr> right
13766 = parse_expr (LBP_DOT_DOT_EQ, AST::AttrVec (), restrictions);
13767 if (right == nullptr)
13768 return nullptr;
13769 // FIXME: make non-associative
13770
13771 // TODO: check types. actually, do so during semantic analysis
13772 location_t locus = left->get_locus ();
13773
13774 return std::unique_ptr<AST::RangeFromToInclExpr> (
13775 new AST::RangeFromToInclExpr (std::move (left), std::move (right), locus));
13776 }
13777
13778 // Parses an inclusive range-to prefix unary expression.
13779 template <typename ManagedTokenSource>
13780 std::unique_ptr<AST::RangeToInclExpr>
13781 Parser<ManagedTokenSource>::parse_range_to_inclusive_expr (
13782 const_TokenPtr tok, AST::AttrVec outer_attrs ATTRIBUTE_UNUSED)
13783 {
13784 // parse RHS (as tok has already been consumed in parse_expression)
13785 std::unique_ptr<AST::Expr> right = parse_expr (LBP_DOT_DOT_EQ);
13786 if (right == nullptr)
13787 return nullptr;
13788 // FIXME: make non-associative
13789
13790 // TODO: check types. actually, do so during semantic analysis
13791
13792 return std::unique_ptr<AST::RangeToInclExpr> (
13793 new AST::RangeToInclExpr (std::move (right), tok->get_locus ()));
13794 }
13795
13796 // Parses a pseudo-binary infix tuple index expression.
13797 template <typename ManagedTokenSource>
13798 std::unique_ptr<AST::TupleIndexExpr>
13799 Parser<ManagedTokenSource>::parse_tuple_index_expr (
13800 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> tuple_expr,
13801 AST::AttrVec outer_attrs, ParseRestrictions restrictions ATTRIBUTE_UNUSED)
13802 {
13803 // parse int literal (as token already skipped)
13804 const_TokenPtr index_tok = expect_token (INT_LITERAL);
13805 if (index_tok == nullptr)
13806 {
13807 return nullptr;
13808 }
13809 std::string index = index_tok->get_str ();
13810
13811 // convert to integer
13812 if (!index_tok->is_pure_decimal ())
13813 {
13814 Error error (index_tok->get_locus (),
13815 "tuple index should be a pure decimal literal");
13816 add_error (std::move (error));
13817 }
13818 int index_int = atoi (index.c_str ());
13819
13820 location_t locus = tuple_expr->get_locus ();
13821
13822 return std::unique_ptr<AST::TupleIndexExpr> (
13823 new AST::TupleIndexExpr (std::move (tuple_expr), index_int,
13824 std::move (outer_attrs), locus));
13825 }
13826
13827 // Parses a pseudo-binary infix array (or slice) index expression.
13828 template <typename ManagedTokenSource>
13829 std::unique_ptr<AST::ArrayIndexExpr>
13830 Parser<ManagedTokenSource>::parse_index_expr (
13831 const_TokenPtr, std::unique_ptr<AST::Expr> array_expr,
13832 AST::AttrVec outer_attrs, ParseRestrictions)
13833 {
13834 // parse RHS (as tok has already been consumed in parse_expression)
13835 /*std::unique_ptr<AST::Expr> index_expr
13836 = parse_expr (LBP_ARRAY_REF, AST::AttrVec (),
13837 restrictions);*/
13838 // TODO: conceptually, should treat [] as brackets, so just parse all expr
13839 std::unique_ptr<AST::Expr> index_expr = parse_expr ();
13840 if (index_expr == nullptr)
13841 return nullptr;
13842
13843 // skip ']' at end of array
13844 if (!skip_token (RIGHT_SQUARE))
13845 {
13846 // skip somewhere?
13847 return nullptr;
13848 }
13849
13850 // TODO: check types. actually, do so during semantic analysis
13851 location_t locus = array_expr->get_locus ();
13852
13853 return std::unique_ptr<AST::ArrayIndexExpr> (
13854 new AST::ArrayIndexExpr (std::move (array_expr), std::move (index_expr),
13855 std::move (outer_attrs), locus));
13856 }
13857
13858 // Parses a pseudo-binary infix struct field access expression.
13859 template <typename ManagedTokenSource>
13860 std::unique_ptr<AST::FieldAccessExpr>
13861 Parser<ManagedTokenSource>::parse_field_access_expr (
13862 const_TokenPtr tok ATTRIBUTE_UNUSED, std::unique_ptr<AST::Expr> struct_expr,
13863 AST::AttrVec outer_attrs, ParseRestrictions restrictions ATTRIBUTE_UNUSED)
13864 {
13865 /* get field name identifier (assume that this is a field access expr and
13866 * not await, for instance) */
13867 const_TokenPtr ident_tok = expect_token (IDENTIFIER);
13868 if (ident_tok == nullptr)
13869 return nullptr;
13870
13871 Identifier ident{ident_tok};
13872
13873 location_t locus = struct_expr->get_locus ();
13874
13875 // TODO: check types. actually, do so during semantic analysis
13876 return std::unique_ptr<AST::FieldAccessExpr> (
13877 new AST::FieldAccessExpr (std::move (struct_expr), std::move (ident),
13878 std::move (outer_attrs), locus));
13879 }
13880
13881 // Parses a pseudo-binary infix method call expression.
13882 template <typename ManagedTokenSource>
13883 std::unique_ptr<AST::MethodCallExpr>
13884 Parser<ManagedTokenSource>::parse_method_call_expr (
13885 const_TokenPtr tok, std::unique_ptr<AST::Expr> receiver_expr,
13886 AST::AttrVec outer_attrs, ParseRestrictions)
13887 {
13888 // parse path expr segment
13889 AST::PathExprSegment segment = parse_path_expr_segment ();
13890 if (segment.is_error ())
13891 {
13892 Error error (tok->get_locus (),
13893 "failed to parse path expr segment of method call expr");
13894 add_error (std::move (error));
13895
13896 return nullptr;
13897 }
13898
13899 // skip left parentheses
13900 if (!skip_token (LEFT_PAREN))
13901 {
13902 return nullptr;
13903 }
13904
13905 // parse method params (if they exist)
13906 std::vector<std::unique_ptr<AST::Expr>> params;
13907
13908 const_TokenPtr t = lexer.peek_token ();
13909 while (t->get_id () != RIGHT_PAREN)
13910 {
13911 std::unique_ptr<AST::Expr> param = parse_expr ();
13912 if (param == nullptr)
13913 {
13914 Error error (t->get_locus (),
13915 "failed to parse method param in method call");
13916 add_error (std::move (error));
13917
13918 return nullptr;
13919 }
13920 params.push_back (std::move (param));
13921
13922 if (lexer.peek_token ()->get_id () != COMMA)
13923 break;
13924
13925 lexer.skip_token ();
13926 t = lexer.peek_token ();
13927 }
13928
13929 // skip right paren
13930 if (!skip_token (RIGHT_PAREN))
13931 {
13932 return nullptr;
13933 }
13934
13935 // TODO: check types. actually do so in semantic analysis pass.
13936 location_t locus = receiver_expr->get_locus ();
13937
13938 return std::unique_ptr<AST::MethodCallExpr> (
13939 new AST::MethodCallExpr (std::move (receiver_expr), std::move (segment),
13940 std::move (params), std::move (outer_attrs),
13941 locus));
13942 }
13943
13944 // Parses a pseudo-binary infix function call expression.
13945 template <typename ManagedTokenSource>
13946 std::unique_ptr<AST::CallExpr>
13947 Parser<ManagedTokenSource>::parse_function_call_expr (
13948 const_TokenPtr, std::unique_ptr<AST::Expr> function_expr,
13949 AST::AttrVec outer_attrs, ParseRestrictions)
13950 {
13951 // parse function params (if they exist)
13952 std::vector<std::unique_ptr<AST::Expr>> params;
13953
13954 const_TokenPtr t = lexer.peek_token ();
13955 while (t->get_id () != RIGHT_PAREN)
13956 {
13957 std::unique_ptr<AST::Expr> param = parse_expr ();
13958 if (param == nullptr)
13959 {
13960 Error error (t->get_locus (),
13961 "failed to parse function param in function call");
13962 add_error (std::move (error));
13963
13964 return nullptr;
13965 }
13966 params.push_back (std::move (param));
13967
13968 if (lexer.peek_token ()->get_id () != COMMA)
13969 break;
13970
13971 lexer.skip_token ();
13972 t = lexer.peek_token ();
13973 }
13974
13975 // skip ')' at end of param list
13976 if (!skip_token (RIGHT_PAREN))
13977 {
13978 // skip somewhere?
13979 return nullptr;
13980 }
13981
13982 // TODO: check types. actually, do so during semantic analysis
13983 location_t locus = function_expr->get_locus ();
13984
13985 return std::unique_ptr<AST::CallExpr> (
13986 new AST::CallExpr (std::move (function_expr), std::move (params),
13987 std::move (outer_attrs), locus));
13988 }
13989
13990 /* Parses a macro invocation with a path in expression already parsed (but not
13991 * '!' token). */
13992 template <typename ManagedTokenSource>
13993 std::unique_ptr<AST::MacroInvocation>
13994 Parser<ManagedTokenSource>::parse_macro_invocation_partial (
13995 AST::PathInExpression path, AST::AttrVec outer_attrs,
13996 ParseRestrictions restrictions)
13997 {
13998 // macro invocation
13999 if (!skip_token (EXCLAM))
14000 {
14001 return nullptr;
14002 }
14003
14004 // convert PathInExpression to SimplePath - if this isn't possible, error
14005 AST::SimplePath converted_path = path.as_simple_path ();
14006 if (converted_path.is_empty ())
14007 {
14008 Error error (lexer.peek_token ()->get_locus (),
14009 "failed to parse simple path in macro invocation");
14010 add_error (std::move (error));
14011
14012 return nullptr;
14013 }
14014
14015 AST::DelimTokenTree tok_tree = parse_delim_token_tree ();
14016
14017 rust_debug ("successfully parsed macro invocation (via partial)");
14018
14019 location_t macro_locus = converted_path.get_locus ();
14020
14021 return AST::MacroInvocation::Regular (
14022 AST::MacroInvocData (std::move (converted_path), std::move (tok_tree)),
14023 std::move (outer_attrs), macro_locus);
14024 }
14025
14026 /* Parses a struct expr struct with a path in expression already parsed (but
14027 * not
14028 * '{' token). */
14029 template <typename ManagedTokenSource>
14030 std::unique_ptr<AST::StructExprStruct>
14031 Parser<ManagedTokenSource>::parse_struct_expr_struct_partial (
14032 AST::PathInExpression path, AST::AttrVec outer_attrs)
14033 {
14034 // assume struct expr struct (as struct-enum disambiguation requires name
14035 // lookup) again, make statement if final ';'
14036 if (!skip_token (LEFT_CURLY))
14037 {
14038 return nullptr;
14039 }
14040
14041 // parse inner attributes
14042 AST::AttrVec inner_attrs = parse_inner_attributes ();
14043
14044 // branch based on next token
14045 const_TokenPtr t = lexer.peek_token ();
14046 location_t path_locus = path.get_locus ();
14047 switch (t->get_id ())
14048 {
14049 case RIGHT_CURLY:
14050 // struct with no body
14051 lexer.skip_token ();
14052
14053 return std::unique_ptr<AST::StructExprStruct> (
14054 new AST::StructExprStruct (std::move (path), std::move (inner_attrs),
14055 std::move (outer_attrs), path_locus));
14056 case DOT_DOT:
14057 /* technically this would give a struct base-only struct, but this
14058 * algorithm should work too. As such, AST type not happening. */
14059 case IDENTIFIER:
14060 case HASH:
14061 case INT_LITERAL: {
14062 // struct with struct expr fields
14063
14064 // parse struct expr fields
14065 std::vector<std::unique_ptr<AST::StructExprField>> fields;
14066
14067 while (t->get_id () != RIGHT_CURLY && t->get_id () != DOT_DOT)
14068 {
14069 std::unique_ptr<AST::StructExprField> field
14070 = parse_struct_expr_field ();
14071 if (field == nullptr)
14072 {
14073 Error error (t->get_locus (),
14074 "failed to parse struct (or enum) expr field");
14075 add_error (std::move (error));
14076
14077 return nullptr;
14078 }
14079
14080 // DEBUG:
14081 rust_debug ("struct/enum expr field validated to not be null");
14082
14083 fields.push_back (std::move (field));
14084
14085 // DEBUG:
14086 rust_debug ("struct/enum expr field pushed back");
14087
14088 if (lexer.peek_token ()->get_id () != COMMA)
14089 {
14090 // DEBUG:
14091 rust_debug ("lack of comma detected in struct/enum expr "
14092 "fields - break");
14093 break;
14094 }
14095 lexer.skip_token ();
14096
14097 // DEBUG:
14098 rust_debug ("struct/enum expr fields comma skipped ");
14099
14100 t = lexer.peek_token ();
14101 }
14102
14103 // DEBUG:
14104 rust_debug ("struct/enum expr about to parse struct base ");
14105
14106 // parse struct base if it exists
14107 AST::StructBase struct_base = AST::StructBase::error ();
14108 if (lexer.peek_token ()->get_id () == DOT_DOT)
14109 {
14110 location_t dot_dot_location = lexer.peek_token ()->get_locus ();
14111 lexer.skip_token ();
14112
14113 // parse required struct base expr
14114 std::unique_ptr<AST::Expr> base_expr = parse_expr ();
14115 if (base_expr == nullptr)
14116 {
14117 Error error (lexer.peek_token ()->get_locus (),
14118 "failed to parse struct base expression in struct "
14119 "expression");
14120 add_error (std::move (error));
14121
14122 return nullptr;
14123 }
14124
14125 // DEBUG:
14126 rust_debug ("struct/enum expr - parsed and validated base expr");
14127
14128 struct_base
14129 = AST::StructBase (std::move (base_expr), dot_dot_location);
14130
14131 // DEBUG:
14132 rust_debug ("assigned struct base to new struct base ");
14133 }
14134
14135 if (!skip_token (RIGHT_CURLY))
14136 {
14137 return nullptr;
14138 }
14139
14140 // DEBUG:
14141 rust_debug (
14142 "struct/enum expr skipped right curly - done and ready to return");
14143
14144 return std::unique_ptr<AST::StructExprStructFields> (
14145 new AST::StructExprStructFields (std::move (path), std::move (fields),
14146 path_locus, std::move (struct_base),
14147 std::move (inner_attrs),
14148 std::move (outer_attrs)));
14149 }
14150 default:
14151 add_error (
14152 Error (t->get_locus (),
14153 "unrecognised token %qs in struct (or enum) expression - "
14154 "expected %<}%>, identifier, integer literal, or %<..%>",
14155 t->get_token_description ()));
14156
14157 return nullptr;
14158 }
14159 }
14160
14161 /* Parses a struct expr tuple with a path in expression already parsed (but
14162 * not
14163 * '(' token).
14164 * FIXME: this currently outputs a call expr, as they cannot be disambiguated.
14165 * A better solution would be to just get this to call that function directly.
14166 * */
14167 template <typename ManagedTokenSource>
14168 std::unique_ptr<AST::CallExpr>
14169 Parser<ManagedTokenSource>::parse_struct_expr_tuple_partial (
14170 AST::PathInExpression path, AST::AttrVec outer_attrs)
14171 {
14172 if (!skip_token (LEFT_PAREN))
14173 {
14174 return nullptr;
14175 }
14176
14177 AST::AttrVec inner_attrs = parse_inner_attributes ();
14178
14179 std::vector<std::unique_ptr<AST::Expr>> exprs;
14180
14181 const_TokenPtr t = lexer.peek_token ();
14182 while (t->get_id () != RIGHT_PAREN)
14183 {
14184 // parse expression (required)
14185 std::unique_ptr<AST::Expr> expr = parse_expr ();
14186 if (expr == nullptr)
14187 {
14188 Error error (t->get_locus (), "failed to parse expression in "
14189 "struct (or enum) expression tuple");
14190 add_error (std::move (error));
14191
14192 return nullptr;
14193 }
14194 exprs.push_back (std::move (expr));
14195
14196 if (lexer.peek_token ()->get_id () != COMMA)
14197 break;
14198
14199 lexer.skip_token ();
14200
14201 t = lexer.peek_token ();
14202 }
14203
14204 if (!skip_token (RIGHT_PAREN))
14205 {
14206 return nullptr;
14207 }
14208
14209 location_t path_locus = path.get_locus ();
14210
14211 auto pathExpr = std::unique_ptr<AST::PathInExpression> (
14212 new AST::PathInExpression (std::move (path)));
14213
14214 return std::unique_ptr<AST::CallExpr> (
14215 new AST::CallExpr (std::move (pathExpr), std::move (exprs),
14216 std::move (outer_attrs), path_locus));
14217 }
14218
14219 /* Parses a path in expression with the first token passed as a parameter (as
14220 * it is skipped in token stream). Note that this only parses segment-first
14221 * paths, not global ones. */
14222 template <typename ManagedTokenSource>
14223 AST::PathInExpression
14224 Parser<ManagedTokenSource>::parse_path_in_expression_pratt (const_TokenPtr tok)
14225 {
14226 // HACK-y way of making up for pratt-parsing consuming first token
14227
14228 // DEBUG
14229 rust_debug ("current peek token when starting path pratt parse: '%s'",
14230 lexer.peek_token ()->get_token_description ());
14231
14232 // create segment vector
14233 std::vector<AST::PathExprSegment> segments;
14234
14235 std::string initial_str;
14236
14237 switch (tok->get_id ())
14238 {
14239 case IDENTIFIER:
14240 initial_str = tok->get_str ();
14241 break;
14242 case SUPER:
14243 initial_str = Values::Keywords::SUPER;
14244 break;
14245 case SELF:
14246 initial_str = Values::Keywords::SELF;
14247 break;
14248 case SELF_ALIAS:
14249 initial_str = Values::Keywords::SELF_ALIAS;
14250 break;
14251 case CRATE:
14252 initial_str = Values::Keywords::CRATE;
14253 break;
14254 case DOLLAR_SIGN:
14255 if (lexer.peek_token ()->get_id () == CRATE)
14256 {
14257 initial_str = "$crate";
14258 break;
14259 }
14260 gcc_fallthrough ();
14261 default:
14262 add_error (Error (tok->get_locus (),
14263 "unrecognised token %qs in path in expression",
14264 tok->get_token_description ()));
14265
14266 return AST::PathInExpression::create_error ();
14267 }
14268
14269 // parse required initial segment
14270 AST::PathExprSegment initial_segment (initial_str, tok->get_locus ());
14271 // parse generic args (and turbofish), if they exist
14272 /* use lookahead to determine if they actually exist (don't want to
14273 * accidently parse over next ident segment) */
14274 if (lexer.peek_token ()->get_id () == SCOPE_RESOLUTION
14275 && lexer.peek_token (1)->get_id () == LEFT_ANGLE)
14276 {
14277 // skip scope resolution
14278 lexer.skip_token ();
14279
14280 AST::GenericArgs generic_args = parse_path_generic_args ();
14281
14282 initial_segment
14283 = AST::PathExprSegment (AST::PathIdentSegment (initial_str,
14284 tok->get_locus ()),
14285 tok->get_locus (), std::move (generic_args));
14286 }
14287 if (initial_segment.is_error ())
14288 {
14289 // skip after somewhere?
14290 // don't necessarily throw error but yeah
14291
14292 // DEBUG
14293 rust_debug ("initial segment is error - returning null");
14294
14295 return AST::PathInExpression::create_error ();
14296 }
14297 segments.push_back (std::move (initial_segment));
14298
14299 // parse optional segments (as long as scope resolution operator exists)
14300 const_TokenPtr t = lexer.peek_token ();
14301 while (t->get_id () == SCOPE_RESOLUTION)
14302 {
14303 // skip scope resolution operator
14304 lexer.skip_token ();
14305
14306 // parse the actual segment - it is an error if it doesn't exist now
14307 AST::PathExprSegment segment = parse_path_expr_segment ();
14308 if (segment.is_error ())
14309 {
14310 // skip after somewhere?
14311 Error error (t->get_locus (),
14312 "could not parse path expression segment");
14313 add_error (std::move (error));
14314
14315 return AST::PathInExpression::create_error ();
14316 }
14317
14318 segments.push_back (std::move (segment));
14319
14320 t = lexer.peek_token ();
14321 }
14322
14323 // DEBUG:
14324 rust_debug (
14325 "current token (just about to return path to null denotation): '%s'",
14326 lexer.peek_token ()->get_token_description ());
14327
14328 return AST::PathInExpression (std::move (segments), {}, tok->get_locus (),
14329 false);
14330 }
14331
14332 // Parses a closure expression with pratt parsing (from null denotation).
14333 template <typename ManagedTokenSource>
14334 std::unique_ptr<AST::ClosureExpr>
14335 Parser<ManagedTokenSource>::parse_closure_expr_pratt (const_TokenPtr tok,
14336 AST::AttrVec outer_attrs)
14337 {
14338 // TODO: does this need pratt parsing (for precedence)? probably not, but
14339 // idk
14340 location_t locus = tok->get_locus ();
14341 bool has_move = false;
14342 if (tok->get_id () == MOVE)
14343 {
14344 has_move = true;
14345 tok = lexer.peek_token ();
14346 lexer.skip_token ();
14347 // skip token and reassign
14348 }
14349
14350 // handle parameter list
14351 std::vector<AST::ClosureParam> params;
14352
14353 switch (tok->get_id ())
14354 {
14355 case OR:
14356 // no parameters, don't skip token
14357 break;
14358 case PIPE: {
14359 // actually may have parameters
14360 // don't skip token
14361 const_TokenPtr t = lexer.peek_token ();
14362 while (t->get_id () != PIPE)
14363 {
14364 AST::ClosureParam param = parse_closure_param ();
14365 if (param.is_error ())
14366 {
14367 // TODO is this really an error?
14368 Error error (t->get_locus (), "could not parse closure param");
14369 add_error (std::move (error));
14370
14371 return nullptr;
14372 }
14373 params.push_back (std::move (param));
14374
14375 if (lexer.peek_token ()->get_id () != COMMA)
14376 {
14377 if (lexer.peek_token ()->get_id () == OR)
14378 lexer.split_current_token (PIPE, PIPE);
14379 // not an error but means param list is done
14380 break;
14381 }
14382 // skip comma
14383 lexer.skip_token ();
14384
14385 if (lexer.peek_token ()->get_id () == OR)
14386 lexer.split_current_token (PIPE, PIPE);
14387
14388 t = lexer.peek_token ();
14389 }
14390
14391 if (!skip_token (PIPE))
14392 {
14393 return nullptr;
14394 }
14395 break;
14396 }
14397 default:
14398 add_error (Error (tok->get_locus (),
14399 "unexpected token %qs in closure expression - expected "
14400 "%<|%> or %<||%>",
14401 tok->get_token_description ()));
14402
14403 // skip somewhere?
14404 return nullptr;
14405 }
14406
14407 // again branch based on next token
14408 tok = lexer.peek_token ();
14409 if (tok->get_id () == RETURN_TYPE)
14410 {
14411 // must be return type closure with block expr
14412
14413 // skip "return type" token
14414 lexer.skip_token ();
14415
14416 // parse actual type, which is required
14417 std::unique_ptr<AST::TypeNoBounds> type = parse_type_no_bounds ();
14418 if (type == nullptr)
14419 {
14420 // error
14421 Error error (tok->get_locus (), "failed to parse type for closure");
14422 add_error (std::move (error));
14423
14424 // skip somewhere?
14425 return nullptr;
14426 }
14427
14428 // parse block expr, which is required
14429 std::unique_ptr<AST::BlockExpr> block = parse_block_expr ();
14430 if (block == nullptr)
14431 {
14432 // error
14433 Error error (lexer.peek_token ()->get_locus (),
14434 "failed to parse block expr in closure");
14435 add_error (std::move (error));
14436
14437 // skip somewhere?
14438 return nullptr;
14439 }
14440
14441 return std::unique_ptr<AST::ClosureExprInnerTyped> (
14442 new AST::ClosureExprInnerTyped (std::move (type), std::move (block),
14443 std::move (params), locus, has_move,
14444 std::move (outer_attrs)));
14445 }
14446 else
14447 {
14448 // must be expr-only closure
14449
14450 // parse expr, which is required
14451 std::unique_ptr<AST::Expr> expr = parse_expr ();
14452 if (expr == nullptr)
14453 {
14454 Error error (tok->get_locus (),
14455 "failed to parse expression in closure");
14456 add_error (std::move (error));
14457
14458 // skip somewhere?
14459 return nullptr;
14460 }
14461
14462 return std::unique_ptr<AST::ClosureExprInner> (
14463 new AST::ClosureExprInner (std::move (expr), std::move (params), locus,
14464 has_move, std::move (outer_attrs)));
14465 }
14466 }
14467
14468 /* Parses a tuple index expression (pratt-parsed) from a 'float' token as a
14469 * result of lexer misidentification. */
14470 template <typename ManagedTokenSource>
14471 std::unique_ptr<AST::TupleIndexExpr>
14472 Parser<ManagedTokenSource>::parse_tuple_index_expr_float (
14473 const_TokenPtr tok, std::unique_ptr<AST::Expr> tuple_expr,
14474 AST::AttrVec outer_attrs, ParseRestrictions restrictions ATTRIBUTE_UNUSED)
14475 {
14476 // only works on float literals
14477 if (tok->get_id () != FLOAT_LITERAL)
14478 return nullptr;
14479
14480 // DEBUG:
14481 rust_debug ("exact string form of float: '%s'", tok->get_str ().c_str ());
14482
14483 // get float string and remove dot and initial 0
14484 std::string index_str = tok->get_str ();
14485 index_str.erase (index_str.begin ());
14486
14487 // get int from string
14488 int index = atoi (index_str.c_str ());
14489
14490 location_t locus = tuple_expr->get_locus ();
14491
14492 return std::unique_ptr<AST::TupleIndexExpr> (
14493 new AST::TupleIndexExpr (std::move (tuple_expr), index,
14494 std::move (outer_attrs), locus));
14495 }
14496
14497 // Returns true if the next token is END, ELSE, or EOF;
14498 template <typename ManagedTokenSource>
14499 bool
14500 Parser<ManagedTokenSource>::done_end_or_else ()
14501 {
14502 const_TokenPtr t = lexer.peek_token ();
14503 return (t->get_id () == RIGHT_CURLY || t->get_id () == ELSE
14504 || t->get_id () == END_OF_FILE);
14505 }
14506
14507 // Returns true if the next token is END or EOF.
14508 template <typename ManagedTokenSource>
14509 bool
14510 Parser<ManagedTokenSource>::done_end ()
14511 {
14512 const_TokenPtr t = lexer.peek_token ();
14513 return (t->get_id () == RIGHT_CURLY || t->get_id () == END_OF_FILE);
14514 }
14515 } // namespace Rust