Debian Codegraph @

gcc/rust/expand/rust-macro-expand.cc

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 #include "rust-macro-expand.h"
20 #include "optional.h"
21 #include "rust-ast-fragment.h"
22 #include "rust-macro-substitute-ctx.h"
23 #include "rust-ast-full.h"
24 #include "rust-ast-visitor.h"
25 #include "rust-diagnostics.h"
26 #include "rust-macro.h"
27 #include "rust-parse.h"
28 #include "rust-cfg-strip.h"
29 #include "rust-early-name-resolver.h"
30 #include "rust-proc-macro.h"
31 #include "rust-token-tree-desugar.h"
32
33 namespace Rust {
34
35 AST::Fragment
36 MacroExpander::expand_decl_macro (location_t invoc_locus,
37 AST::MacroInvocData &invoc,
38 AST::MacroRulesDefinition &rules_def,
39 AST::InvocKind semicolon)
40 {
41 // ensure that both invocation and rules are in a valid state
42 rust_assert (!invoc.is_marked_for_strip ());
43 rust_assert (!rules_def.is_marked_for_strip ());
44 rust_assert (rules_def.get_macro_rules ().size () > 0);
45
46 /* probably something here about parsing invoc and rules def token trees to
47 * token stream. if not, how would parser handle the captures of exprs and
48 * stuff? on the other hand, token trees may be kind of useful in rules def
49 * as creating a point where recursion can occur (like having
50 * "compare_macro_match" and then it calling itself when it finds
51 * delimiters)
52 */
53
54 /* find matching rule to invoc token tree, based on macro rule's matcher. if
55 * none exist, error.
56 * - specifically, check each matcher in order. if one fails to match, move
57 * onto next. */
58 /* TODO: does doing this require parsing expressions and whatever in the
59 * invoc? if so, might as well save the results if referenced using $ or
60 * whatever. If not, do another pass saving them. Except this is probably
61 * useless as different rules could have different starting points for exprs
62 * or whatever. Decision trees could avoid this, but they have their own
63 * issues. */
64 /* TODO: will need to modify the parser so that it can essentially "catch"
65 * errors - maybe "try_parse_expr" or whatever methods. */
66 // this technically creates a back-tracking parser - this will be the
67 // implementation style
68
69 /* then, after results are saved, generate the macro output from the
70 * transcriber token tree. if i understand this correctly, the macro
71 * invocation gets replaced by the transcriber tokens, except with
72 * substitutions made (e.g. for $i variables) */
73
74 /* TODO: it is probably better to modify AST::Token to store a pointer to a
75 * Lexer::Token (rather than being converted) - i.e. not so much have
76 * AST::Token as a Token but rather a TokenContainer (as it is another type
77 * of TokenTree). This will prevent re-conversion of Tokens between each
78 * type all the time, while still allowing the heterogenous storage of token
79 * trees.
80 */
81
82 AST::DelimTokenTree &invoc_token_tree_sugar = invoc.get_delim_tok_tree ();
83
84 // We must first desugar doc comments into proper attributes
85 auto invoc_token_tree = AST::TokenTreeDesugar ().go (invoc_token_tree_sugar);
86
87 // find matching arm
88 AST::MacroRule *matched_rule = nullptr;
89 std::map<std::string, std::unique_ptr<MatchedFragmentContainer>>
90 matched_fragments;
91 for (auto &rule : rules_def.get_rules ())
92 {
93 sub_stack.push ();
94 bool did_match_rule = try_match_rule (rule, invoc_token_tree);
95 matched_fragments = sub_stack.pop ();
96
97 if (did_match_rule)
98 {
99 // // Debugging
100 // for (auto &kv : matched_fragments)
101 // rust_debug ("[fragment]: %s (%ld - %s)", kv.first.c_str (),
102 // kv.second.get_fragments ().size (),
103 // kv.second.get_kind ()
104 // == MatchedFragmentContainer::Kind::Repetition
105 // ? "repetition"
106 // : "metavar");
107
108 matched_rule = &rule;
109 break;
110 }
111 }
112
113 if (matched_rule == nullptr)
114 {
115 rich_location r (line_table, invoc_locus);
116 r.add_range (rules_def.get_locus ());
117 rust_error_at (r, "Failed to match any rule within macro");
118 return AST::Fragment::create_error ();
119 }
120
121 std::map<std::string, MatchedFragmentContainer *> matched_fragments_ptr;
122
123 for (auto &ent : matched_fragments)
124 matched_fragments_ptr.emplace (ent.first, ent.second.get ());
125
126 return transcribe_rule (rules_def, *matched_rule, invoc_token_tree,
127 matched_fragments_ptr, semicolon, peek_context ());
128 }
129
130 void
131 MacroExpander::expand_eager_invocations (AST::MacroInvocation &invoc)
132 {
133 if (invoc.get_pending_eager_invocations ().empty ())
134 return;
135
136 // We have to basically create a new delimited token tree which contains the
137 // result of one step of expansion. In the case of builtin macros called with
138 // other macro invocations, such as `concat!("h", 'a', a!())`, we need to
139 // expand `a!()` before expanding the concat macro.
140 // This will, ideally, give us a new token tree containing the various
141 // existing tokens + the result of the expansion of a!().
142 // To do this, we "parse" the given token tree to find anything that "looks
143 // like a macro invocation". Then, we get the corresponding macro invocation
144 // from the `pending_eager_invocations` vector and expand it.
145 // Because the `pending_eager_invocations` vector is created in the same order
146 // that the DelimTokenTree is parsed, we know that the first macro invocation
147 // within the DelimTokenTree corresponds to the first element in
148 // `pending_eager_invocations`. The idea is thus to:
149 // 1. Find a macro invocation in the token tree, noting the index of the start
150 // token and of the end token
151 // 2. Get its associated invocation in `pending_eager_invocations`
152 // 3. Expand that element
153 // 4. Get the token tree associated with that AST fragment
154 // 5. Replace the original tokens corresponding to the invocation with the new
155 // tokens from the fragment
156 // pseudo-code:
157 //
158 // i = 0;
159 // for tok in dtt:
160 // if tok is identifier && tok->next() is !:
161 // start = index(tok);
162 // l_delim = tok->next()->next();
163 // tok = skip_until_r_delim();
164 // end = index(tok);
165 //
166 // new_tt = expand_eager_invoc(eagers[i++]);
167 // old_tt[start..end] = new_tt;
168
169 auto dtt = invoc.get_invoc_data ().get_delim_tok_tree ();
170 auto stream = dtt.to_token_stream ();
171 std::vector<std::unique_ptr<AST::TokenTree>> new_stream;
172 size_t current_pending = 0;
173
174 // we need to create a clone of the delimited token tree as the lexer
175 // expects ownership of the tokens
176 std::vector<std::unique_ptr<Rust::AST::Token>> dtt_clone;
177 for (auto &tok : stream)
178 dtt_clone.emplace_back (tok->clone_token ());
179
180 MacroInvocLexer lex (std::move (dtt_clone));
181 Parser<MacroInvocLexer> parser (lex);
182
183 // we want to build a substitution map - basically, associating a `start` and
184 // `end` index for each of the pending macro invocations
185 std::map<std::pair<size_t, size_t>, std::unique_ptr<AST::MacroInvocation> &>
186 substitution_map;
187
188 for (size_t i = 0; i < stream.size (); i++)
189 {
190 // FIXME: Can't these offsets be figure out when we actually parse the
191 // pending_eager_invocation in the first place?
192 auto invocation = parser.parse_macro_invocation ({});
193
194 // if we've managed to parse a macro invocation, we look at the current
195 // offset and store them in the substitution map. Otherwise, we skip one
196 // token and try parsing again
197 if (invocation)
198 substitution_map.insert (
199 {{i, parser.get_token_source ().get_offs ()},
200 invoc.get_pending_eager_invocations ()[current_pending++]});
201 else
202 parser.skip_token (stream[i]->get_id ());
203 }
204
205 size_t current_idx = 0;
206 for (auto kv : substitution_map)
207 {
208 auto &to_expand = kv.second;
209 expand_invoc (*to_expand, AST::InvocKind::Expr);
210
211 auto fragment = take_expanded_fragment ();
212 auto &new_tokens = fragment.get_tokens ();
213
214 auto start = kv.first.first;
215 auto end = kv.first.second;
216
217 // We're now going to re-add the tokens to the invocation's token tree.
218 // 1. Basically, what we want to do is insert all tokens up until the
219 // beginning of the macro invocation (start).
220 // 2. Then, we'll insert all of the tokens resulting from the macro
221 // expansion: These are in `new_tokens`.
222 // 3. Finally, we'll do that again from
223 // the end of macro and go back to 1.
224
225 for (size_t i = current_idx; i < start; i++)
226 new_stream.emplace_back (stream[i]->clone_token ());
227
228 for (auto &tok : new_tokens)
229 new_stream.emplace_back (tok->clone_token ());
230
231 current_idx = end;
232 }
233
234 // Once all of that is done, we copy the last remaining tokens from the
235 // original stream
236 for (size_t i = current_idx; i < stream.size (); i++)
237 new_stream.emplace_back (stream[i]->clone_token ());
238
239 auto new_dtt
240 = AST::DelimTokenTree (dtt.get_delim_type (), std::move (new_stream));
241
242 invoc.get_pending_eager_invocations ().clear ();
243 invoc.get_invoc_data ().set_delim_tok_tree (new_dtt);
244 }
245
246 void
247 MacroExpander::expand_invoc (AST::MacroInvocation &invoc,
248 AST::InvocKind semicolon)
249 {
250 if (depth_exceeds_recursion_limit ())
251 {
252 rust_error_at (invoc.get_locus (), "reached recursion limit");
253 return;
254 }
255
256 if (invoc.get_kind () == AST::MacroInvocation::InvocKind::Builtin)
257 {
258 // Eager expansions are always expressions
259 push_context (ContextType::EXPR);
260 expand_eager_invocations (invoc);
261 pop_context ();
262 }
263
264 AST::MacroInvocData &invoc_data = invoc.get_invoc_data ();
265
266 // ??
267 // switch on type of macro:
268 // - '!' syntax macro (inner switch)
269 // - procedural macro - "A token-based function-like macro"
270 // - 'macro_rules' (by example/pattern-match) macro? or not? "an
271 // AST-based function-like macro"
272 // - else is unreachable
273 // - attribute syntax macro (inner switch)
274 // - procedural macro attribute syntax - "A token-based attribute
275 // macro"
276 // - legacy macro attribute syntax? - "an AST-based attribute macro"
277 // - non-macro attribute: mark known
278 // - else is unreachable
279 // - derive macro (inner switch)
280 // - derive or legacy derive - "token-based" vs "AST-based"
281 // - else is unreachable
282 // - derive container macro - unreachable
283
284 auto fragment = AST::Fragment::create_error ();
285 invoc_data.set_expander (this);
286
287 // lookup the rules
288 auto rules_def = mappings.lookup_macro_invocation (invoc);
289
290 // If there's no rule associated with the invocation, we can simply return
291 // early. The early name resolver will have already emitted an error.
292 if (!rules_def)
293 return;
294
295 auto rdef = rules_def.value ();
296
297 // We store the last expanded invocation and macro definition for error
298 // reporting in case the recursion limit is reached
299 last_invoc = *invoc.clone_macro_invocation_impl ();
300 last_def = *rdef;
301
302 if (rdef->is_builtin ())
303 fragment = rdef
304 ->get_builtin_transcriber () (invoc.get_locus (), invoc_data,
305 semicolon)
306 .value_or (AST::Fragment::create_empty ());
307 else
308 fragment
309 = expand_decl_macro (invoc.get_locus (), invoc_data, *rdef, semicolon);
310
311 set_expanded_fragment (std::move (fragment));
312 }
313
314 void
315 MacroExpander::expand_crate ()
316 {
317 NodeId scope_node_id = crate.get_node_id ();
318 resolver->get_macro_scope ().push (scope_node_id);
319
320 /* fill macro/decorator map from init list? not sure where init list comes
321 * from? */
322
323 // TODO: does cfg apply for inner attributes? research.
324 // the apparent answer (from playground test) is yes
325
326 push_context (ContextType::ITEM);
327
328 // expand attributes recursively and strip items if required
329 // AttrVisitor attr_visitor (*this);
330 auto &items = crate.items;
331 for (auto it = items.begin (); it != items.end ();)
332 {
333 auto &item = *it;
334
335 auto fragment = take_expanded_fragment ();
336 if (fragment.should_expand ())
337 {
338 // Remove the current expanded invocation
339 it = items.erase (it);
340 for (auto &node : fragment.get_nodes ())
341 {
342 it = items.insert (it, node.take_item ());
343 it++;
344 }
345 }
346 else if (item->is_marked_for_strip ())
347 it = items.erase (it);
348 else
349 it++;
350 }
351
352 pop_context ();
353
354 // TODO: should recursive attribute and macro expansion be done in the same
355 // transversal? Or in separate ones like currently?
356
357 // expand module tree recursively
358
359 // post-process
360
361 // extract exported macros?
362 }
363
364 bool
365 MacroExpander::depth_exceeds_recursion_limit () const
366 {
367 return expansion_depth >= cfg.recursion_limit;
368 }
369
370 bool
371 MacroExpander::try_match_rule (AST::MacroRule &match_rule,
372 AST::DelimTokenTree &invoc_token_tree)
373 {
374 MacroInvocLexer lex (invoc_token_tree.to_token_stream ());
375 Parser<MacroInvocLexer> parser (lex);
376
377 AST::MacroMatcher &matcher = match_rule.get_matcher ();
378
379 expansion_depth++;
380 if (!match_matcher (parser, matcher, false, false))
381 {
382 expansion_depth--;
383 return false;
384 }
385 expansion_depth--;
386
387 bool used_all_input_tokens = parser.skip_token (END_OF_FILE);
388 return used_all_input_tokens;
389 }
390
391 bool
392 MacroExpander::match_fragment (Parser<MacroInvocLexer> &parser,
393 AST::MacroMatchFragment &fragment)
394 {
395 switch (fragment.get_frag_spec ().get_kind ())
396 {
397 case AST::MacroFragSpec::EXPR:
398 parser.parse_expr ();
399 break;
400
401 case AST::MacroFragSpec::BLOCK:
402 parser.parse_block_expr ();
403 break;
404
405 case AST::MacroFragSpec::IDENT:
406 parser.parse_identifier_or_keyword_token ();
407 break;
408
409 case AST::MacroFragSpec::LITERAL:
410 parser.parse_literal_expr ();
411 break;
412
413 case AST::MacroFragSpec::ITEM:
414 parser.parse_item (false);
415 break;
416
417 case AST::MacroFragSpec::TY:
418 parser.parse_type ();
419 break;
420
421 case AST::MacroFragSpec::PAT:
422 parser.parse_pattern ();
423 break;
424
425 case AST::MacroFragSpec::PATH:
426 parser.parse_path_in_expression ();
427 break;
428
429 case AST::MacroFragSpec::VIS:
430 parser.parse_visibility ();
431 break;
432
433 case AST::MacroFragSpec::STMT: {
434 auto restrictions = ParseRestrictions ();
435 restrictions.consume_semi = false;
436 parser.parse_stmt (restrictions);
437 break;
438 }
439
440 case AST::MacroFragSpec::LIFETIME:
441 parser.parse_lifetime_params ();
442 break;
443
444 // is meta attributes?
445 case AST::MacroFragSpec::META:
446 parser.parse_attribute_body ();
447 break;
448
449 case AST::MacroFragSpec::TT:
450 parser.parse_token_tree ();
451 break;
452
453 // i guess we just ignore invalid and just error out
454 case AST::MacroFragSpec::INVALID:
455 return false;
456 }
457
458 // it matches if the parser did not produce errors trying to parse that type
459 // of item
460 return !parser.has_errors ();
461 }
462
463 bool
464 MacroExpander::match_matcher (Parser<MacroInvocLexer> &parser,
465 AST::MacroMatcher &matcher, bool in_repetition,
466 bool match_delim)
467 {
468 if (depth_exceeds_recursion_limit ())
469 {
470 rust_error_at (matcher.get_match_locus (), "reached recursion limit");
471 return false;
472 }
473
474 auto delimiter = parser.peek_current_token ();
475
476 auto check_delim = [&matcher, match_delim] (AST::DelimType delim) {
477 return !match_delim || matcher.get_delim_type () == delim;
478 };
479
480 // this is used so we can check that we delimit the stream correctly.
481 switch (delimiter->get_id ())
482 {
483 case LEFT_PAREN: {
484 if (!check_delim (AST::DelimType::PARENS))
485 return false;
486 }
487 break;
488
489 case LEFT_SQUARE: {
490 if (!check_delim (AST::DelimType::SQUARE))
491 return false;
492 }
493 break;
494
495 case LEFT_CURLY: {
496 if (!check_delim (AST::DelimType::CURLY))
497 return false;
498 }
499 break;
500 default:
501 return false;
502 }
503 parser.skip_token ();
504
505 const MacroInvocLexer &source = parser.get_token_source ();
506
507 for (auto &match : matcher.get_matches ())
508 {
509 size_t offs_begin = source.get_offs ();
510
511 switch (match->get_macro_match_type ())
512 {
513 case AST::MacroMatch::MacroMatchType::Fragment: {
514 AST::MacroMatchFragment *fragment
515 = static_cast<AST::MacroMatchFragment *> (match.get ());
516 if (!match_fragment (parser, *fragment))
517 return false;
518
519 // matched fragment get the offset in the token stream
520 size_t offs_end = source.get_offs ();
521 sub_stack.insert_metavar (
522 MatchedFragment (fragment->get_ident ().as_string (), offs_begin,
523 offs_end));
524 }
525 break;
526
527 case AST::MacroMatch::MacroMatchType::Tok: {
528 AST::Token *tok = static_cast<AST::Token *> (match.get ());
529 if (!match_token (parser, *tok))
530 return false;
531 }
532 break;
533
534 case AST::MacroMatch::MacroMatchType::Repetition: {
535 AST::MacroMatchRepetition *rep
536 = static_cast<AST::MacroMatchRepetition *> (match.get ());
537 if (!match_repetition (parser, *rep))
538 return false;
539 }
540 break;
541
542 case AST::MacroMatch::MacroMatchType::Matcher: {
543 AST::MacroMatcher *m
544 = static_cast<AST::MacroMatcher *> (match.get ());
545 expansion_depth++;
546 if (!match_matcher (parser, *m, in_repetition))
547 {
548 expansion_depth--;
549 return false;
550 }
551 expansion_depth--;
552 }
553 break;
554 }
555 }
556
557 switch (delimiter->get_id ())
558 {
559 case LEFT_PAREN: {
560 if (!parser.skip_token (RIGHT_PAREN))
561 return false;
562 }
563 break;
564
565 case LEFT_SQUARE: {
566 if (!parser.skip_token (RIGHT_SQUARE))
567 return false;
568 }
569 break;
570
571 case LEFT_CURLY: {
572 if (!parser.skip_token (RIGHT_CURLY))
573 return false;
574 }
575 break;
576 default:
577 rust_unreachable ();
578 }
579
580 return true;
581 }
582
583 bool
584 MacroExpander::match_token (Parser<MacroInvocLexer> &parser, AST::Token &token)
585 {
586 return parser.skip_token (token.get_tok_ptr ());
587 }
588
589 bool
590 MacroExpander::match_n_matches (Parser<MacroInvocLexer> &parser,
591 AST::MacroMatchRepetition &rep,
592 size_t &match_amount, size_t lo_bound,
593 size_t hi_bound)
594 {
595 match_amount = 0;
596 auto &matches = rep.get_matches ();
597
598 const MacroInvocLexer &source = parser.get_token_source ();
599 while (true)
600 {
601 // If the current token is a closing macro delimiter, break away.
602 // TODO: Is this correct?
603 auto t_id = parser.peek_current_token ()->get_id ();
604 if (t_id == RIGHT_PAREN || t_id == RIGHT_SQUARE || t_id == RIGHT_CURLY)
605 break;
606
607 // Skip parsing a separator on the first match, otherwise consume it.
608 // If it isn't present, this is an error
609 if (rep.has_sep () && match_amount > 0)
610 if (!match_token (parser, *rep.get_sep ()))
611 break;
612
613 sub_stack.push ();
614 bool valid_current_match = false;
615 for (auto &match : matches)
616 {
617 size_t offs_begin = source.get_offs ();
618 switch (match->get_macro_match_type ())
619 {
620 case AST::MacroMatch::MacroMatchType::Fragment: {
621 AST::MacroMatchFragment *fragment
622 = static_cast<AST::MacroMatchFragment *> (match.get ());
623 valid_current_match = match_fragment (parser, *fragment);
624
625 // matched fragment get the offset in the token stream
626 size_t offs_end = source.get_offs ();
627
628 if (valid_current_match)
629 sub_stack.insert_metavar (
630 MatchedFragment (fragment->get_ident ().as_string (),
631 offs_begin, offs_end));
632 }
633 break;
634
635 case AST::MacroMatch::MacroMatchType::Tok: {
636 AST::Token *tok = static_cast<AST::Token *> (match.get ());
637 valid_current_match = match_token (parser, *tok);
638 }
639 break;
640
641 case AST::MacroMatch::MacroMatchType::Repetition: {
642 AST::MacroMatchRepetition *rep
643 = static_cast<AST::MacroMatchRepetition *> (match.get ());
644 valid_current_match = match_repetition (parser, *rep);
645 }
646 break;
647
648 case AST::MacroMatch::MacroMatchType::Matcher: {
649 AST::MacroMatcher *m
650 = static_cast<AST::MacroMatcher *> (match.get ());
651 valid_current_match = match_matcher (parser, *m, true);
652 }
653 break;
654 }
655 }
656 auto old_stack = sub_stack.pop ();
657
658 // If we've encountered an error once, stop trying to match more
659 // repetitions
660 if (!valid_current_match)
661 break;
662
663 // nest metavars into repetitions
664 for (auto &ent : old_stack)
665 sub_stack.append_fragment (ent.first, std::move (ent.second));
666
667 match_amount++;
668
669 // Break early if we notice there's too many expressions already
670 if (hi_bound && match_amount > hi_bound)
671 break;
672 }
673
674 // Check if the amount of matches we got is valid: Is it more than the lower
675 // bound and less than the higher bound?
676 bool did_meet_lo_bound = match_amount >= lo_bound;
677 bool did_meet_hi_bound = hi_bound ? match_amount <= hi_bound : true;
678
679 // If the end-result is valid, then we can clear the parse errors: Since
680 // repetitions are parsed eagerly, it is okay to fail in some cases
681 auto res = did_meet_lo_bound && did_meet_hi_bound;
682 if (res)
683 parser.clear_errors ();
684
685 return res;
686 }
687
688 /*
689 * Helper function for defining unmatched repetition metavars
690 */
691 void
692 MacroExpander::match_repetition_skipped_metavars (AST::MacroMatch &match)
693 {
694 // We have to handle zero fragments differently: They will not have been
695 // "matched" but they are still valid and should be inserted as a special
696 // case. So we go through the stack map, and for every fragment which doesn't
697 // exist, insert a zero-matched fragment.
698 switch (match.get_macro_match_type ())
699 {
700 case AST::MacroMatch::MacroMatchType::Fragment:
701 match_repetition_skipped_metavars (
702 static_cast<AST::MacroMatchFragment &> (match));
703 break;
704 case AST::MacroMatch::MacroMatchType::Repetition:
705 match_repetition_skipped_metavars (
706 static_cast<AST::MacroMatchRepetition &> (match));
707 break;
708 case AST::MacroMatch::MacroMatchType::Matcher:
709 match_repetition_skipped_metavars (
710 static_cast<AST::MacroMatcher &> (match));
711 break;
712 case AST::MacroMatch::MacroMatchType::Tok:
713 break;
714 }
715 }
716
717 void
718 MacroExpander::match_repetition_skipped_metavars (
719 AST::MacroMatchFragment &fragment)
720 {
721 auto &stack_map = sub_stack.peek ();
722 auto it = stack_map.find (fragment.get_ident ().as_string ());
723
724 if (it == stack_map.end ())
725 sub_stack.insert_matches (fragment.get_ident ().as_string (),
726 MatchedFragmentContainer::zero ());
727 }
728
729 void
730 MacroExpander::match_repetition_skipped_metavars (
731 AST::MacroMatchRepetition &rep)
732 {
733 for (auto &match : rep.get_matches ())
734 match_repetition_skipped_metavars (*match);
735 }
736
737 void
738 MacroExpander::match_repetition_skipped_metavars (AST::MacroMatcher &rep)
739 {
740 for (auto &match : rep.get_matches ())
741 match_repetition_skipped_metavars (*match);
742 }
743
744 bool
745 MacroExpander::match_repetition (Parser<MacroInvocLexer> &parser,
746 AST::MacroMatchRepetition &rep)
747 {
748 size_t match_amount = 0;
749 bool res = false;
750
751 std::string lo_str;
752 std::string hi_str;
753 switch (rep.get_op ())
754 {
755 case AST::MacroMatchRepetition::MacroRepOp::ANY:
756 lo_str = "0";
757 hi_str = "+inf";
758 res = match_n_matches (parser, rep, match_amount);
759 break;
760 case AST::MacroMatchRepetition::MacroRepOp::ONE_OR_MORE:
761 lo_str = "1";
762 hi_str = "+inf";
763 res = match_n_matches (parser, rep, match_amount, 1);
764 break;
765 case AST::MacroMatchRepetition::MacroRepOp::ZERO_OR_ONE:
766 lo_str = "0";
767 hi_str = "1";
768 res = match_n_matches (parser, rep, match_amount, 0, 1);
769 break;
770 default:
771 rust_unreachable ();
772 }
773
774 rust_debug_loc (rep.get_match_locus (), "%s matched %lu times",
775 res ? "successfully" : "unsuccessfully",
776 (unsigned long) match_amount);
777
778 match_repetition_skipped_metavars (rep);
779
780 return res;
781 }
782
783 /**
784 * Helper function to refactor calling a parsing function 0 or more times
785 */
786 static AST::Fragment
787 parse_many (Parser<MacroInvocLexer> &parser, TokenId delimiter,
788 std::function<AST::SingleASTNode ()> parse_fn)
789 {
790 auto &lexer = parser.get_token_source ();
791 auto start = lexer.get_offs ();
792
793 std::vector<AST::SingleASTNode> nodes;
794 while (true)
795 {
796 if (parser.peek_current_token ()->get_id () == delimiter)
797 break;
798
799 auto node = parse_fn ();
800 if (node.is_error ())
801 {
802 for (auto err : parser.get_errors ())
803 err.emit ();
804
805 return AST::Fragment::create_error ();
806 }
807
808 nodes.emplace_back (std::move (node));
809 }
810 auto end = lexer.get_offs ();
811
812 return AST::Fragment (std::move (nodes), lexer.get_token_slice (start, end));
813 }
814
815 /**
816 * Transcribe 0 or more items from a macro invocation
817 *
818 * @param parser Parser to extract items from
819 * @param delimiter Id of the token on which parsing should stop
820 */
821 static AST::Fragment
822 transcribe_many_items (Parser<MacroInvocLexer> &parser, TokenId &delimiter)
823 {
824 return parse_many (parser, delimiter, [&parser] () {
825 auto item = parser.parse_item (true);
826 return AST::SingleASTNode (std::move (item));
827 });
828 }
829
830 /**
831 * Transcribe 0 or more external items from a macro invocation
832 *
833 * @param parser Parser to extract items from
834 * @param delimiter Id of the token on which parsing should stop
835 */
836 static AST::Fragment
837 transcribe_many_ext (Parser<MacroInvocLexer> &parser, TokenId &delimiter)
838 {
839 return parse_many (parser, delimiter, [&parser] () {
840 auto item = parser.parse_external_item ();
841 return AST::SingleASTNode (std::move (item));
842 });
843 }
844
845 /**
846 * Transcribe 0 or more trait items from a macro invocation
847 *
848 * @param parser Parser to extract items from
849 * @param delimiter Id of the token on which parsing should stop
850 */
851 static AST::Fragment
852 transcribe_many_trait_items (Parser<MacroInvocLexer> &parser,
853 TokenId &delimiter)
854 {
855 return parse_many (parser, delimiter, [&parser] () {
856 auto item = parser.parse_trait_item ();
857 return AST::SingleASTNode (std::move (item));
858 });
859 }
860
861 /**
862 * Transcribe 0 or more impl items from a macro invocation
863 *
864 * @param parser Parser to extract items from
865 * @param delimiter Id of the token on which parsing should stop
866 */
867 static AST::Fragment
868 transcribe_many_impl_items (Parser<MacroInvocLexer> &parser, TokenId &delimiter)
869 {
870 return parse_many (parser, delimiter, [&parser] () {
871 auto item = parser.parse_inherent_impl_item ();
872 return AST::SingleASTNode (std::move (item));
873 });
874 }
875
876 /**
877 * Transcribe 0 or more trait impl items from a macro invocation
878 *
879 * @param parser Parser to extract items from
880 * @param delimiter Id of the token on which parsing should stop
881 */
882 static AST::Fragment
883 transcribe_many_trait_impl_items (Parser<MacroInvocLexer> &parser,
884 TokenId &delimiter)
885 {
886 return parse_many (parser, delimiter, [&parser] () {
887 auto item = parser.parse_trait_impl_item ();
888 return AST::SingleASTNode (std::move (item));
889 });
890 }
891
892 /**
893 * Transcribe 0 or more statements from a macro invocation
894 *
895 * @param parser Parser to extract statements from
896 * @param delimiter Id of the token on which parsing should stop
897 */
898 static AST::Fragment
899 transcribe_many_stmts (Parser<MacroInvocLexer> &parser, TokenId delimiter,
900 bool semicolon)
901 {
902 auto restrictions = ParseRestrictions ();
903 restrictions.allow_close_after_expr_stmt = true;
904
905 return parse_many (parser, delimiter,
906 [&parser, restrictions, delimiter, semicolon] () {
907 auto stmt = parser.parse_stmt (restrictions);
908 if (semicolon && stmt
909 && parser.peek_current_token ()->get_id ()
910 == delimiter)
911 stmt->add_semicolon ();
912
913 return AST::SingleASTNode (std::move (stmt));
914 });
915 }
916
917 /**
918 * Transcribe one expression from a macro invocation
919 *
920 * @param parser Parser to extract statements from
921 */
922 static AST::Fragment
923 transcribe_expression (Parser<MacroInvocLexer> &parser)
924 {
925 auto &lexer = parser.get_token_source ();
926 auto start = lexer.get_offs ();
927
928 auto expr = parser.parse_expr ();
929 if (expr == nullptr)
930 return AST::Fragment::create_error ();
931
932 // FIXME: make this an error for some edititons
933 if (parser.peek_current_token ()->get_id () == SEMICOLON)
934 {
935 rust_warning_at (
936 parser.peek_current_token ()->get_locus (), 0,
937 "trailing semicolon in macro used in expression context");
938 parser.skip_token ();
939 }
940
941 auto end = lexer.get_offs ();
942
943 return AST::Fragment ({std::move (expr)}, lexer.get_token_slice (start, end));
944 }
945
946 /**
947 * Transcribe one type from a macro invocation
948 *
949 * @param parser Parser to extract statements from
950 */
951 static AST::Fragment
952 transcribe_type (Parser<MacroInvocLexer> &parser)
953 {
954 auto &lexer = parser.get_token_source ();
955 auto start = lexer.get_offs ();
956
957 auto type = parser.parse_type (true);
958 for (auto err : parser.get_errors ())
959 err.emit ();
960
961 auto end = lexer.get_offs ();
962
963 return AST::Fragment ({std::move (type)}, lexer.get_token_slice (start, end));
964 }
965
966 static AST::Fragment
967 transcribe_context (MacroExpander::ContextType ctx,
968 Parser<MacroInvocLexer> &parser, bool semicolon,
969 AST::DelimType delimiter, TokenId last_token_id)
970 {
971 // The flow-chart in order to choose a parsing function is as follows:
972 //
973 // [switch special context]
974 // -- Item --> parser.parse_item();
975 // -- Trait --> parser.parse_trait_item();
976 // -- Impl --> parser.parse_impl_item();
977 // -- Extern --> parser.parse_extern_item();
978 // -- None --> [has semicolon?]
979 // -- Yes --> parser.parse_stmt();
980 // -- No --> [switch invocation.delimiter()]
981 // -- { } --> parser.parse_stmt();
982 // -- _ --> parser.parse_expr(); // once!
983
984 // If there is a semicolon OR we are expanding a MacroInvocationSemi, then
985 // we can parse multiple items. Otherwise, parse *one* expression
986
987 switch (ctx)
988 {
989 case MacroExpander::ContextType::ITEM:
990 return transcribe_many_items (parser, last_token_id);
991 break;
992 case MacroExpander::ContextType::TRAIT:
993 return transcribe_many_trait_items (parser, last_token_id);
994 break;
995 case MacroExpander::ContextType::IMPL:
996 return transcribe_many_impl_items (parser, last_token_id);
997 break;
998 case MacroExpander::ContextType::TRAIT_IMPL:
999 return transcribe_many_trait_impl_items (parser, last_token_id);
1000 break;
1001 case MacroExpander::ContextType::EXTERN:
1002 return transcribe_many_ext (parser, last_token_id);
1003 break;
1004 case MacroExpander::ContextType::TYPE:
1005 return transcribe_type (parser);
1006 break;
1007 case MacroExpander::ContextType::STMT:
1008 return transcribe_many_stmts (parser, last_token_id, semicolon);
1009 case MacroExpander::ContextType::EXPR:
1010 return transcribe_expression (parser);
1011 default:
1012 rust_unreachable ();
1013 }
1014 }
1015
1016 static std::string
1017 tokens_to_str (std::vector<std::unique_ptr<AST::Token>> &tokens)
1018 {
1019 std::string str;
1020 if (!tokens.empty ())
1021 {
1022 str += tokens[0]->as_string ();
1023 for (size_t i = 1; i < tokens.size (); i++)
1024 str += " " + tokens[i]->as_string ();
1025 }
1026
1027 return str;
1028 }
1029
1030 AST::Fragment
1031 MacroExpander::transcribe_rule (
1032 AST::MacroRulesDefinition &definition, AST::MacroRule &match_rule,
1033 AST::DelimTokenTree &invoc_token_tree,
1034 std::map<std::string, MatchedFragmentContainer *> &matched_fragments,
1035 AST::InvocKind invoc_kind, ContextType ctx)
1036 {
1037 bool semicolon = invoc_kind == AST::InvocKind::Semicoloned;
1038
1039 // we can manipulate the token tree to substitute the dollar identifiers so
1040 // that when we call parse its already substituted for us
1041 AST::MacroTranscriber &transcriber = match_rule.get_transcriber ();
1042 AST::DelimTokenTree &transcribe_tree = transcriber.get_token_tree ();
1043
1044 auto invoc_stream = invoc_token_tree.to_token_stream ();
1045 auto macro_rule_tokens = transcribe_tree.to_token_stream ();
1046
1047 auto substitute_context = SubstituteCtx (invoc_stream, macro_rule_tokens,
1048 matched_fragments, definition);
1049 std::vector<std::unique_ptr<AST::Token>> substituted_tokens
1050 = substitute_context.substitute_tokens ();
1051
1052 rust_debug ("substituted tokens: %s",
1053 tokens_to_str (substituted_tokens).c_str ());
1054
1055 // parse it to an Fragment
1056 MacroInvocLexer lex (std::move (substituted_tokens));
1057 Parser<MacroInvocLexer> parser (lex);
1058
1059 auto last_token_id = TokenId::RIGHT_CURLY;
1060
1061 // this is used so we can check that we delimit the stream correctly.
1062 switch (transcribe_tree.get_delim_type ())
1063 {
1064 case AST::DelimType::PARENS:
1065 last_token_id = TokenId::RIGHT_PAREN;
1066 rust_assert (parser.skip_token (LEFT_PAREN));
1067 break;
1068
1069 case AST::DelimType::CURLY:
1070 rust_assert (parser.skip_token (LEFT_CURLY));
1071 break;
1072
1073 case AST::DelimType::SQUARE:
1074 last_token_id = TokenId::RIGHT_SQUARE;
1075 rust_assert (parser.skip_token (LEFT_SQUARE));
1076 break;
1077 }
1078
1079 // see https://github.com/Rust-GCC/gccrs/issues/22
1080 // TL;DR:
1081 // - Treat all macro invocations with parentheses, (), or square brackets,
1082 // [], as expressions.
1083 // - If the macro invocation has curly brackets, {}, it may be parsed as a
1084 // statement depending on the context.
1085 // - If the macro invocation has a semicolon at the end, it must be parsed
1086 // as a statement (either via ExpressionStatement or
1087 // MacroInvocationWithSemi)
1088
1089 auto fragment
1090 = transcribe_context (ctx, parser, semicolon,
1091 invoc_token_tree.get_delim_type (), last_token_id);
1092
1093 // emit any errors
1094 if (parser.has_errors ())
1095 {
1096 for (auto &err : parser.get_errors ())
1097 rust_error_at (err.locus, "%s", err.message.c_str ());
1098 return AST::Fragment::create_error ();
1099 }
1100
1101 // are all the tokens used?
1102 bool did_delimit = parser.skip_token (last_token_id);
1103
1104 bool reached_end_of_stream = did_delimit && parser.skip_token (END_OF_FILE);
1105 if (!reached_end_of_stream)
1106 {
1107 // FIXME: rustc has some cases it accepts this with a warning due to
1108 // backwards compatibility.
1109 const_TokenPtr current_token = parser.peek_current_token ();
1110 rust_error_at (current_token->get_locus (),
1111 "tokens here and after are unparsed");
1112 }
1113
1114 return fragment;
1115 }
1116
1117 AST::Fragment
1118 MacroExpander::parse_proc_macro_output (ProcMacro::TokenStream ts)
1119 {
1120 ProcMacroInvocLexer lex (convert (ts));
1121 Parser<ProcMacroInvocLexer> parser (lex);
1122
1123 std::vector<AST::SingleASTNode> nodes;
1124 switch (peek_context ())
1125 {
1126 case ContextType::ITEM:
1127 while (lex.peek_token ()->get_id () != END_OF_FILE)
1128 {
1129 auto result = parser.parse_item (false);
1130 if (result == nullptr)
1131 break;
1132 nodes.push_back ({std::move (result)});
1133 }
1134 break;
1135 case ContextType::STMT:
1136 while (lex.peek_token ()->get_id () != END_OF_FILE)
1137 {
1138 auto result = parser.parse_stmt ();
1139 if (result == nullptr)
1140 break;
1141 nodes.push_back ({std::move (result)});
1142 }
1143 break;
1144 case ContextType::TRAIT:
1145 case ContextType::IMPL:
1146 case ContextType::TRAIT_IMPL:
1147 case ContextType::EXTERN:
1148 case ContextType::TYPE:
1149 case ContextType::EXPR:
1150 default:
1151 rust_unreachable ();
1152 }
1153
1154 if (parser.has_errors ())
1155 return AST::Fragment::create_error ();
1156 else
1157 return {nodes, std::vector<std::unique_ptr<AST::Token>> ()};
1158 }
1159
1160 MatchedFragment &
1161 MatchedFragmentContainer::get_single_fragment ()
1162 {
1163 rust_assert (is_single_fragment ());
1164
1165 return static_cast<MatchedFragmentContainerMetaVar &> (*this).get_fragment ();
1166 }
1167
1168 std::vector<std::unique_ptr<MatchedFragmentContainer>> &
1169 MatchedFragmentContainer::get_fragments ()
1170 {
1171 rust_assert (!is_single_fragment ());
1172
1173 return static_cast<MatchedFragmentContainerRepetition &> (*this)
1174 .get_fragments ();
1175 }
1176
1177 void
1178 MatchedFragmentContainer::add_fragment (MatchedFragment fragment)
1179 {
1180 rust_assert (!is_single_fragment ());
1181
1182 return static_cast<MatchedFragmentContainerRepetition &> (*this)
1183 .add_fragment (fragment);
1184 }
1185
1186 void
1187 MatchedFragmentContainer::add_fragment (
1188 std::unique_ptr<MatchedFragmentContainer> fragment)
1189 {
1190 rust_assert (!is_single_fragment ());
1191
1192 return static_cast<MatchedFragmentContainerRepetition &> (*this)
1193 .add_fragment (std::move (fragment));
1194 }
1195
1196 std::unique_ptr<MatchedFragmentContainer>
1197 MatchedFragmentContainer::zero ()
1198 {
1199 return std::unique_ptr<MatchedFragmentContainer> (
1200 new MatchedFragmentContainerRepetition ());
1201 }
1202
1203 std::unique_ptr<MatchedFragmentContainer>
1204 MatchedFragmentContainer::metavar (MatchedFragment fragment)
1205 {
1206 return std::unique_ptr<MatchedFragmentContainer> (
1207 new MatchedFragmentContainerMetaVar (fragment));
1208 }
1209
1210 } // namespace Rust