Branch data Line data Source code
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 : : #ifndef RUST_MACRO_EXPAND_H
20 : : #define RUST_MACRO_EXPAND_H
21 : :
22 : : #include "optional.h"
23 : : #include "rust-ast-fragment.h"
24 : : #include "rust-buffered-queue.h"
25 : : #include "rust-parse.h"
26 : : #include "rust-token.h"
27 : : #include "rust-ast.h"
28 : : #include "rust-macro.h"
29 : : #include "rust-hir-map.h"
30 : : #include "rust-name-resolver.h"
31 : : #include "rust-macro-invoc-lexer.h"
32 : : #include "rust-proc-macro-invoc-lexer.h"
33 : : #include "rust-token-converter.h"
34 : : #include "rust-ast-collector.h"
35 : : #include "rust-system.h"
36 : : #include "libproc_macro_internal/proc_macro.h"
37 : :
38 : : // Provides objects and method prototypes for macro expansion
39 : :
40 : : namespace Rust {
41 : : // forward decls for AST
42 : : namespace AST {
43 : : class MacroInvocation;
44 : : }
45 : :
46 : : // Object used to store configuration data for macro expansion.
47 : : // NOTE: Keep all these items complying with the latest rustc.
48 : 8898 : struct ExpansionCfg
49 : : {
50 : : // features?
51 : : // TODO: Add `features' when we have it.
52 : : unsigned int recursion_limit = 1024;
53 : : bool trace_mac = false; // trace macro
54 : : bool should_test = false; // strip #[test] nodes if false
55 : : bool keep_macs = false; // keep macro definitions
56 : : std::string crate_name = "";
57 : : };
58 : :
59 : 206249 : struct MatchedFragment
60 : : {
61 : : std::string fragment_ident;
62 : : size_t token_offset_begin;
63 : : size_t token_offset_end;
64 : :
65 : 206249 : MatchedFragment (std::string identifier, size_t token_offset_begin,
66 : : size_t token_offset_end)
67 : 206249 : : fragment_ident (identifier), token_offset_begin (token_offset_begin),
68 : 206249 : token_offset_end (token_offset_end)
69 : : {}
70 : :
71 : : /**
72 : : * Empty constructor for uninitialized fragments
73 : : */
74 : : MatchedFragment () : MatchedFragment ("", 0, 0) {}
75 : :
76 : 0 : std::string as_string () const
77 : : {
78 : 0 : return fragment_ident + "=" + std::to_string (token_offset_begin) + ":"
79 : 0 : + std::to_string (token_offset_end);
80 : : }
81 : : };
82 : :
83 : 211120 : class MatchedFragmentContainer
84 : : {
85 : : public:
86 : : // Does the container refer to a simple metavariable, different from a
87 : : // repetition repeated once
88 : : enum class Kind
89 : : {
90 : : MetaVar,
91 : : Repetition,
92 : : };
93 : :
94 : : virtual ~MatchedFragmentContainer () = default;
95 : :
96 : : virtual Kind get_kind () const = 0;
97 : :
98 : : virtual std::string as_string () const = 0;
99 : :
100 : : /**
101 : : * Create a valid fragment matched zero times. This is useful for repetitions
102 : : * which allow the absence of a fragment, such as * and ?
103 : : */
104 : : static std::unique_ptr<MatchedFragmentContainer> zero ();
105 : :
106 : : /**
107 : : * Create a valid fragment matched one time
108 : : */
109 : : static std::unique_ptr<MatchedFragmentContainer>
110 : : metavar (MatchedFragment fragment);
111 : :
112 : : /**
113 : : * Add a matched fragment to the container
114 : : */
115 : : void add_fragment (MatchedFragment fragment);
116 : :
117 : : /**
118 : : * Add a matched fragment to the container
119 : : */
120 : : void add_fragment (std::unique_ptr<MatchedFragmentContainer> fragment);
121 : :
122 : : // const std::string &get_fragment_name () const { return fragment_name; }
123 : :
124 : 896439 : bool is_single_fragment () const { return get_kind () == Kind::MetaVar; }
125 : :
126 : : MatchedFragment &get_single_fragment ();
127 : :
128 : : std::vector<std::unique_ptr<MatchedFragmentContainer>> &get_fragments ();
129 : : };
130 : :
131 : : class MatchedFragmentContainerMetaVar : public MatchedFragmentContainer
132 : : {
133 : : MatchedFragment fragment;
134 : :
135 : : public:
136 : 206249 : MatchedFragmentContainerMetaVar (const MatchedFragment &fragment)
137 : 206249 : : fragment (fragment)
138 : : {}
139 : :
140 : 344417 : MatchedFragment &get_fragment () { return fragment; }
141 : :
142 : 726723 : virtual Kind get_kind () const { return Kind::MetaVar; }
143 : :
144 : 0 : virtual std::string as_string () const { return fragment.as_string (); }
145 : : };
146 : :
147 : : class MatchedFragmentContainerRepetition : public MatchedFragmentContainer
148 : : {
149 : : std::vector<std::unique_ptr<MatchedFragmentContainer>> fragments;
150 : :
151 : : public:
152 : 4871 : MatchedFragmentContainerRepetition () {}
153 : :
154 : 6999 : size_t get_match_amount () const { return fragments.size (); }
155 : :
156 : 87674 : std::vector<std::unique_ptr<MatchedFragmentContainer>> &get_fragments ()
157 : : {
158 : 87674 : return fragments;
159 : : }
160 : :
161 : : /**
162 : : * Add a matched fragment to the container
163 : : */
164 : 0 : void add_fragment (MatchedFragment fragment)
165 : : {
166 : 0 : add_fragment (metavar (fragment));
167 : 0 : }
168 : :
169 : : /**
170 : : * Add a matched fragment to the container
171 : : */
172 : 31015 : void add_fragment (std::unique_ptr<MatchedFragmentContainer> fragment)
173 : : {
174 : 31015 : fragments.emplace_back (std::move (fragment));
175 : : }
176 : :
177 : 169716 : virtual Kind get_kind () const { return Kind::Repetition; }
178 : :
179 : 0 : virtual std::string as_string () const
180 : : {
181 : 0 : std::string acc = "[";
182 : 0 : for (size_t i = 0; i < fragments.size (); i++)
183 : : {
184 : 0 : if (i)
185 : 0 : acc += " ";
186 : 0 : acc += fragments[i]->as_string ();
187 : : }
188 : 0 : acc += "]";
189 : 0 : return acc;
190 : : }
191 : : };
192 : :
193 : 8898 : class SubstitutionScope
194 : : {
195 : : public:
196 : 4449 : SubstitutionScope () : stack () {}
197 : :
198 : 88019 : void push () { stack.push_back ({}); }
199 : :
200 : 88019 : std::map<std::string, std::unique_ptr<MatchedFragmentContainer>> pop ()
201 : : {
202 : 88019 : auto top = std::move (stack.back ());
203 : 88019 : stack.pop_back ();
204 : 88019 : return top;
205 : : }
206 : :
207 : 4871 : std::map<std::string, std::unique_ptr<MatchedFragmentContainer>> &peek ()
208 : : {
209 : 4871 : return stack.back ();
210 : : }
211 : :
212 : : /**
213 : : * Insert a new matched metavar into the current substitution map
214 : : */
215 : 206249 : void insert_metavar (MatchedFragment fragment)
216 : : {
217 : 206249 : auto ¤t_map = stack.back ();
218 : 206249 : auto it = current_map.find (fragment.fragment_ident);
219 : :
220 : 206249 : if (it == current_map.end ())
221 : 206249 : current_map.emplace (fragment.fragment_ident,
222 : 412498 : MatchedFragmentContainer::metavar (fragment));
223 : : else
224 : 0 : rust_unreachable ();
225 : 206249 : }
226 : :
227 : : /**
228 : : * Append a new matched fragment to a repetition into the current substitution
229 : : * map
230 : : */
231 : : void append_fragment (MatchedFragment fragment)
232 : : {
233 : : auto ¤t_map = stack.back ();
234 : : auto it = current_map.find (fragment.fragment_ident);
235 : :
236 : : if (it == current_map.end ())
237 : : it = current_map
238 : : .emplace (fragment.fragment_ident,
239 : : std::unique_ptr<MatchedFragmentContainer> (
240 : : new MatchedFragmentContainerRepetition ()))
241 : : .first;
242 : :
243 : : it->second->add_fragment (fragment);
244 : : }
245 : :
246 : : /**
247 : : * Append a new matched fragment to a repetition into the current substitution
248 : : * map
249 : : */
250 : 31015 : void append_fragment (std::string ident,
251 : : std::unique_ptr<MatchedFragmentContainer> fragment)
252 : : {
253 : 31015 : auto ¤t_map = stack.back ();
254 : 31015 : auto it = current_map.find (ident);
255 : :
256 : 31015 : if (it == current_map.end ())
257 : 9486 : it = current_map
258 : 4743 : .emplace (ident, std::unique_ptr<MatchedFragmentContainer> (
259 : 4743 : new MatchedFragmentContainerRepetition ()))
260 : : .first;
261 : :
262 : 31015 : it->second->add_fragment (std::move (fragment));
263 : 31015 : }
264 : :
265 : 128 : void insert_matches (std::string key,
266 : : std::unique_ptr<MatchedFragmentContainer> matches)
267 : : {
268 : 128 : auto ¤t_map = stack.back ();
269 : 128 : auto it = current_map.find (key);
270 : 128 : rust_assert (it == current_map.end ());
271 : :
272 : 128 : current_map.emplace (std::move (key), std::move (matches));
273 : 128 : }
274 : :
275 : : private:
276 : : std::vector<std::map<std::string, std::unique_ptr<MatchedFragmentContainer>>>
277 : : stack;
278 : : };
279 : :
280 : : // Object used to store shared data (between functions) for macro expansion.
281 : : struct MacroExpander
282 : : {
283 : : enum class ContextType
284 : : {
285 : : ITEM,
286 : : STMT,
287 : : EXPR,
288 : : EXTERN,
289 : : TYPE,
290 : : TRAIT,
291 : : IMPL,
292 : : TRAIT_IMPL,
293 : : PATTERN,
294 : : };
295 : :
296 : : ExpansionCfg cfg;
297 : : unsigned int expansion_depth = 0;
298 : :
299 : 4449 : MacroExpander (AST::Crate &crate, ExpansionCfg cfg, Session &session)
300 : 4449 : : cfg (cfg), crate (crate), session (session),
301 : 4449 : sub_stack (SubstitutionScope ()),
302 : 4449 : expanded_fragment (AST::Fragment::create_error ()),
303 : 8898 : has_changed_flag (false), resolver (Resolver::Resolver::get ()),
304 : 4449 : mappings (Analysis::Mappings::get ())
305 : 4449 : {}
306 : :
307 : 8898 : ~MacroExpander () = default;
308 : :
309 : : // Expands all macros in the crate passed in.
310 : : void expand_crate ();
311 : :
312 : : /**
313 : : * Expand the eager invocations contained within a builtin macro invocation.
314 : : * Called by `expand_invoc` when expanding builtin invocations.
315 : : */
316 : : void expand_eager_invocations (AST::MacroInvocation &invoc);
317 : :
318 : : /* Expands a macro invocation - possibly make both
319 : : * have similar duck-typed interface and use templates?*/
320 : : // should this be public or private?
321 : : void expand_invoc (AST::MacroInvocation &invoc, AST::InvocKind semicolon);
322 : :
323 : : // Expands a single declarative macro.
324 : : AST::Fragment expand_decl_macro (location_t locus, AST::MacroInvocData &invoc,
325 : : AST::MacroRulesDefinition &rules_def,
326 : : AST::InvocKind semicolon);
327 : :
328 : : bool depth_exceeds_recursion_limit () const;
329 : :
330 : : bool try_match_rule (AST::MacroRule &match_rule,
331 : : AST::DelimTokenTree &invoc_token_tree);
332 : :
333 : : AST::Fragment transcribe_rule (
334 : : AST::MacroRulesDefinition &definition, AST::MacroRule &match_rule,
335 : : AST::DelimTokenTree &invoc_token_tree,
336 : : std::map<std::string, MatchedFragmentContainer *> &matched_fragments,
337 : : AST::InvocKind invoc_kind, ContextType ctx);
338 : :
339 : : bool match_fragment (Parser<MacroInvocLexer> &parser,
340 : : AST::MacroMatchFragment &fragment);
341 : :
342 : : bool match_token (Parser<MacroInvocLexer> &parser, AST::Token &token);
343 : :
344 : : void match_repetition_skipped_metavars (AST::MacroMatch &);
345 : : void match_repetition_skipped_metavars (AST::MacroMatchFragment &);
346 : : void match_repetition_skipped_metavars (AST::MacroMatchRepetition &);
347 : : void match_repetition_skipped_metavars (AST::MacroMatcher &);
348 : :
349 : : bool match_repetition (Parser<MacroInvocLexer> &parser,
350 : : AST::MacroMatchRepetition &rep);
351 : :
352 : : bool match_matcher (Parser<MacroInvocLexer> &parser,
353 : : AST::MacroMatcher &matcher, bool in_repetition = false,
354 : : bool match_delim = true);
355 : :
356 : : /**
357 : : * Match any amount of matches
358 : : *
359 : : * @param parser Parser to use for matching
360 : : * @param rep Repetition to try and match
361 : : * @param match_amount Reference in which to store the ammount of succesful
362 : : * and valid matches
363 : : *
364 : : * @param lo_bound Lower bound of the matcher. When specified, the matcher
365 : : * will only succeed if it parses at *least* `lo_bound` fragments. If
366 : : * unspecified, the matcher could succeed when parsing 0 fragments.
367 : : *
368 : : * @param hi_bound Higher bound of the matcher. When specified, the matcher
369 : : * will only succeed if it parses *less than* `hi_bound` fragments. If
370 : : * unspecified, the matcher could succeed when parsing an infinity of
371 : : * fragments.
372 : : *
373 : : * @return true if matching was successful and within the given limits, false
374 : : * otherwise
375 : : */
376 : : bool match_n_matches (Parser<MacroInvocLexer> &parser,
377 : : AST::MacroMatchRepetition &rep, size_t &match_amount,
378 : : size_t lo_bound = 0, size_t hi_bound = 0);
379 : :
380 : 22923357 : void push_context (ContextType t) { context.push_back (t); }
381 : :
382 : 22923357 : ContextType pop_context ()
383 : : {
384 : 22923357 : rust_assert (!context.empty ());
385 : :
386 : 22923357 : ContextType t = context.back ();
387 : 22923357 : context.pop_back ();
388 : :
389 : 22923357 : return t;
390 : : }
391 : :
392 : 55191 : ContextType peek_context () { return context.back (); }
393 : :
394 : 61694 : void set_expanded_fragment (AST::Fragment &&fragment)
395 : : {
396 : 61694 : if (!fragment.is_error ())
397 : 55708 : has_changed_flag = true;
398 : :
399 : 61694 : expanded_fragment = std::move (fragment);
400 : 61694 : }
401 : :
402 : 23019706 : AST::Fragment take_expanded_fragment ()
403 : : {
404 : 23019706 : auto fragment = std::move (expanded_fragment);
405 : 23019706 : expanded_fragment = AST::Fragment::create_error ();
406 : :
407 : 23019706 : return fragment;
408 : : }
409 : :
410 : : void import_proc_macros (std::string extern_crate);
411 : :
412 : : template <typename T>
413 : 0 : AST::Fragment expand_derive_proc_macro (T &item, AST::SimplePath &path)
414 : : {
415 : : tl::optional<CustomDeriveProcMacro &> macro
416 : 0 : = mappings.lookup_derive_proc_macro_invocation (path);
417 : 0 : if (!macro.has_value ())
418 : : {
419 : 0 : rust_error_at (path.get_locus (), "macro not found");
420 : 0 : return AST::Fragment::create_error ();
421 : : }
422 : :
423 : 0 : AST::TokenCollector collector;
424 : :
425 : 0 : collector.visit (item);
426 : :
427 : 0 : auto c = collector.collect_tokens ();
428 : 0 : std::vector<const_TokenPtr> vec (c.cbegin (), c.cend ());
429 : :
430 : : return parse_proc_macro_output (
431 : 0 : macro.value ().get_handle () (convert (vec)));
432 : 0 : }
433 : :
434 : : template <typename T>
435 : : AST::Fragment expand_bang_proc_macro (T &item,
436 : : AST::MacroInvocation &invocation)
437 : : {
438 : : tl::optional<BangProcMacro &> macro
439 : : = mappings.lookup_bang_proc_macro_invocation (invocation);
440 : : if (!macro.has_value ())
441 : : {
442 : : rust_error_at (invocation.get_locus (), "macro not found");
443 : : return AST::Fragment::create_error ();
444 : : }
445 : :
446 : : AST::TokenCollector collector;
447 : :
448 : : collector.visit (item);
449 : :
450 : : auto c = collector.collect_tokens ();
451 : : std::vector<const_TokenPtr> vec (c.cbegin (), c.cend ());
452 : :
453 : : return parse_proc_macro_output (
454 : : macro.value ().get_handle () (convert (vec)));
455 : : }
456 : :
457 : : template <typename T>
458 : 1 : AST::Fragment expand_attribute_proc_macro (T &item, AST::SimplePath &path)
459 : : {
460 : : tl::optional<AttributeProcMacro &> macro
461 : 1 : = mappings.lookup_attribute_proc_macro_invocation (path);
462 : 1 : if (!macro.has_value ())
463 : : {
464 : 1 : rust_error_at (path.get_locus (), "macro not found");
465 : 1 : return AST::Fragment::create_error ();
466 : : }
467 : :
468 : 0 : AST::TokenCollector collector;
469 : :
470 : 0 : collector.visit (item);
471 : :
472 : 0 : auto c = collector.collect_tokens ();
473 : 0 : std::vector<const_TokenPtr> vec (c.cbegin (), c.cend ());
474 : :
475 : : // FIXME: Handle attributes
476 : : return parse_proc_macro_output (
477 : 0 : macro.value ().get_handle () (ProcMacro::TokenStream::make_tokenstream (),
478 : 0 : convert (vec)));
479 : 0 : }
480 : :
481 : : /**
482 : : * Has the MacroExpander expanded a macro since its state was last reset?
483 : : */
484 : 10288 : bool has_changed () const { return has_changed_flag; }
485 : :
486 : : /**
487 : : * Reset the expander's "changed" state. This function should be executed at
488 : : * each iteration in a fixed point loop
489 : : */
490 : 10288 : void reset_changed_state () { has_changed_flag = false; }
491 : :
492 : 1 : tl::optional<AST::MacroRulesDefinition &> &get_last_definition ()
493 : : {
494 : 1 : return last_def;
495 : : }
496 : :
497 : 1 : tl::optional<AST::MacroInvocation &> &get_last_invocation ()
498 : : {
499 : 1 : return last_invoc;
500 : : }
501 : :
502 : : private:
503 : : AST::Fragment parse_proc_macro_output (ProcMacro::TokenStream ts);
504 : :
505 : : AST::Crate &crate;
506 : : Session &session;
507 : : SubstitutionScope sub_stack;
508 : : std::vector<ContextType> context;
509 : : AST::Fragment expanded_fragment;
510 : : bool has_changed_flag;
511 : :
512 : : tl::optional<AST::MacroRulesDefinition &> last_def;
513 : : tl::optional<AST::MacroInvocation &> last_invoc;
514 : :
515 : : public:
516 : : Resolver::Resolver *resolver;
517 : : Analysis::Mappings &mappings;
518 : : };
519 : :
520 : : } // namespace Rust
521 : :
522 : : #endif
|