Debian Codegraph @

gcc/rust/ast/rust-ast.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 #ifndef RUST_AST_BASE_H
20 #define RUST_AST_BASE_H
21 // Base for AST used in gccrs, basically required by all specific ast things
22
23 #include "rust-system.h"
24 #include "rust-hir-map.h"
25 #include "rust-token.h"
26 #include "rust-location.h"
27 #include "rust-diagnostics.h"
28 #include "rust-keyword-values.h"
29
30 namespace Rust {
31 // TODO: remove typedefs and make actual types for these
32 typedef int TupleIndex;
33 struct Session;
34 struct MacroExpander;
35
36 class Identifier
37 {
38 public:
39 // Create dummy identifier
40 Identifier () : ident (""), loc (UNDEF_LOCATION) {}
41 // Create identifier with dummy location
42 Identifier (std::string ident, location_t loc = UNDEF_LOCATION)
43 : ident (ident), loc (loc)
44 {}
45 // Create identifier from token
46 Identifier (const_TokenPtr token)
47 : ident (token->get_str ()), loc (token->get_locus ())
48 {}
49
50 Identifier (const Identifier &) = default;
51 Identifier (Identifier &&) = default;
52 Identifier &operator= (const Identifier &) = default;
53 Identifier &operator= (Identifier &&) = default;
54
55 location_t get_locus () const { return loc; }
56 const std::string &as_string () const { return ident; }
57
58 bool empty () const { return ident.empty (); }
59
60 private:
61 std::string ident;
62 location_t loc;
63 };
64
65 std::ostream &
66 operator<< (std::ostream &os, Identifier const &i);
67
68 namespace AST {
69 // foward decl: ast visitor
70 class ASTVisitor;
71 using AttrVec = std::vector<Attribute>;
72
73 class Visitable
74 {
75 public:
76 virtual ~Visitable () = default;
77 virtual void accept_vis (ASTVisitor &vis) = 0;
78 };
79
80 // Delimiter types - used in macros and whatever.
81 enum DelimType
82 {
83 PARENS,
84 SQUARE,
85 CURLY
86 };
87
88 // forward decl for use in token tree method
89 class Token;
90
91 // A tree of tokens (or a single token) - abstract base class
92 class TokenTree : public Visitable
93 {
94 public:
95 virtual ~TokenTree () {}
96
97 // Unique pointer custom clone function
98 std::unique_ptr<TokenTree> clone_token_tree () const
99 {
100 return std::unique_ptr<TokenTree> (clone_token_tree_impl ());
101 }
102
103 virtual std::string as_string () const = 0;
104
105 /* Converts token tree to a flat token stream. Tokens must be pointer to
106 * avoid mutual dependency with Token. */
107 virtual std::vector<std::unique_ptr<Token>> to_token_stream () const = 0;
108
109 protected:
110 // pure virtual clone implementation
111 virtual TokenTree *clone_token_tree_impl () const = 0;
112 };
113
114 // Abstract base class for a macro match
115 class MacroMatch : public Visitable
116 {
117 public:
118 enum MacroMatchType
119 {
120 Fragment,
121 Repetition,
122 Matcher,
123 Tok
124 };
125
126 virtual ~MacroMatch () {}
127
128 virtual std::string as_string () const = 0;
129 virtual location_t get_match_locus () const = 0;
130
131 // Unique pointer custom clone function
132 std::unique_ptr<MacroMatch> clone_macro_match () const
133 {
134 return std::unique_ptr<MacroMatch> (clone_macro_match_impl ());
135 }
136
137 virtual MacroMatchType get_macro_match_type () const = 0;
138
139 protected:
140 // pure virtual clone implementation
141 virtual MacroMatch *clone_macro_match_impl () const = 0;
142 };
143
144 // A token is a kind of token tree (except delimiter tokens)
145 class Token : public TokenTree, public MacroMatch
146 {
147 // A token is a kind of token tree (except delimiter tokens)
148 // A token is a kind of MacroMatch (except $ and delimiter tokens)
149 #if 0
150 // TODO: improve member variables - current ones are the same as lexer token
151 // Token kind.
152 TokenId token_id;
153 // Token location.
154 location_t locus;
155 // Associated text (if any) of token.
156 std::string str;
157 // Token type hint (if any).
158 PrimitiveCoreType type_hint;
159 #endif
160
161 const_TokenPtr tok_ref;
162
163 /* new idea: wrapper around const_TokenPtr used for heterogeneuous storage
164 * in token trees. rather than convert back and forth when parsing macros,
165 * just wrap it. */
166
167 public:
168 // Unique pointer custom clone function
169 std::unique_ptr<Token> clone_token () const
170 {
171 return std::unique_ptr<Token> (clone_token_impl ());
172 }
173
174 #if 0
175 /* constructor from general text - avoid using if lexer const_TokenPtr is
176 * available */
177 Token (TokenId token_id, location_t locus, std::string str,
178 PrimitiveCoreType type_hint)
179 : token_id (token_id), locus (locus), str (std::move (str)),
180 type_hint (type_hint)
181 {}
182 #endif
183 // not doable with new implementation - will have to make a const_TokenPtr
184
185 // Constructor from lexer const_TokenPtr
186 #if 0
187 /* TODO: find workaround for std::string being nullptr - probably have to
188 * introduce new method in lexer Token, or maybe make conversion method
189 * there */
190 Token (const_TokenPtr lexer_token_ptr)
191 : token_id (lexer_token_ptr->get_id ()),
192 locus (lexer_token_ptr->get_locus ()), str (""),
193 type_hint (lexer_token_ptr->get_type_hint ())
194 {
195 // FIXME: change to "should have str" later?
196 if (lexer_token_ptr->has_str ())
197 {
198 str = lexer_token_ptr->get_str ();
199
200 // DEBUG
201 rust_debug ("ast token created with str '%s'", str.c_str ());
202 }
203 else
204 {
205 // FIXME: is this returning correct thing?
206 str = lexer_token_ptr->get_token_description ();
207
208 // DEBUG
209 rust_debug ("ast token created with string '%s'", str.c_str ());
210 }
211
212 // DEBUG
213 if (lexer_token_ptr->should_have_str () && !lexer_token_ptr->has_str ())
214 {
215 rust_debug (
216 "BAD: for token '%s', should have string but does not!",
217 lexer_token_ptr->get_token_description ());
218 }
219 }
220 #endif
221 Token (const_TokenPtr lexer_tok_ptr) : tok_ref (std::move (lexer_tok_ptr)) {}
222
223 bool is_string_lit () const
224 {
225 switch (get_id ())
226 {
227 case STRING_LITERAL:
228 case BYTE_STRING_LITERAL:
229 case RAW_STRING_LITERAL:
230 return true;
231 default:
232 return false;
233 }
234 }
235
236 std::string as_string () const override;
237 location_t get_match_locus () const override
238 {
239 return tok_ref->get_locus ();
240 };
241
242 void accept_vis (ASTVisitor &vis) override;
243
244 // Return copy of itself but in token stream form.
245 std::vector<std::unique_ptr<Token>> to_token_stream () const override;
246
247 TokenId get_id () const { return tok_ref->get_id (); }
248 const std::string &get_str () const { return tok_ref->get_str (); }
249
250 location_t get_locus () const { return tok_ref->get_locus (); }
251
252 PrimitiveCoreType get_type_hint () const { return tok_ref->get_type_hint (); }
253
254 // Get a new token pointer copy.
255 const_TokenPtr get_tok_ptr () const { return tok_ref; }
256
257 MacroMatchType get_macro_match_type () const override
258 {
259 return MacroMatchType::Tok;
260 }
261
262 protected:
263 // No virtual for now as not polymorphic but can be in future
264 /*virtual*/ Token *clone_token_impl () const { return new Token (*this); }
265
266 /* Use covariance to implement clone function as returning this object
267 * rather than base */
268 Token *clone_token_tree_impl () const final override
269 {
270 return clone_token_impl ();
271 }
272
273 /* Use covariance to implement clone function as returning this object
274 * rather than base */
275 Token *clone_macro_match_impl () const final override
276 {
277 return clone_token_impl ();
278 }
279 };
280
281 // A literal - value with a type. Used in LiteralExpr and LiteralPattern.
282 struct Literal
283 {
284 public:
285 enum LitType
286 {
287 CHAR,
288 STRING,
289 BYTE,
290 BYTE_STRING,
291 RAW_STRING,
292 INT,
293 FLOAT,
294 BOOL,
295 ERROR
296 };
297
298 private:
299 /* TODO: maybe make subclasses of each type of literal with their typed
300 * values (or generics) */
301 std::string value_as_string;
302 LitType type;
303 PrimitiveCoreType type_hint;
304
305 public:
306 std::string as_string () const { return value_as_string; }
307
308 LitType get_lit_type () const { return type; }
309
310 PrimitiveCoreType get_type_hint () const { return type_hint; }
311
312 Literal (std::string value_as_string, LitType type,
313 PrimitiveCoreType type_hint)
314 : value_as_string (std::move (value_as_string)), type (type),
315 type_hint (type_hint)
316 {}
317
318 static Literal create_error ()
319 {
320 return Literal ("", ERROR, PrimitiveCoreType::CORETYPE_UNKNOWN);
321 }
322
323 // Returns whether literal is in an invalid state.
324 bool is_error () const { return type == ERROR; }
325 };
326
327 /* Forward decl - definition moved to rust-expr.h as it requires LiteralExpr
328 * to be defined */
329 class AttrInputLiteral;
330
331 /* TODO: move applicable stuff into here or just don't include it because
332 * nothing uses it A segment of a path (maybe) */
333 class PathSegment
334 {
335 public:
336 virtual ~PathSegment () {}
337
338 virtual std::string as_string () const = 0;
339
340 // TODO: add visitor here?
341 };
342
343 // A segment of a simple path without generic or type arguments
344 class SimplePathSegment : public PathSegment
345 {
346 std::string segment_name;
347 location_t locus;
348 NodeId node_id;
349
350 // only allow identifiers, "super", "self", "crate", or "$crate"
351 public:
352 // TODO: put checks in constructor to enforce this rule?
353 SimplePathSegment (std::string segment_name, location_t locus)
354 : segment_name (std::move (segment_name)), locus (locus),
355 node_id (Analysis::Mappings::get ().get_next_node_id ())
356 {}
357
358 /* Returns whether simple path segment is in an invalid state (currently, if
359 * empty). */
360 bool is_error () const { return segment_name.empty (); }
361
362 // Creates an error SimplePathSegment
363 static SimplePathSegment create_error ()
364 {
365 return SimplePathSegment (std::string (""), UNDEF_LOCATION);
366 }
367
368 std::string as_string () const override;
369
370 location_t get_locus () const { return locus; }
371 NodeId get_node_id () const { return node_id; }
372 const std::string &get_segment_name () const { return segment_name; }
373 bool is_super_path_seg () const
374 {
375 return as_string ().compare (Values::Keywords::SUPER) == 0;
376 }
377 bool is_crate_path_seg () const
378 {
379 return as_string ().compare (Values::Keywords::CRATE) == 0;
380 }
381 bool is_lower_self_seg () const
382 {
383 return as_string ().compare (Values::Keywords::SELF) == 0;
384 }
385 bool is_big_self () const
386 {
387 return as_string ().compare (Values::Keywords::SELF_ALIAS) == 0;
388 }
389 };
390
391 // A simple path without generic or type arguments
392 class SimplePath
393 {
394 bool opening_scope_resolution;
395 std::vector<SimplePathSegment> segments;
396 location_t locus;
397 NodeId node_id;
398
399 public:
400 // Constructor
401 SimplePath (std::vector<SimplePathSegment> path_segments,
402 bool has_opening_scope_resolution = false,
403 location_t locus = UNDEF_LOCATION)
404 : opening_scope_resolution (has_opening_scope_resolution),
405 segments (std::move (path_segments)), locus (locus),
406 node_id (Analysis::Mappings::get ().get_next_node_id ())
407 {}
408
409 SimplePath (Identifier ident)
410 : opening_scope_resolution (false),
411 segments ({SimplePathSegment (ident.as_string (), ident.get_locus ())}),
412 locus (ident.get_locus ()),
413 node_id (Analysis::Mappings::get ().get_next_node_id ())
414 {}
415
416 // Creates an empty SimplePath.
417 static SimplePath create_empty ()
418 {
419 return SimplePath (std::vector<SimplePathSegment> ());
420 }
421
422 // Returns whether the SimplePath is empty, i.e. has path segments.
423 bool is_empty () const { return segments.empty (); }
424
425 const std::string as_string () const;
426
427 bool has_opening_scope_resolution () const
428 {
429 return opening_scope_resolution;
430 }
431
432 location_t get_locus () const { return locus; }
433 NodeId get_node_id () const { return node_id; }
434
435 // does this need visitor if not polymorphic? probably not
436
437 // path-to-string comparison operator
438 bool operator== (const std::string &rhs) const
439 {
440 return !opening_scope_resolution && segments.size () == 1
441 && segments[0].as_string () == rhs;
442 }
443
444 /* Creates a single-segment SimplePath from a string. This will not check to
445 * ensure that this is a valid identifier in path, so be careful. Also, this
446 * will have no location data.
447 * TODO have checks? */
448 static SimplePath from_str (std::string str, location_t locus)
449 {
450 std::vector<AST::SimplePathSegment> single_segments
451 = {AST::SimplePathSegment (std::move (str), locus)};
452 return SimplePath (std::move (single_segments), false, locus);
453 }
454
455 const std::vector<SimplePathSegment> &get_segments () const
456 {
457 return segments;
458 }
459
460 std::vector<SimplePathSegment> &get_segments () { return segments; }
461
462 const SimplePathSegment &get_final_segment () const
463 {
464 return segments.back ();
465 }
466 };
467
468 // path-to-string inverse comparison operator
469 inline bool
470 operator!= (const SimplePath &lhs, const std::string &rhs)
471 {
472 return !(lhs == rhs);
473 }
474
475 // forward decl for Attribute
476 class AttrInput;
477
478 // Visibility of item - if the item has it, then it is some form of public
479 struct Visibility
480 {
481 public:
482 enum VisType
483 {
484 PRIV,
485 PUB,
486 PUB_CRATE,
487 PUB_SELF,
488 PUB_SUPER,
489 PUB_IN_PATH
490 };
491
492 private:
493 VisType vis_type;
494 // Only assigned if vis_type is IN_PATH
495 SimplePath in_path;
496 location_t locus;
497
498 // should this store location info?
499
500 public:
501 // Creates a Visibility - TODO make constructor protected or private?
502 Visibility (VisType vis_type, SimplePath in_path, location_t locus)
503 : vis_type (vis_type), in_path (std::move (in_path)), locus (locus)
504 {}
505
506 VisType get_vis_type () const { return vis_type; }
507
508 // Returns whether visibility is in an error state.
509 bool is_error () const
510 {
511 return vis_type == PUB_IN_PATH && in_path.is_empty ();
512 }
513
514 // Returns whether a visibility has a path
515 bool has_path () const { return !is_error () && vis_type >= PUB_CRATE; }
516
517 // Returns whether visibility is public or not.
518 bool is_public () const { return vis_type != PRIV && !is_error (); }
519
520 location_t get_locus () const { return locus; }
521
522 // empty?
523 // Creates an error visibility.
524 static Visibility create_error ()
525 {
526 return Visibility (PUB_IN_PATH, SimplePath::create_empty (),
527 UNDEF_LOCATION);
528 }
529
530 // Unique pointer custom clone function
531 /*std::unique_ptr<Visibility> clone_visibility() const {
532 return std::unique_ptr<Visibility>(clone_visibility_impl());
533 }*/
534
535 /* TODO: think of a way to only allow valid Visibility states - polymorphism
536 * is one idea but may be too resource-intensive. */
537
538 // Creates a public visibility with no further features/arguments.
539 // empty?
540 static Visibility create_public (location_t pub_vis_location)
541 {
542 return Visibility (PUB, SimplePath::create_empty (), pub_vis_location);
543 }
544
545 // Creates a public visibility with crate-relative paths
546 static Visibility create_crate (location_t crate_tok_location,
547 location_t crate_vis_location)
548 {
549 return Visibility (PUB_CRATE,
550 SimplePath::from_str (Values::Keywords::CRATE,
551 crate_tok_location),
552 crate_vis_location);
553 }
554
555 // Creates a public visibility with self-relative paths
556 static Visibility create_self (location_t self_tok_location,
557 location_t self_vis_location)
558 {
559 return Visibility (PUB_SELF,
560 SimplePath::from_str (Values::Keywords::SELF,
561 self_tok_location),
562 self_vis_location);
563 }
564
565 // Creates a public visibility with parent module-relative paths
566 static Visibility create_super (location_t super_tok_location,
567 location_t super_vis_location)
568 {
569 return Visibility (PUB_SUPER,
570 SimplePath::from_str (Values::Keywords::SUPER,
571 super_tok_location),
572 super_vis_location);
573 }
574
575 // Creates a private visibility
576 static Visibility create_private ()
577 {
578 return Visibility (PRIV, SimplePath::create_empty (), UNDEF_LOCATION);
579 }
580
581 // Creates a public visibility with a given path or whatever.
582 static Visibility create_in_path (SimplePath in_path,
583 location_t in_path_vis_location)
584 {
585 return Visibility (PUB_IN_PATH, std::move (in_path), in_path_vis_location);
586 }
587
588 std::string as_string () const;
589 const SimplePath &get_path () const { return in_path; }
590 SimplePath &get_path () { return in_path; }
591
592 protected:
593 // Clone function implementation - not currently virtual but may be if
594 // polymorphism used
595 /*virtual*/ Visibility *clone_visibility_impl () const
596 {
597 return new Visibility (*this);
598 }
599 };
600
601 // aka Attr
602 // Attribute AST representation
603 struct Attribute
604 {
605 private:
606 SimplePath path;
607
608 // bool has_attr_input;
609 std::unique_ptr<AttrInput> attr_input;
610
611 location_t locus;
612
613 bool inner_attribute;
614
615 // TODO: maybe a variable storing whether attr input is parsed or not
616
617 public:
618 // Returns whether Attribute has AttrInput
619 bool has_attr_input () const { return attr_input != nullptr; }
620
621 // Constructor has pointer AttrInput for polymorphism reasons
622 Attribute (SimplePath path, std::unique_ptr<AttrInput> input,
623 location_t locus = UNDEF_LOCATION, bool inner_attribute = false)
624 : path (std::move (path)), attr_input (std::move (input)), locus (locus),
625 inner_attribute (inner_attribute)
626 {}
627
628 bool is_derive () const;
629
630 std::vector<std::reference_wrapper<AST::SimplePath>> get_traits_to_derive ();
631
632 // default destructor
633 ~Attribute () = default;
634
635 // no point in being defined inline as requires virtual call anyway
636 Attribute (const Attribute &other);
637
638 // no point in being defined inline as requires virtual call anyway
639 Attribute &operator= (const Attribute &other);
640
641 // default move semantics
642 Attribute (Attribute &&other) = default;
643 Attribute &operator= (Attribute &&other) = default;
644
645 // Unique pointer custom clone function
646 std::unique_ptr<Attribute> clone_attribute () const
647 {
648 return std::unique_ptr<Attribute> (clone_attribute_impl ());
649 }
650
651 // Creates an empty attribute (which is invalid)
652 static Attribute create_empty ()
653 {
654 return Attribute (SimplePath::create_empty (), nullptr);
655 }
656
657 // Returns whether the attribute is considered an "empty" attribute.
658 bool is_empty () const { return attr_input == nullptr && path.is_empty (); }
659
660 // Returns whether the attribute has no input
661 bool empty_input () const { return !attr_input; }
662
663 location_t get_locus () const { return locus; }
664
665 AttrInput &get_attr_input () const { return *attr_input; }
666
667 /* e.g.:
668 #![crate_type = "lib"]
669 #[test]
670 #[cfg(target_os = "linux")]
671 #[allow(non_camel_case_types)]
672 #![allow(unused_variables)]
673 */
674
675 // Full built-in attribute list:
676 /* cfg
677 * cfg_attr
678 * test
679 * ignore
680 * should_panic
681 * derive
682 * macro_export
683 * macro_use
684 * proc_macro
685 * proc_macro_derive
686 * proc_macro_attribute
687 * allow
688 * warn
689 * deny
690 * forbid
691 * deprecated
692 * must_use
693 * link
694 * link_name
695 * no_link
696 * repr
697 * crate_type
698 * no_main
699 * export_name
700 * link_section
701 * no_mangle
702 * used
703 * crate_name
704 * inline
705 * cold
706 * no_builtins
707 * target_feature
708 * doc
709 * no_std
710 * no_implicit_prelude
711 * path
712 * recursion_limit
713 * type_length_limit
714 * panic_handler
715 * global_allocator
716 * windows_subsystem
717 * feature */
718
719 std::string as_string () const;
720
721 bool is_inner_attribute () const { return inner_attribute; }
722
723 // no visitor pattern as not currently polymorphic
724
725 const SimplePath &get_path () const { return path; }
726 SimplePath &get_path () { return path; }
727
728 // Call to parse attribute body to meta item syntax.
729 void parse_attr_to_meta_item ();
730
731 /* Determines whether cfg predicate is true and item with attribute should
732 * not be stripped. Attribute body must already be parsed to meta item. */
733 bool check_cfg_predicate (const Session &session) const;
734
735 // Returns whether body has been parsed to meta item form or not.
736 bool is_parsed_to_meta_item () const;
737
738 /* Returns any attributes generated from cfg_attr attributes. Attribute body
739 * must already be parsed to meta item. */
740 std::vector<Attribute> separate_cfg_attrs () const;
741
742 protected:
743 // not virtual as currently no subclasses of Attribute, but could be in
744 // future
745 /*virtual*/ Attribute *clone_attribute_impl () const
746 {
747 return new Attribute (*this);
748 }
749 };
750
751 // Attribute body - abstract base class
752 class AttrInput : public Visitable
753 {
754 public:
755 enum AttrInputType
756 {
757 LITERAL,
758 MACRO,
759 META_ITEM,
760 TOKEN_TREE,
761 };
762
763 virtual ~AttrInput () {}
764
765 // Unique pointer custom clone function
766 std::unique_ptr<AttrInput> clone_attr_input () const
767 {
768 return std::unique_ptr<AttrInput> (clone_attr_input_impl ());
769 }
770
771 virtual std::string as_string () const = 0;
772
773 virtual bool check_cfg_predicate (const Session &session) const = 0;
774
775 // Parse attribute input to meta item, if possible
776 virtual AttrInput *parse_to_meta_item () const { return nullptr; }
777
778 virtual std::vector<Attribute> separate_cfg_attrs () const { return {}; }
779
780 // Returns whether attr input has been parsed to meta item syntax.
781 virtual bool is_meta_item () const = 0;
782
783 virtual AttrInputType get_attr_input_type () const = 0;
784
785 protected:
786 // pure virtual clone implementation
787 virtual AttrInput *clone_attr_input_impl () const = 0;
788 };
789
790 // Forward decl - defined in rust-macro.h
791 class MetaNameValueStr;
792
793 // abstract base meta item inner class
794 class MetaItemInner : public Visitable
795 {
796 protected:
797 // pure virtual as MetaItemInner
798 virtual MetaItemInner *clone_meta_item_inner_impl () const = 0;
799
800 public:
801 enum class Kind
802 {
803 LitExpr,
804 MetaItem,
805 };
806
807 // Unique pointer custom clone function
808 std::unique_ptr<MetaItemInner> clone_meta_item_inner () const
809 {
810 return std::unique_ptr<MetaItemInner> (clone_meta_item_inner_impl ());
811 }
812
813 virtual Kind get_kind () = 0;
814
815 virtual ~MetaItemInner ();
816
817 virtual location_t get_locus () const = 0;
818
819 virtual std::string as_string () const = 0;
820
821 /* HACK: used to simplify parsing - creates a copy of that type, or returns
822 * null */
823 virtual std::unique_ptr<MetaNameValueStr> to_meta_name_value_str () const;
824
825 // HACK: used to simplify parsing - same thing
826 virtual SimplePath to_path_item () const
827 {
828 return SimplePath::create_empty ();
829 }
830
831 virtual Attribute to_attribute () const { return Attribute::create_empty (); }
832
833 virtual bool check_cfg_predicate (const Session &session) const = 0;
834
835 virtual bool is_key_value_pair () const { return false; }
836 };
837
838 // Container used to store MetaItems as AttrInput (bridge-ish kinda thing)
839 class AttrInputMetaItemContainer : public AttrInput
840 {
841 std::vector<std::unique_ptr<MetaItemInner>> items;
842
843 public:
844 AttrInputMetaItemContainer (std::vector<std::unique_ptr<MetaItemInner>> items)
845 : items (std::move (items))
846 {}
847
848 // copy constructor with vector clone
849 AttrInputMetaItemContainer (const AttrInputMetaItemContainer &other)
850 {
851 items.reserve (other.items.size ());
852 for (const auto &e : other.items)
853 items.push_back (e->clone_meta_item_inner ());
854 }
855
856 // copy assignment operator with vector clone
857 AttrInputMetaItemContainer &
858 operator= (const AttrInputMetaItemContainer &other)
859 {
860 AttrInput::operator= (other);
861
862 items.reserve (other.items.size ());
863 for (const auto &e : other.items)
864 items.push_back (e->clone_meta_item_inner ());
865
866 return *this;
867 }
868
869 // default move constructors
870 AttrInputMetaItemContainer (AttrInputMetaItemContainer &&other) = default;
871 AttrInputMetaItemContainer &operator= (AttrInputMetaItemContainer &&other)
872 = default;
873
874 std::string as_string () const override;
875
876 void accept_vis (ASTVisitor &vis) override;
877
878 bool check_cfg_predicate (const Session &session) const override;
879
880 AttrInputType get_attr_input_type () const final override
881 {
882 return AttrInput::AttrInputType::META_ITEM;
883 }
884
885 // Clones this object.
886 std::unique_ptr<AttrInputMetaItemContainer>
887 clone_attr_input_meta_item_container () const
888 {
889 return std::unique_ptr<AttrInputMetaItemContainer> (
890 clone_attr_input_meta_item_container_impl ());
891 }
892
893 std::vector<Attribute> separate_cfg_attrs () const override;
894
895 bool is_meta_item () const override { return true; }
896
897 // TODO: this mutable getter seems dodgy
898 std::vector<std::unique_ptr<MetaItemInner>> &get_items () { return items; }
899 const std::vector<std::unique_ptr<MetaItemInner>> &get_items () const
900 {
901 return items;
902 }
903
904 protected:
905 // Use covariance to implement clone function as returning this type
906 AttrInputMetaItemContainer *clone_attr_input_impl () const final override
907 {
908 return clone_attr_input_meta_item_container_impl ();
909 }
910
911 AttrInputMetaItemContainer *clone_attr_input_meta_item_container_impl () const
912 {
913 return new AttrInputMetaItemContainer (*this);
914 }
915 };
916
917 // A token tree with delimiters
918 class DelimTokenTree : public TokenTree, public AttrInput
919 {
920 DelimType delim_type;
921 std::vector<std::unique_ptr<TokenTree>> token_trees;
922 location_t locus;
923
924 protected:
925 DelimTokenTree *clone_delim_tok_tree_impl () const
926 {
927 return new DelimTokenTree (*this);
928 }
929
930 /* Use covariance to implement clone function as returning a DelimTokenTree
931 * object */
932 DelimTokenTree *clone_attr_input_impl () const final override
933 {
934 return clone_delim_tok_tree_impl ();
935 }
936
937 /* Use covariance to implement clone function as returning a DelimTokenTree
938 * object */
939 DelimTokenTree *clone_token_tree_impl () const final override
940 {
941 return clone_delim_tok_tree_impl ();
942 }
943
944 public:
945 DelimTokenTree (DelimType delim_type,
946 std::vector<std::unique_ptr<TokenTree>> token_trees
947 = std::vector<std::unique_ptr<TokenTree>> (),
948 location_t locus = UNDEF_LOCATION)
949 : delim_type (delim_type), token_trees (std::move (token_trees)),
950 locus (locus)
951 {}
952
953 // Copy constructor with vector clone
954 DelimTokenTree (DelimTokenTree const &other)
955 : delim_type (other.delim_type), locus (other.locus)
956 {
957 token_trees.clear ();
958 token_trees.reserve (other.token_trees.size ());
959 for (const auto &e : other.token_trees)
960 token_trees.push_back (e->clone_token_tree ());
961 }
962
963 // overloaded assignment operator with vector clone
964 DelimTokenTree &operator= (DelimTokenTree const &other)
965 {
966 delim_type = other.delim_type;
967 locus = other.locus;
968
969 token_trees.clear ();
970 token_trees.reserve (other.token_trees.size ());
971 for (const auto &e : other.token_trees)
972 token_trees.push_back (e->clone_token_tree ());
973
974 return *this;
975 }
976
977 // move constructors
978 DelimTokenTree (DelimTokenTree &&other) = default;
979 DelimTokenTree &operator= (DelimTokenTree &&other) = default;
980
981 static DelimTokenTree create_empty () { return DelimTokenTree (PARENS); }
982
983 std::string as_string () const override;
984
985 void accept_vis (ASTVisitor &vis) override;
986
987 bool check_cfg_predicate (const Session &) const override
988 {
989 // this should never be called - should be converted first
990 rust_assert (false);
991 return false;
992 }
993
994 AttrInputMetaItemContainer *parse_to_meta_item () const override;
995
996 std::vector<std::unique_ptr<Token>> to_token_stream () const override;
997
998 std::unique_ptr<DelimTokenTree> clone_delim_token_tree () const
999 {
1000 return std::unique_ptr<DelimTokenTree> (clone_delim_tok_tree_impl ());
1001 }
1002
1003 bool is_meta_item () const override { return false; }
1004
1005 AttrInputType get_attr_input_type () const final override
1006 {
1007 return AttrInput::AttrInputType::TOKEN_TREE;
1008 }
1009
1010 std::vector<std::unique_ptr<TokenTree>> &get_token_trees ()
1011 {
1012 return token_trees;
1013 }
1014
1015 const std::vector<std::unique_ptr<TokenTree>> &get_token_trees () const
1016 {
1017 return token_trees;
1018 }
1019
1020 DelimType get_delim_type () const { return delim_type; }
1021 location_t get_locus () const { return locus; }
1022 };
1023
1024 /* Forward decl - definition moved to rust-expr.h as it requires LiteralExpr
1025 * to be defined */
1026 class AttrInputLiteral;
1027
1028 // abstract base meta item class
1029 class MetaItem : public MetaItemInner
1030 {
1031 public:
1032 enum class ItemKind
1033 {
1034 Path,
1035 Word,
1036 NameValueStr,
1037 PathLit,
1038 Seq,
1039 ListPaths,
1040 ListNameValueStr,
1041 };
1042
1043 MetaItemInner::Kind get_kind () override
1044 {
1045 return MetaItemInner::Kind::MetaItem;
1046 }
1047
1048 virtual ItemKind get_item_kind () const = 0;
1049 };
1050
1051 // Forward decl - defined in rust-expr.h
1052 class MetaItemLitExpr;
1053
1054 // Forward decl - defined in rust-expr.h
1055 class MetaItemPathLit;
1056
1057 // Forward decl - defined in rust-macro.h
1058 class MetaItemPath;
1059
1060 // Forward decl - defined in rust-macro.h
1061 class MetaItemSeq;
1062
1063 // Forward decl - defined in rust-macro.h
1064 class MetaWord;
1065
1066 // Forward decl - defined in rust-macro.h
1067 class MetaListPaths;
1068
1069 // Forward decl - defined in rust-macro.h
1070 class MetaListNameValueStr;
1071
1072 /* Base statement abstract class. Note that most "statements" are not allowed
1073 * in top-level module scope - only a subclass of statements called "items"
1074 * are. */
1075 class Stmt : public Visitable
1076 {
1077 public:
1078 enum class Kind
1079 {
1080 Empty,
1081 Item,
1082 Let,
1083 Expr,
1084 MacroInvocation,
1085 };
1086
1087 // Unique pointer custom clone function
1088 std::unique_ptr<Stmt> clone_stmt () const
1089 {
1090 return std::unique_ptr<Stmt> (clone_stmt_impl ());
1091 }
1092
1093 virtual ~Stmt () {}
1094
1095 virtual std::string as_string () const = 0;
1096
1097 virtual location_t get_locus () const = 0;
1098
1099 virtual void mark_for_strip () = 0;
1100 virtual bool is_marked_for_strip () const = 0;
1101 NodeId get_node_id () const { return node_id; }
1102
1103 virtual Kind get_stmt_kind () = 0;
1104
1105 // TODO: Can we remove these two?
1106 virtual bool is_item () const = 0;
1107 virtual bool is_expr () const { return false; }
1108
1109 virtual void add_semicolon () {}
1110
1111 protected:
1112 Stmt () : node_id (Analysis::Mappings::get ().get_next_node_id ()) {}
1113
1114 // Clone function implementation as pure virtual method
1115 virtual Stmt *clone_stmt_impl () const = 0;
1116
1117 NodeId node_id;
1118 };
1119
1120 // Rust "item" AST node (declaration of top-level/module-level allowed stuff)
1121 class Item : public Stmt
1122 {
1123 public:
1124 enum class Kind
1125 {
1126 MacroRulesDefinition,
1127 MacroInvocation,
1128 Module,
1129 ExternCrate,
1130 UseDeclaration,
1131 Function,
1132 TypeAlias,
1133 Struct,
1134 EnumItem,
1135 Enum,
1136 Union,
1137 ConstantItem,
1138 StaticItem,
1139 Trait,
1140 Impl,
1141 ExternBlock,
1142 };
1143
1144 virtual Kind get_item_kind () const = 0;
1145
1146 // Unique pointer custom clone function
1147 std::unique_ptr<Item> clone_item () const
1148 {
1149 return std::unique_ptr<Item> (clone_item_impl ());
1150 }
1151
1152 /* Adds crate names to the vector passed by reference, if it can
1153 * (polymorphism). TODO: remove, unused. */
1154 virtual void
1155 add_crate_name (std::vector<std::string> &names ATTRIBUTE_UNUSED) const
1156 {}
1157
1158 Stmt::Kind get_stmt_kind () final { return Stmt::Kind::Item; }
1159
1160 // FIXME: ARTHUR: Is it okay to have removed that final? Is it *required*
1161 // behavior that we have items that can also be expressions?
1162 bool is_item () const override { return true; }
1163
1164 virtual std::vector<Attribute> &get_outer_attrs () = 0;
1165 virtual const std::vector<Attribute> &get_outer_attrs () const = 0;
1166
1167 virtual bool has_outer_attrs () const { return !get_outer_attrs ().empty (); }
1168
1169 protected:
1170 // Clone function implementation as pure virtual method
1171 virtual Item *clone_item_impl () const = 0;
1172
1173 /* Save having to specify two clone methods in derived classes by making
1174 * statement clone return item clone. Hopefully won't affect performance too
1175 * much. */
1176 Item *clone_stmt_impl () const final override { return clone_item_impl (); }
1177 };
1178
1179 // Item that supports visibility - abstract base class
1180 class VisItem : public Item
1181 {
1182 Visibility visibility;
1183 std::vector<Attribute> outer_attrs;
1184
1185 protected:
1186 // Visibility constructor
1187 VisItem (Visibility visibility,
1188 std::vector<Attribute> outer_attrs = std::vector<Attribute> ())
1189 : visibility (std::move (visibility)), outer_attrs (std::move (outer_attrs))
1190 {}
1191
1192 // Visibility copy constructor
1193 VisItem (VisItem const &other)
1194 : visibility (other.visibility), outer_attrs (other.outer_attrs)
1195 {}
1196
1197 // Overload assignment operator to clone
1198 VisItem &operator= (VisItem const &other)
1199 {
1200 visibility = other.visibility;
1201 outer_attrs = other.outer_attrs;
1202
1203 return *this;
1204 }
1205
1206 // move constructors
1207 VisItem (VisItem &&other) = default;
1208 VisItem &operator= (VisItem &&other) = default;
1209
1210 public:
1211 /* Does the item have some kind of public visibility (non-default
1212 * visibility)? */
1213 bool has_visibility () const { return visibility.is_public (); }
1214
1215 std::string as_string () const override;
1216
1217 // TODO: this mutable getter seems really dodgy. Think up better way.
1218 Visibility &get_visibility () { return visibility; }
1219 const Visibility &get_visibility () const { return visibility; }
1220
1221 std::vector<Attribute> &get_outer_attrs () override { return outer_attrs; }
1222 const std::vector<Attribute> &get_outer_attrs () const override
1223 {
1224 return outer_attrs;
1225 }
1226
1227 virtual Item::Kind get_item_kind () const override = 0;
1228 };
1229
1230 // forward decl of ExprWithoutBlock
1231 class ExprWithoutBlock;
1232
1233 // Base expression AST node - abstract
1234 class Expr : public Visitable
1235 {
1236 public:
1237 enum class Kind
1238 {
1239 PathInExpression,
1240 QualifiedPathInExpression,
1241 Literal,
1242 Operator,
1243 Grouped,
1244 Array,
1245 ArrayIndex,
1246 Tuple,
1247 TupleIndex,
1248 Struct,
1249 Call,
1250 MethodCall,
1251 FieldAccess,
1252 Closure,
1253 Block,
1254 Continue,
1255 Break,
1256 Range,
1257 Box,
1258 Return,
1259 UnsafeBlock,
1260 Loop,
1261 If,
1262 IfLet,
1263 Match,
1264 Await,
1265 AsyncBlock,
1266 InlineAsm,
1267 Identifier,
1268 FormatArgs,
1269 MacroInvocation,
1270 Borrow,
1271 Dereference,
1272 ErrorPropagation,
1273 Negation,
1274 ArithmeticOrLogical,
1275 Comparison,
1276 LazyBoolean,
1277 TypeCast,
1278 Assignment,
1279 CompoundAssignment,
1280 };
1281
1282 virtual Kind get_expr_kind () const = 0;
1283
1284 // Unique pointer custom clone function
1285 std::unique_ptr<Expr> clone_expr () const
1286 {
1287 return std::unique_ptr<Expr> (clone_expr_impl ());
1288 }
1289
1290 /* TODO: public methods that could be useful:
1291 * - get_type() - returns type of expression. set_type() may also be useful
1292 * for some?
1293 * - evaluate() - evaluates expression if constant? can_evaluate()? */
1294
1295 virtual std::string as_string () const = 0;
1296
1297 virtual ~Expr () {}
1298
1299 virtual location_t get_locus () const = 0;
1300
1301 virtual bool is_literal () const { return false; }
1302
1303 // HACK: strictly not needed, but faster than full downcast clone
1304 virtual bool is_expr_without_block () const = 0;
1305
1306 virtual void mark_for_strip () = 0;
1307 virtual bool is_marked_for_strip () const = 0;
1308
1309 virtual NodeId get_node_id () const { return node_id; }
1310
1311 virtual void set_node_id (NodeId id) { node_id = id; }
1312
1313 virtual std::vector<Attribute> &get_outer_attrs () = 0;
1314
1315 // TODO: think of less hacky way to implement this kind of thing
1316 // Sets outer attributes.
1317 virtual void set_outer_attrs (std::vector<Attribute>) = 0;
1318
1319 protected:
1320 // Constructor
1321 Expr () : node_id (Analysis::Mappings::get ().get_next_node_id ()) {}
1322
1323 // Clone function implementation as pure virtual method
1324 virtual Expr *clone_expr_impl () const = 0;
1325
1326 NodeId node_id;
1327 };
1328
1329 // AST node for an expression without an accompanying block - abstract
1330 class ExprWithoutBlock : public Expr
1331 {
1332 protected:
1333 // pure virtual clone implementation
1334 virtual ExprWithoutBlock *clone_expr_without_block_impl () const = 0;
1335
1336 /* Save having to specify two clone methods in derived classes by making
1337 * expr clone return exprwithoutblock clone. Hopefully won't affect
1338 * performance too much. */
1339 ExprWithoutBlock *clone_expr_impl () const final override
1340 {
1341 return clone_expr_without_block_impl ();
1342 }
1343
1344 bool is_expr_without_block () const final override { return true; };
1345
1346 public:
1347 // Unique pointer custom clone function
1348 std::unique_ptr<ExprWithoutBlock> clone_expr_without_block () const
1349 {
1350 return std::unique_ptr<ExprWithoutBlock> (clone_expr_without_block_impl ());
1351 }
1352 };
1353
1354 /* HACK: IdentifierExpr, delete when figure out identifier vs expr problem in
1355 * Pratt parser */
1356 /* Alternatively, identifiers could just be represented as single-segment
1357 * paths
1358 */
1359 class IdentifierExpr : public ExprWithoutBlock
1360 {
1361 std::vector<Attribute> outer_attrs;
1362 Identifier ident;
1363 location_t locus;
1364
1365 public:
1366 IdentifierExpr (Identifier ident, std::vector<Attribute> outer_attrs,
1367 location_t locus)
1368 : outer_attrs (std::move (outer_attrs)), ident (std::move (ident)),
1369 locus (locus)
1370 {}
1371
1372 std::string as_string () const override { return ident.as_string (); }
1373
1374 location_t get_locus () const override final { return locus; }
1375
1376 Identifier get_ident () const { return ident; }
1377
1378 void accept_vis (ASTVisitor &vis) override;
1379
1380 // Clones this object.
1381 std::unique_ptr<IdentifierExpr> clone_identifier_expr () const
1382 {
1383 return std::unique_ptr<IdentifierExpr> (clone_identifier_expr_impl ());
1384 }
1385
1386 // "Error state" if ident is empty, so base stripping on this.
1387 void mark_for_strip () override { ident = {""}; }
1388 bool is_marked_for_strip () const override { return ident.empty (); }
1389
1390 const std::vector<Attribute> &get_outer_attrs () const { return outer_attrs; }
1391 std::vector<Attribute> &get_outer_attrs () override { return outer_attrs; }
1392
1393 void set_outer_attrs (std::vector<Attribute> new_attrs) override
1394 {
1395 outer_attrs = std::move (new_attrs);
1396 }
1397
1398 Expr::Kind get_expr_kind () const override { return Expr::Kind::Identifier; }
1399
1400 protected:
1401 // Clone method implementation
1402 IdentifierExpr *clone_expr_without_block_impl () const final override
1403 {
1404 return clone_identifier_expr_impl ();
1405 }
1406
1407 IdentifierExpr *clone_identifier_expr_impl () const
1408 {
1409 return new IdentifierExpr (*this);
1410 }
1411 };
1412
1413 // Pattern base AST node
1414 class Pattern : public Visitable
1415 {
1416 public:
1417 enum class Kind
1418 {
1419 Literal,
1420 Identifier,
1421 Wildcard,
1422 Rest,
1423 Range,
1424 Reference,
1425 Struct,
1426 TupleStruct,
1427 Tuple,
1428 Grouped,
1429 Slice,
1430 Alt,
1431 Path,
1432 MacroInvocation,
1433 };
1434
1435 // Unique pointer custom clone function
1436 std::unique_ptr<Pattern> clone_pattern () const
1437 {
1438 return std::unique_ptr<Pattern> (clone_pattern_impl ());
1439 }
1440
1441 virtual Kind get_pattern_kind () = 0;
1442
1443 // possible virtual methods: is_refutable()
1444
1445 virtual ~Pattern () {}
1446
1447 virtual std::string as_string () const = 0;
1448
1449 // as only one kind of pattern can be stripped, have default of nothing
1450 virtual void mark_for_strip () {}
1451 virtual bool is_marked_for_strip () const { return false; }
1452
1453 virtual location_t get_locus () const = 0;
1454 virtual NodeId get_node_id () const = 0;
1455
1456 protected:
1457 // Clone pattern implementation as pure virtual method
1458 virtual Pattern *clone_pattern_impl () const = 0;
1459 };
1460
1461 // forward decl for Type
1462 class TraitBound;
1463
1464 // Base class for types as represented in AST - abstract
1465 class Type : public Visitable
1466 {
1467 public:
1468 // Unique pointer custom clone function
1469 std::unique_ptr<Type> clone_type () const
1470 {
1471 return std::unique_ptr<Type> (clone_type_impl ());
1472 }
1473
1474 // virtual destructor
1475 virtual ~Type () {}
1476
1477 virtual std::string as_string () const = 0;
1478
1479 /* HACK: convert to trait bound. Virtual method overriden by classes that
1480 * enable this. */
1481 virtual TraitBound *to_trait_bound (bool) const { return nullptr; }
1482 /* as pointer, shouldn't require definition beforehand, only forward
1483 * declaration. */
1484
1485 // as only two kinds of types can be stripped, have default of nothing
1486 virtual void mark_for_strip () {}
1487 virtual bool is_marked_for_strip () const { return false; }
1488
1489 virtual location_t get_locus () const = 0;
1490
1491 NodeId get_node_id () const { return node_id; }
1492
1493 protected:
1494 Type () : node_id (Analysis::Mappings::get ().get_next_node_id ()) {}
1495
1496 // Clone function implementation as pure virtual method
1497 virtual Type *clone_type_impl () const = 0;
1498
1499 NodeId node_id;
1500 };
1501
1502 // A type without parentheses? - abstract
1503 class TypeNoBounds : public Type
1504 {
1505 public:
1506 // Unique pointer custom clone function
1507 std::unique_ptr<TypeNoBounds> clone_type_no_bounds () const
1508 {
1509 return std::unique_ptr<TypeNoBounds> (clone_type_no_bounds_impl ());
1510 }
1511
1512 protected:
1513 // Clone function implementation as pure virtual method
1514 virtual TypeNoBounds *clone_type_no_bounds_impl () const = 0;
1515
1516 /* Save having to specify two clone methods in derived classes by making
1517 * type clone return typenobounds clone. Hopefully won't affect performance
1518 * too much. */
1519 TypeNoBounds *clone_type_impl () const final override
1520 {
1521 return clone_type_no_bounds_impl ();
1522 }
1523
1524 TypeNoBounds () : Type () {}
1525 };
1526
1527 /* Abstract base class representing a type param bound - Lifetime and
1528 * TraitBound extends it */
1529 class TypeParamBound : public Visitable
1530 {
1531 public:
1532 enum TypeParamBoundType
1533 {
1534 TRAIT,
1535 LIFETIME
1536 };
1537
1538 virtual ~TypeParamBound () {}
1539
1540 // Unique pointer custom clone function
1541 std::unique_ptr<TypeParamBound> clone_type_param_bound () const
1542 {
1543 return std::unique_ptr<TypeParamBound> (clone_type_param_bound_impl ());
1544 }
1545
1546 virtual std::string as_string () const = 0;
1547
1548 NodeId get_node_id () const { return node_id; }
1549
1550 virtual location_t get_locus () const = 0;
1551
1552 virtual TypeParamBoundType get_bound_type () const = 0;
1553
1554 protected:
1555 // Clone function implementation as pure virtual method
1556 virtual TypeParamBound *clone_type_param_bound_impl () const = 0;
1557
1558 TypeParamBound (NodeId node_id) : node_id (node_id) {}
1559
1560 NodeId node_id;
1561 };
1562
1563 // Represents a lifetime (and is also a kind of type param bound)
1564 class Lifetime : public TypeParamBound
1565 {
1566 public:
1567 enum LifetimeType
1568 {
1569 NAMED, // corresponds to LIFETIME_OR_LABEL
1570 STATIC, // corresponds to 'static
1571 WILDCARD // corresponds to '_
1572 };
1573
1574 private:
1575 LifetimeType lifetime_type;
1576 std::string lifetime_name;
1577 location_t locus;
1578 NodeId node_id;
1579
1580 public:
1581 // Constructor
1582 Lifetime (LifetimeType type, std::string name = std::string (),
1583 location_t locus = UNDEF_LOCATION)
1584 : TypeParamBound (Analysis::Mappings::get ().get_next_node_id ()),
1585 lifetime_type (type), lifetime_name (std::move (name)), locus (locus)
1586 {}
1587
1588 Lifetime (NodeId id, LifetimeType type, std::string name = std::string (),
1589 location_t locus = UNDEF_LOCATION)
1590 : TypeParamBound (id), lifetime_type (type),
1591 lifetime_name (std::move (name)), locus (locus)
1592 {}
1593
1594 static Lifetime elided () { return Lifetime (WILDCARD, ""); }
1595
1596 // Returns true if the lifetime is in an error state.
1597 std::string as_string () const override;
1598
1599 void accept_vis (ASTVisitor &vis) override;
1600
1601 LifetimeType get_lifetime_type () const { return lifetime_type; }
1602
1603 location_t get_locus () const override final { return locus; }
1604
1605 std::string get_lifetime_name () const { return lifetime_name; }
1606
1607 TypeParamBoundType get_bound_type () const override
1608 {
1609 return TypeParamBound::TypeParamBoundType::LIFETIME;
1610 }
1611
1612 protected:
1613 /* Use covariance to implement clone function as returning this object
1614 * rather than base */
1615 Lifetime *clone_type_param_bound_impl () const override
1616 {
1617 return new Lifetime (node_id, lifetime_type, lifetime_name, locus);
1618 }
1619 };
1620
1621 /* Base generic parameter in AST. Abstract - can be represented by a Lifetime
1622 * or Type param */
1623 class GenericParam : public Visitable
1624 {
1625 public:
1626 enum class Kind
1627 {
1628 Lifetime,
1629 Type,
1630 Const,
1631 };
1632
1633 virtual ~GenericParam () {}
1634
1635 // Unique pointer custom clone function
1636 std::unique_ptr<GenericParam> clone_generic_param () const
1637 {
1638 return std::unique_ptr<GenericParam> (clone_generic_param_impl ());
1639 }
1640
1641 virtual std::string as_string () const = 0;
1642
1643 virtual location_t get_locus () const = 0;
1644
1645 virtual Kind get_kind () const = 0;
1646
1647 NodeId get_node_id () const { return node_id; }
1648
1649 protected:
1650 GenericParam () : node_id (Analysis::Mappings::get ().get_next_node_id ()) {}
1651 GenericParam (NodeId node_id) : node_id (node_id) {}
1652
1653 // Clone function implementation as pure virtual method
1654 virtual GenericParam *clone_generic_param_impl () const = 0;
1655
1656 NodeId node_id;
1657 };
1658
1659 // A lifetime generic parameter (as opposed to a type generic parameter)
1660 class LifetimeParam : public GenericParam
1661 {
1662 Lifetime lifetime;
1663 std::vector<Lifetime> lifetime_bounds;
1664 AST::AttrVec outer_attrs;
1665 location_t locus;
1666
1667 public:
1668 Lifetime get_lifetime () const { return lifetime; }
1669
1670 Lifetime &get_lifetime () { return lifetime; }
1671
1672 AST::AttrVec &get_outer_attrs () { return outer_attrs; }
1673
1674 // Returns whether the lifetime param has any lifetime bounds.
1675 bool has_lifetime_bounds () const { return !lifetime_bounds.empty (); }
1676
1677 std::vector<Lifetime> &get_lifetime_bounds () { return lifetime_bounds; }
1678
1679 const std::vector<Lifetime> &get_lifetime_bounds () const
1680 {
1681 return lifetime_bounds;
1682 }
1683
1684 // Returns whether the lifetime param has an outer attribute.
1685 bool has_outer_attribute () const { return !outer_attrs.empty (); }
1686
1687 // Constructor
1688 LifetimeParam (Lifetime lifetime, std::vector<Lifetime> lifetime_bounds,
1689 AST::AttrVec outer_attrs, location_t locus)
1690 : lifetime (std::move (lifetime)),
1691 lifetime_bounds (std::move (lifetime_bounds)),
1692 outer_attrs (std::move (outer_attrs)), locus (locus)
1693 {}
1694
1695 std::string as_string () const override;
1696
1697 void accept_vis (ASTVisitor &vis) override;
1698
1699 location_t get_locus () const override final { return locus; }
1700
1701 Kind get_kind () const override final { return Kind::Lifetime; }
1702
1703 protected:
1704 /* Use covariance to implement clone function as returning this object
1705 * rather than base */
1706 LifetimeParam *clone_generic_param_impl () const override
1707 {
1708 return new LifetimeParam (*this);
1709 }
1710 };
1711
1712 class AssociatedItem : public Visitable
1713 {
1714 protected:
1715 // Clone function implementation as pure virtual method
1716 virtual AssociatedItem *clone_associated_item_impl () const = 0;
1717
1718 public:
1719 virtual ~AssociatedItem () {}
1720
1721 std::unique_ptr<AssociatedItem> clone_associated_item () const
1722 {
1723 return std::unique_ptr<AssociatedItem> (clone_associated_item_impl ());
1724 }
1725
1726 virtual std::string as_string () const = 0;
1727
1728 virtual void mark_for_strip () = 0;
1729 virtual bool is_marked_for_strip () const = 0;
1730
1731 virtual location_t get_locus () const = 0;
1732 };
1733
1734 // Item used in trait declarations - abstract base class
1735 class TraitItem : public AssociatedItem
1736 {
1737 protected:
1738 TraitItem (location_t locus)
1739 : node_id (Analysis::Mappings::get ().get_next_node_id ()),
1740 vis (Visibility::create_private ()), locus (locus)
1741 {}
1742
1743 TraitItem (Visibility vis, location_t locus)
1744 : node_id (Analysis::Mappings::get ().get_next_node_id ()), vis (vis),
1745 locus (locus)
1746 {}
1747
1748 // Clone function implementation as pure virtual method
1749 virtual TraitItem *clone_associated_item_impl () const override = 0;
1750
1751 NodeId node_id;
1752 Visibility vis;
1753 location_t locus;
1754
1755 public:
1756 // Unique pointer custom clone function
1757 std::unique_ptr<TraitItem> clone_trait_item () const
1758 {
1759 return std::unique_ptr<TraitItem> (clone_associated_item_impl ());
1760 }
1761
1762 NodeId get_node_id () const { return node_id; }
1763 location_t get_locus () const override { return locus; }
1764 };
1765
1766 // Abstract base class for an item used inside an extern block
1767 class ExternalItem : public Visitable
1768 {
1769 public:
1770 ExternalItem () : node_id (Analysis::Mappings::get ().get_next_node_id ()) {}
1771
1772 ExternalItem (NodeId node_id) : node_id (node_id) {}
1773
1774 virtual ~ExternalItem () {}
1775
1776 // Unique pointer custom clone function
1777 std::unique_ptr<ExternalItem> clone_external_item () const
1778 {
1779 return std::unique_ptr<ExternalItem> (clone_external_item_impl ());
1780 }
1781
1782 virtual std::string as_string () const = 0;
1783
1784 virtual void mark_for_strip () = 0;
1785 virtual bool is_marked_for_strip () const = 0;
1786
1787 virtual NodeId get_node_id () const { return node_id; }
1788
1789 protected:
1790 // Clone function implementation as pure virtual method
1791 virtual ExternalItem *clone_external_item_impl () const = 0;
1792
1793 NodeId node_id;
1794 };
1795
1796 /* Data structure to store the data used in macro invocations and macro
1797 * invocations with semicolons. */
1798 struct MacroInvocData
1799 {
1800 private:
1801 SimplePath path;
1802 DelimTokenTree token_tree;
1803
1804 // One way of parsing the macro. Probably not applicable for all macros.
1805 std::vector<std::unique_ptr<MetaItemInner>> parsed_items;
1806 bool parsed_to_meta_item = false;
1807 MacroExpander *expander = nullptr;
1808
1809 public:
1810 std::string as_string () const;
1811
1812 MacroInvocData (SimplePath path, DelimTokenTree token_tree)
1813 : path (std::move (path)), token_tree (std::move (token_tree))
1814 {}
1815
1816 // Copy constructor with vector clone
1817 MacroInvocData (const MacroInvocData &other)
1818 : path (other.path), token_tree (other.token_tree),
1819 parsed_to_meta_item (other.parsed_to_meta_item)
1820 {
1821 parsed_items.reserve (other.parsed_items.size ());
1822 for (const auto &e : other.parsed_items)
1823 parsed_items.push_back (e->clone_meta_item_inner ());
1824 }
1825
1826 // Copy assignment operator with vector clone
1827 MacroInvocData &operator= (const MacroInvocData &other)
1828 {
1829 path = other.path;
1830 token_tree = other.token_tree;
1831 parsed_to_meta_item = other.parsed_to_meta_item;
1832 expander = other.expander;
1833
1834 parsed_items.reserve (other.parsed_items.size ());
1835 for (const auto &e : other.parsed_items)
1836 parsed_items.push_back (e->clone_meta_item_inner ());
1837
1838 return *this;
1839 }
1840
1841 // Move constructors
1842 MacroInvocData (MacroInvocData &&other) = default;
1843 MacroInvocData &operator= (MacroInvocData &&other) = default;
1844
1845 // Invalid if path is empty, so base stripping on that.
1846 void mark_for_strip () { path = SimplePath::create_empty (); }
1847 bool is_marked_for_strip () const { return path.is_empty (); }
1848
1849 // Returns whether the macro has been parsed already.
1850 bool is_parsed () const { return parsed_to_meta_item; }
1851 // TODO: update on other ways of parsing it
1852
1853 // TODO: this mutable getter seems kinda dodgy
1854 DelimTokenTree &get_delim_tok_tree () { return token_tree; }
1855 const DelimTokenTree &get_delim_tok_tree () const { return token_tree; }
1856
1857 // Set the delim token tree of a macro invocation
1858 void set_delim_tok_tree (DelimTokenTree tree) { token_tree = tree; }
1859
1860 // TODO: this mutable getter seems kinda dodgy
1861 SimplePath &get_path () { return path; }
1862 const SimplePath &get_path () const { return path; }
1863
1864 void set_expander (MacroExpander *new_expander) { expander = new_expander; }
1865 MacroExpander *get_expander ()
1866 {
1867 rust_assert (expander);
1868 return expander;
1869 }
1870
1871 void
1872 set_meta_item_output (std::vector<std::unique_ptr<MetaItemInner>> new_items)
1873 {
1874 parsed_items = std::move (new_items);
1875 }
1876 // TODO: mutable getter seems kinda dodgy
1877 std::vector<std::unique_ptr<MetaItemInner>> &get_meta_items ()
1878 {
1879 return parsed_items;
1880 }
1881 const std::vector<std::unique_ptr<MetaItemInner>> &get_meta_items () const
1882 {
1883 return parsed_items;
1884 }
1885 };
1886
1887 class SingleASTNode : public Visitable
1888 {
1889 public:
1890 enum NodeType
1891 {
1892 EXPRESSION,
1893 ITEM,
1894 STMT,
1895 EXTERN,
1896 ASSOC_ITEM,
1897 TYPE,
1898 };
1899
1900 private:
1901 NodeType kind;
1902
1903 // FIXME make this a union
1904 std::unique_ptr<Expr> expr;
1905 std::unique_ptr<Item> item;
1906 std::unique_ptr<Stmt> stmt;
1907 std::unique_ptr<ExternalItem> external_item;
1908 std::unique_ptr<AssociatedItem> assoc_item;
1909 std::unique_ptr<Type> type;
1910
1911 public:
1912 SingleASTNode (std::unique_ptr<Expr> expr)
1913 : kind (EXPRESSION), expr (std::move (expr))
1914 {}
1915
1916 SingleASTNode (std::unique_ptr<Item> item)
1917 : kind (ITEM), item (std::move (item))
1918 {}
1919
1920 SingleASTNode (std::unique_ptr<Stmt> stmt)
1921 : kind (STMT), stmt (std::move (stmt))
1922 {}
1923
1924 SingleASTNode (std::unique_ptr<ExternalItem> item)
1925 : kind (EXTERN), external_item (std::move (item))
1926 {}
1927
1928 SingleASTNode (std::unique_ptr<AssociatedItem> item)
1929 : kind (ASSOC_ITEM), assoc_item (std::move (item))
1930 {}
1931
1932 SingleASTNode (std::unique_ptr<Type> type)
1933 : kind (TYPE), type (std::move (type))
1934 {}
1935
1936 SingleASTNode (SingleASTNode const &other);
1937
1938 SingleASTNode operator= (SingleASTNode const &other);
1939
1940 SingleASTNode (SingleASTNode &&other) = default;
1941 SingleASTNode &operator= (SingleASTNode &&other) = default;
1942
1943 NodeType get_kind () const { return kind; }
1944
1945 std::unique_ptr<Expr> &get_expr ()
1946 {
1947 rust_assert (kind == EXPRESSION);
1948 return expr;
1949 }
1950
1951 std::unique_ptr<Item> &get_item ()
1952 {
1953 rust_assert (kind == ITEM);
1954 return item;
1955 }
1956
1957 std::unique_ptr<Stmt> &get_stmt ()
1958 {
1959 rust_assert (kind == STMT);
1960 return stmt;
1961 }
1962
1963 /**
1964 * Access the inner nodes and take ownership of them.
1965 * You can only call these functions once per node
1966 */
1967
1968 std::unique_ptr<Stmt> take_stmt ()
1969 {
1970 rust_assert (!is_error ());
1971 return std::move (stmt);
1972 }
1973
1974 std::unique_ptr<Expr> take_expr ()
1975 {
1976 rust_assert (!is_error ());
1977 return std::move (expr);
1978 }
1979
1980 std::unique_ptr<Item> take_item ()
1981 {
1982 rust_assert (!is_error ());
1983 return std::move (item);
1984 }
1985
1986 std::unique_ptr<ExternalItem> take_external_item ()
1987 {
1988 rust_assert (!is_error ());
1989 return std::move (external_item);
1990 }
1991
1992 std::unique_ptr<AssociatedItem> take_assoc_item ()
1993 {
1994 rust_assert (!is_error ());
1995 return std::move (assoc_item);
1996 }
1997
1998 std::unique_ptr<Type> take_type ()
1999 {
2000 rust_assert (!is_error ());
2001 return std::move (type);
2002 }
2003
2004 void accept_vis (ASTVisitor &vis) override;
2005
2006 bool is_error ();
2007
2008 std::string as_string () const;
2009 };
2010
2011 // A crate AST object - holds all the data for a single compilation unit
2012 struct Crate
2013 {
2014 std::vector<Attribute> inner_attrs;
2015 // dodgy spacing required here
2016 /* TODO: is it better to have a vector of items here or a module (implicit
2017 * top-level one)? */
2018 std::vector<std::unique_ptr<Item>> items;
2019
2020 NodeId node_id;
2021
2022 public:
2023 // Constructor
2024 Crate (std::vector<std::unique_ptr<Item>> items,
2025 std::vector<Attribute> inner_attrs)
2026 : inner_attrs (std::move (inner_attrs)), items (std::move (items)),
2027 node_id (Analysis::Mappings::get ().get_next_node_id ())
2028 {}
2029
2030 // Copy constructor with vector clone
2031 Crate (Crate const &other)
2032 : inner_attrs (other.inner_attrs), node_id (other.node_id)
2033 {
2034 items.reserve (other.items.size ());
2035 for (const auto &e : other.items)
2036 items.push_back (e->clone_item ());
2037 }
2038
2039 ~Crate () = default;
2040
2041 // Overloaded assignment operator with vector clone
2042 Crate &operator= (Crate const &other)
2043 {
2044 inner_attrs = other.inner_attrs;
2045 node_id = other.node_id;
2046
2047 items.reserve (other.items.size ());
2048 for (const auto &e : other.items)
2049 items.push_back (e->clone_item ());
2050
2051 return *this;
2052 }
2053
2054 // Move constructors
2055 Crate (Crate &&other) = default;
2056 Crate &operator= (Crate &&other) = default;
2057
2058 // Get crate representation as string (e.g. for debugging).
2059 std::string as_string () const;
2060
2061 // Delete all crate information, e.g. if fails cfg.
2062 void strip_crate ()
2063 {
2064 inner_attrs.clear ();
2065 inner_attrs.shrink_to_fit ();
2066
2067 items.clear ();
2068 items.shrink_to_fit ();
2069 // TODO: is this the best way to do this?
2070 }
2071
2072 NodeId get_node_id () const { return node_id; }
2073 const std::vector<Attribute> &get_inner_attrs () const { return inner_attrs; }
2074 std::vector<Attribute> &get_inner_attrs () { return inner_attrs; }
2075
2076 std::vector<std::unique_ptr<AST::Item>> take_items ()
2077 {
2078 return std::move (items);
2079 }
2080
2081 void set_items (std::vector<std::unique_ptr<AST::Item>> &&new_items)
2082 {
2083 items = std::move (new_items);
2084 }
2085 };
2086
2087 } // namespace AST
2088 } // namespace Rust
2089
2090 namespace std {
2091 template <> struct less<Rust::Identifier>
2092 {
2093 bool operator() (const Rust::Identifier &lhs,
2094 const Rust::Identifier &rhs) const
2095 {
2096 return lhs.as_string () < rhs.as_string ();
2097 }
2098 };
2099 } // namespace std
2100
2101 #endif