1 // The Rust abstract syntax tree.
3 pub use GenericArgs::*;
4 pub use UnsafeSource::*;
5 pub use crate::symbol::{Ident, Symbol as Name};
6 pub use crate::util::parser::ExprPrecedence;
8 use crate::ext::hygiene::{Mark, SyntaxContext};
9 use crate::parse::token;
10 use crate::print::pprust;
12 use crate::source_map::{dummy_spanned, respan, Spanned};
13 use crate::symbol::{keywords, Symbol};
14 use crate::tokenstream::TokenStream;
17 use rustc_data_structures::indexed_vec::Idx;
18 #[cfg(target_arch = "x86_64")]
19 use rustc_data_structures::static_assert;
20 use rustc_target::spec::abi::Abi;
21 use syntax_pos::{Span, DUMMY_SP};
23 use rustc_data_structures::fx::FxHashSet;
24 use rustc_data_structures::sync::Lrc;
25 use serialize::{self, Decoder, Encoder};
28 pub use rustc_target::abi::FloatTy;
30 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
35 impl fmt::Debug for Label {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 write!(f, "label({:?})", self.ident)
41 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
47 impl fmt::Debug for Lifetime {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 pprust::lifetime_to_string(self)
58 /// A "Path" is essentially Rust's notion of a name.
60 /// It's represented as a sequence of identifiers,
61 /// along with a bunch of supporting information.
63 /// E.g., `std::cmp::PartialEq`.
64 #[derive(Clone, RustcEncodable, RustcDecodable)]
67 /// The segments in the path: the things separated by `::`.
68 /// Global paths begin with `keywords::PathRoot`.
69 pub segments: Vec<PathSegment>,
72 impl PartialEq<Symbol> for Path {
73 fn eq(&self, symbol: &Symbol) -> bool {
74 self.segments.len() == 1 && {
75 let name = self.segments[0].ident.name;
76 // Make sure these symbols are pure strings
77 debug_assert!(!symbol.is_gensymed());
78 debug_assert!(!name.is_gensymed());
84 impl fmt::Debug for Path {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 write!(f, "path({})", pprust::path_to_string(self))
90 impl fmt::Display for Path {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 write!(f, "{}", pprust::path_to_string(self))
97 // Convert a span and an identifier to the corresponding
99 pub fn from_ident(ident: Ident) -> Path {
101 segments: vec![PathSegment::from_ident(ident)],
106 pub fn is_global(&self) -> bool {
107 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
111 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
113 /// E.g., `std`, `String` or `Box<T>`.
114 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
115 pub struct PathSegment {
116 /// The identifier portion of this path segment.
121 /// Type/lifetime parameters attached to this path. They come in
122 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
123 /// `None` means that no parameter list is supplied (`Path`),
124 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
125 /// but it can be empty (`Path<>`).
126 /// `P` is used as a size optimization for the common case with no parameters.
127 pub args: Option<P<GenericArgs>>,
131 pub fn from_ident(ident: Ident) -> Self {
132 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
134 pub fn path_root(span: Span) -> Self {
135 PathSegment::from_ident(Ident::new(keywords::PathRoot.name(), span))
139 /// The arguments of a path segment.
141 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
142 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
143 pub enum GenericArgs {
144 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
145 AngleBracketed(AngleBracketedArgs),
146 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
147 Parenthesized(ParenthesizedArgs),
151 pub fn is_parenthesized(&self) -> bool {
153 Parenthesized(..) => true,
158 pub fn is_angle_bracketed(&self) -> bool {
160 AngleBracketed(..) => true,
165 pub fn span(&self) -> Span {
167 AngleBracketed(ref data) => data.span,
168 Parenthesized(ref data) => data.span,
173 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
174 pub enum GenericArg {
181 pub fn span(&self) -> Span {
183 GenericArg::Lifetime(lt) => lt.ident.span,
184 GenericArg::Type(ty) => ty.span,
185 GenericArg::Const(ct) => ct.value.span,
190 /// A path like `Foo<'a, T>`.
191 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
192 pub struct AngleBracketedArgs {
193 /// The overall span.
195 /// The arguments for this path segment.
196 pub args: Vec<GenericArg>,
197 /// Bindings (equality constraints) on associated types, if present.
198 /// E.g., `Foo<A = Bar>`.
199 pub bindings: Vec<TypeBinding>,
202 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
203 fn into(self) -> Option<P<GenericArgs>> {
204 Some(P(GenericArgs::AngleBracketed(self)))
208 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
209 fn into(self) -> Option<P<GenericArgs>> {
210 Some(P(GenericArgs::Parenthesized(self)))
214 /// A path like `Foo(A, B) -> C`.
215 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
216 pub struct ParenthesizedArgs {
221 pub inputs: Vec<P<Ty>>,
224 pub output: Option<P<Ty>>,
227 impl ParenthesizedArgs {
228 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
231 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
237 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
239 use rustc_data_structures::indexed_vec::Idx;
240 use rustc_data_structures::newtype_index;
244 DEBUG_FORMAT = "NodeId({})"
249 pub use node_id_inner::NodeId;
252 pub fn placeholder_from_mark(mark: Mark) -> Self {
253 NodeId::from_u32(mark.as_u32())
256 pub fn placeholder_to_mark(self) -> Mark {
257 Mark::from_u32(self.as_u32())
261 impl fmt::Display for NodeId {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 fmt::Display::fmt(&self.as_u32(), f)
267 impl serialize::UseSpecializedEncodable for NodeId {
268 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
269 s.emit_u32(self.as_u32())
273 impl serialize::UseSpecializedDecodable for NodeId {
274 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
275 d.read_u32().map(NodeId::from_u32)
279 /// `NodeId` used to represent the root of the crate.
280 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
282 /// When parsing and doing expansions, we initially give all AST nodes this AST
283 /// node value. Then later, in the renumber pass, we renumber them to have
284 /// small, positive ids.
285 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
287 /// A modifier on a bound, currently this is only used for `?Sized`, where the
288 /// modifier is `Maybe`. Negative bounds should also be handled here.
289 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
290 pub enum TraitBoundModifier {
295 /// The AST represents all type param bounds as types.
296 /// `typeck::collect::compute_bounds` matches these against
297 /// the "special" built-in traits (see `middle::lang_items`) and
298 /// detects `Copy`, `Send` and `Sync`.
299 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
300 pub enum GenericBound {
301 Trait(PolyTraitRef, TraitBoundModifier),
306 pub fn span(&self) -> Span {
308 &GenericBound::Trait(ref t, ..) => t.span,
309 &GenericBound::Outlives(ref l) => l.ident.span,
314 pub type GenericBounds = Vec<GenericBound>;
316 /// Specifies the enforced ordering for generic parameters. In the future,
317 /// if we wanted to relax this order, we could override `PartialEq` and
318 /// `PartialOrd`, to allow the kinds to be unordered.
319 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
320 pub enum ParamKindOrd {
326 impl fmt::Display for ParamKindOrd {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329 ParamKindOrd::Lifetime => "lifetime".fmt(f),
330 ParamKindOrd::Type => "type".fmt(f),
331 ParamKindOrd::Const => "const".fmt(f),
336 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
337 pub enum GenericParamKind {
338 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
340 Type { default: Option<P<Ty>> },
344 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
345 pub struct GenericParam {
348 pub attrs: ThinVec<Attribute>,
349 pub bounds: GenericBounds,
351 pub kind: GenericParamKind,
354 /// Represents lifetime, type and const parameters attached to a declaration of
355 /// a function, enum, trait, etc.
356 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
357 pub struct Generics {
358 pub params: Vec<GenericParam>,
359 pub where_clause: WhereClause,
363 impl Default for Generics {
364 /// Creates an instance of `Generics`.
365 fn default() -> Generics {
368 where_clause: WhereClause {
370 predicates: Vec::new(),
378 /// A where-clause in a definition.
379 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
380 pub struct WhereClause {
382 pub predicates: Vec<WherePredicate>,
386 /// A single predicate in a where-clause.
387 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
388 pub enum WherePredicate {
389 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
390 BoundPredicate(WhereBoundPredicate),
391 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
392 RegionPredicate(WhereRegionPredicate),
393 /// An equality predicate (unsupported).
394 EqPredicate(WhereEqPredicate),
397 impl WherePredicate {
398 pub fn span(&self) -> Span {
400 &WherePredicate::BoundPredicate(ref p) => p.span,
401 &WherePredicate::RegionPredicate(ref p) => p.span,
402 &WherePredicate::EqPredicate(ref p) => p.span,
409 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
410 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
411 pub struct WhereBoundPredicate {
413 /// Any generics from a `for` binding
414 pub bound_generic_params: Vec<GenericParam>,
415 /// The type being bounded
416 pub bounded_ty: P<Ty>,
417 /// Trait and lifetime bounds (`Clone+Send+'static`)
418 pub bounds: GenericBounds,
421 /// A lifetime predicate.
423 /// E.g., `'a: 'b + 'c`.
424 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
425 pub struct WhereRegionPredicate {
427 pub lifetime: Lifetime,
428 pub bounds: GenericBounds,
431 /// An equality predicate (unsupported).
434 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
435 pub struct WhereEqPredicate {
442 /// The set of `MetaItem`s that define the compilation environment of the crate,
443 /// used to drive conditional compilation.
444 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
446 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
449 pub attrs: Vec<Attribute>,
453 /// Possible values inside of compile-time attribute lists.
455 /// E.g., the '..' in `#[name(..)]`.
456 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
457 pub enum NestedMetaItem {
458 /// A full MetaItem, for recursive meta items.
462 /// E.g., `"foo"`, `64`, `true`.
466 /// A spanned compile-time attribute item.
468 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
469 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
470 pub struct MetaItem {
472 pub node: MetaItemKind,
476 /// A compile-time attribute item.
478 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
479 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
480 pub enum MetaItemKind {
483 /// E.g., `test` as in `#[test]`.
487 /// E.g., `derive(..)` as in `#[derive(..)]`.
488 List(Vec<NestedMetaItem>),
489 /// Name value meta item.
491 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
495 /// A Block (`{ .. }`).
497 /// E.g., `{ .. }` as in `fn foo() { .. }`.
498 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
500 /// Statements in a block
501 pub stmts: Vec<Stmt>,
503 /// Distinguishes between `unsafe { ... }` and `{ ... }`
504 pub rules: BlockCheckMode,
508 #[derive(Clone, RustcEncodable, RustcDecodable)]
515 impl fmt::Debug for Pat {
516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
522 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
523 let node = match &self.node {
524 PatKind::Wild => TyKind::Infer,
525 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
526 TyKind::Path(None, Path::from_ident(*ident))
528 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
529 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
530 PatKind::Ref(pat, mutbl) => pat
532 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
533 PatKind::Slice(pats, None, _) if pats.len() == 1 => {
534 pats[0].to_ty().map(TyKind::Slice)?
536 PatKind::Tuple(pats, None) => {
537 let mut tys = Vec::with_capacity(pats.len());
538 // FIXME(#48994) - could just be collected into an Option<Vec>
540 tys.push(pat.to_ty()?);
554 pub fn walk<F>(&self, it: &mut F) -> bool
556 F: FnMut(&Pat) -> bool,
563 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
564 PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
565 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
566 s.iter().all(|p| p.walk(it))
568 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
569 PatKind::Slice(ref before, ref slice, ref after) => {
570 before.iter().all(|p| p.walk(it))
571 && slice.iter().all(|p| p.walk(it))
572 && after.iter().all(|p| p.walk(it))
579 | PatKind::Mac(_) => true,
584 /// A single field in a struct pattern
586 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
587 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
588 /// except is_shorthand is true
589 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
590 pub struct FieldPat {
591 /// The identifier for the field
593 /// The pattern the field is destructured to
595 pub is_shorthand: bool,
596 pub attrs: ThinVec<Attribute>,
599 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
600 pub enum BindingMode {
605 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
607 Included(RangeSyntax),
611 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
612 pub enum RangeSyntax {
617 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
619 /// Represents a wildcard pattern (`_`).
622 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
623 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
624 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
625 /// during name resolution.
626 Ident(BindingMode, Ident, Option<P<Pat>>),
628 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
629 /// The `bool` is `true` in the presence of a `..`.
630 Struct(Path, Vec<Spanned<FieldPat>>, /* recovered */ bool),
632 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
633 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
634 /// `0 <= position <= subpats.len()`.
635 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
637 /// A possibly qualified path pattern.
638 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
639 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
640 /// only legally refer to associated constants.
641 Path(Option<QSelf>, Path),
643 /// A tuple pattern (`(a, b)`).
644 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
645 /// `0 <= position <= subpats.len()`.
646 Tuple(Vec<P<Pat>>, Option<usize>),
651 /// A reference pattern (e.g., `&mut (a, b)`).
652 Ref(P<Pat>, Mutability),
657 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
658 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
660 /// `[a, b, ..i, y, z]` is represented as:
661 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
662 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
664 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
667 /// A macro pattern; pre-expansion.
672 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
674 pub enum Mutability {
679 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
681 /// The `+` operator (addition)
683 /// The `-` operator (subtraction)
685 /// The `*` operator (multiplication)
687 /// The `/` operator (division)
689 /// The `%` operator (modulus)
691 /// The `&&` operator (logical and)
693 /// The `||` operator (logical or)
695 /// The `^` operator (bitwise xor)
697 /// The `&` operator (bitwise and)
699 /// The `|` operator (bitwise or)
701 /// The `<<` operator (shift left)
703 /// The `>>` operator (shift right)
705 /// The `==` operator (equality)
707 /// The `<` operator (less than)
709 /// The `<=` operator (less than or equal to)
711 /// The `!=` operator (not equal to)
713 /// The `>=` operator (greater than or equal to)
715 /// The `>` operator (greater than)
720 pub fn to_string(&self) -> &'static str {
743 pub fn lazy(&self) -> bool {
745 BinOpKind::And | BinOpKind::Or => true,
750 pub fn is_shift(&self) -> bool {
752 BinOpKind::Shl | BinOpKind::Shr => true,
757 pub fn is_comparison(&self) -> bool {
760 Eq | Lt | Le | Ne | Gt | Ge => true,
761 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
765 /// Returns `true` if the binary operator takes its arguments by value
766 pub fn is_by_value(&self) -> bool {
767 !self.is_comparison()
771 pub type BinOp = Spanned<BinOpKind>;
773 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
775 /// The `*` operator for dereferencing
777 /// The `!` operator for logical inversion
779 /// The `-` operator for negation
784 /// Returns `true` if the unary operator takes its argument by value
785 pub fn is_by_value(u: UnOp) -> bool {
787 UnOp::Neg | UnOp::Not => true,
792 pub fn to_string(op: UnOp) -> &'static str {
802 #[derive(Clone, RustcEncodable, RustcDecodable)]
810 pub fn add_trailing_semicolon(mut self) -> Self {
811 self.node = match self.node {
812 StmtKind::Expr(expr) => StmtKind::Semi(expr),
813 StmtKind::Mac(mac) => {
814 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
821 pub fn is_item(&self) -> bool {
823 StmtKind::Item(_) => true,
828 pub fn is_expr(&self) -> bool {
830 StmtKind::Expr(_) => true,
836 impl fmt::Debug for Stmt {
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
842 pprust::stmt_to_string(self)
847 #[derive(Clone, RustcEncodable, RustcDecodable)]
849 /// A local (let) binding.
852 /// An item definition.
855 /// Expr without trailing semi-colon.
857 /// Expr with a trailing semi-colon.
860 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
863 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
864 pub enum MacStmtStyle {
865 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
866 /// `foo!(...);`, `foo![...];`).
868 /// The macro statement had braces (e.g., `foo! { ... }`).
870 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
871 /// `foo!(...)`). All of these will end up being converted into macro
876 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
877 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
880 pub ty: Option<P<Ty>>,
881 /// Initializer expression to set the value, if any.
882 pub init: Option<P<Expr>>,
885 pub attrs: ThinVec<Attribute>,
886 /// Origin of this local variable.
887 pub source: LocalSource,
890 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
891 pub enum LocalSource {
892 /// Local was parsed from source.
894 /// Within `ast::IsAsync::Async`, a local is generated that will contain the moved arguments
895 /// of an `async fn`.
899 /// An arm of a 'match'.
901 /// E.g., `0..=10 => { println!("match!") }` as in
905 /// 0..=10 => { println!("match!") },
906 /// _ => { println!("no match!") },
909 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
911 pub attrs: Vec<Attribute>,
912 pub pats: Vec<P<Pat>>,
913 pub guard: Option<Guard>,
917 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
922 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
927 pub is_shorthand: bool,
928 pub attrs: ThinVec<Attribute>,
931 pub type SpannedIdent = Spanned<Ident>;
933 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
934 pub enum BlockCheckMode {
936 Unsafe(UnsafeSource),
939 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
940 pub enum UnsafeSource {
945 /// A constant (expression) that's not an item or associated item,
946 /// but needs its own `DefId` for type-checking, const-eval, etc.
947 /// These are usually found nested inside types (e.g., array lengths)
948 /// or expressions (e.g., repeat counts), and also used to define
949 /// explicit discriminant values for enum variants.
950 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
951 pub struct AnonConst {
957 #[derive(Clone, RustcEncodable, RustcDecodable)]
962 pub attrs: ThinVec<Attribute>,
965 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
966 #[cfg(target_arch = "x86_64")]
967 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 96);
970 /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
972 pub fn returns(&self) -> bool {
973 if let ExprKind::Block(ref block, _) = self.node {
974 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
976 Some(&StmtKind::Expr(_)) => true,
977 Some(&StmtKind::Semi(ref expr)) => {
978 if let ExprKind::Ret(_) = expr.node {
979 // last statement is explicit return
985 // This is a block that doesn't end in either an implicit or explicit return
989 // This is not a block, it is a value
994 fn to_bound(&self) -> Option<GenericBound> {
996 ExprKind::Path(None, path) => Some(GenericBound::Trait(
997 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
998 TraitBoundModifier::None,
1004 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
1005 let node = match &self.node {
1006 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1007 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1008 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1009 ExprKind::AddrOf(mutbl, expr) => expr
1011 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
1012 ExprKind::Repeat(expr, expr_len) => {
1013 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1015 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1016 ExprKind::Tup(exprs) => {
1019 .map(|expr| expr.to_ty())
1020 .collect::<Option<Vec<_>>>()?;
1023 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1024 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1025 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1040 pub fn precedence(&self) -> ExprPrecedence {
1042 ExprKind::Box(_) => ExprPrecedence::Box,
1043 ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
1044 ExprKind::Array(_) => ExprPrecedence::Array,
1045 ExprKind::Call(..) => ExprPrecedence::Call,
1046 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1047 ExprKind::Tup(_) => ExprPrecedence::Tup,
1048 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1049 ExprKind::Unary(..) => ExprPrecedence::Unary,
1050 ExprKind::Lit(_) => ExprPrecedence::Lit,
1051 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1052 ExprKind::If(..) => ExprPrecedence::If,
1053 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
1054 ExprKind::While(..) => ExprPrecedence::While,
1055 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
1056 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1057 ExprKind::Loop(..) => ExprPrecedence::Loop,
1058 ExprKind::Match(..) => ExprPrecedence::Match,
1059 ExprKind::Closure(..) => ExprPrecedence::Closure,
1060 ExprKind::Block(..) => ExprPrecedence::Block,
1061 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1062 ExprKind::Async(..) => ExprPrecedence::Async,
1063 ExprKind::Await(..) => ExprPrecedence::Await,
1064 ExprKind::Assign(..) => ExprPrecedence::Assign,
1065 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1066 ExprKind::Field(..) => ExprPrecedence::Field,
1067 ExprKind::Index(..) => ExprPrecedence::Index,
1068 ExprKind::Range(..) => ExprPrecedence::Range,
1069 ExprKind::Path(..) => ExprPrecedence::Path,
1070 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1071 ExprKind::Break(..) => ExprPrecedence::Break,
1072 ExprKind::Continue(..) => ExprPrecedence::Continue,
1073 ExprKind::Ret(..) => ExprPrecedence::Ret,
1074 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1075 ExprKind::Mac(..) => ExprPrecedence::Mac,
1076 ExprKind::Struct(..) => ExprPrecedence::Struct,
1077 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1078 ExprKind::Paren(..) => ExprPrecedence::Paren,
1079 ExprKind::Try(..) => ExprPrecedence::Try,
1080 ExprKind::Yield(..) => ExprPrecedence::Yield,
1081 ExprKind::Err => ExprPrecedence::Err,
1086 impl fmt::Debug for Expr {
1087 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1088 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1092 /// Limit types of a range (inclusive or exclusive)
1093 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1094 pub enum RangeLimits {
1095 /// Inclusive at the beginning, exclusive at the end
1097 /// Inclusive at the beginning and end
1101 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1103 /// A `box x` expression.
1105 /// First expr is the place; second expr is the value.
1106 ObsoleteInPlace(P<Expr>, P<Expr>),
1107 /// An array (`[a, b, c, d]`)
1108 Array(Vec<P<Expr>>),
1111 /// The first field resolves to the function itself,
1112 /// and the second field is the list of arguments.
1113 /// This also represents calling the constructor of
1114 /// tuple-like ADTs such as tuple structs and enum variants.
1115 Call(P<Expr>, Vec<P<Expr>>),
1116 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1118 /// The `PathSegment` represents the method name and its generic arguments
1119 /// (within the angle brackets).
1120 /// The first element of the vector of an `Expr` is the expression that evaluates
1121 /// to the object on which the method is being called on (the receiver),
1122 /// and the remaining elements are the rest of the arguments.
1123 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1124 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1125 MethodCall(PathSegment, Vec<P<Expr>>),
1126 /// A tuple (e.g., `(a, b, c, d)`).
1128 /// A binary operation (e.g., `a + b`, `a * b`).
1129 Binary(BinOp, P<Expr>, P<Expr>),
1130 /// A unary operation (e.g., `!x`, `*x`).
1131 Unary(UnOp, P<Expr>),
1132 /// A literal (e.g., `1`, `"foo"`).
1134 /// A cast (e.g., `foo as f64`).
1135 Cast(P<Expr>, P<Ty>),
1136 /// A type ascription (e.g., `42: usize`).
1137 Type(P<Expr>, P<Ty>),
1138 /// An `if` block, with an optional `else` block.
1140 /// `if expr { block } else { expr }`
1141 If(P<Expr>, P<Block>, Option<P<Expr>>),
1142 /// An `if let` expression with an optional else block
1144 /// `if let pat = expr { block } else { expr }`
1146 /// This is desugared to a `match` expression.
1147 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1148 /// A while loop, with an optional label
1150 /// `'label: while expr { block }`
1151 While(P<Expr>, P<Block>, Option<Label>),
1152 /// A `while let` loop, with an optional label.
1154 /// `'label: while let pat = expr { block }`
1156 /// This is desugared to a combination of `loop` and `match` expressions.
1157 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1158 /// A `for` loop, with an optional label.
1160 /// `'label: for pat in expr { block }`
1162 /// This is desugared to a combination of `loop` and `match` expressions.
1163 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1164 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1166 /// `'label: loop { block }`
1167 Loop(P<Block>, Option<Label>),
1168 /// A `match` block.
1169 Match(P<Expr>, Vec<Arm>),
1170 /// A closure (e.g., `move |a, b, c| a + b + c`).
1172 /// The final span is the span of the argument block `|...|`.
1173 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1174 /// A block (`'label: { ... }`).
1175 Block(P<Block>, Option<Label>),
1176 /// An async block (`async move { ... }`).
1178 /// The `NodeId` is the `NodeId` for the closure that results from
1179 /// desugaring an async block, just like the NodeId field in the
1180 /// `IsAsync` enum. This is necessary in order to create a def for the
1181 /// closure which can be used as a parent of any child defs. Defs
1182 /// created during lowering cannot be made the parent of any other
1183 /// preexisting defs.
1184 Async(CaptureBy, NodeId, P<Block>),
1185 /// An await expression (`my_future.await`).
1186 Await(AwaitOrigin, P<Expr>),
1188 /// A try block (`try { ... }`).
1191 /// An assignment (`a = foo()`).
1192 Assign(P<Expr>, P<Expr>),
1193 /// An assignment with an operator.
1196 AssignOp(BinOp, P<Expr>, P<Expr>),
1197 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1198 Field(P<Expr>, Ident),
1199 /// An indexing operation (e.g., `foo[2]`).
1200 Index(P<Expr>, P<Expr>),
1201 /// A range (e.g., `1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`).
1202 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1204 /// Variable reference, possibly containing `::` and/or type
1205 /// parameters (e.g., `foo::bar::<baz>`).
1207 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1208 Path(Option<QSelf>, Path),
1210 /// A referencing operation (`&a` or `&mut a`).
1211 AddrOf(Mutability, P<Expr>),
1212 /// A `break`, with an optional label to break, and an optional expression.
1213 Break(Option<Label>, Option<P<Expr>>),
1214 /// A `continue`, with an optional label.
1215 Continue(Option<Label>),
1216 /// A `return`, with an optional value to be returned.
1217 Ret(Option<P<Expr>>),
1219 /// Output of the `asm!()` macro.
1220 InlineAsm(P<InlineAsm>),
1222 /// A macro invocation; pre-expansion.
1225 /// A struct literal expression.
1227 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1228 /// where `base` is the `Option<Expr>`.
1229 Struct(Path, Vec<Field>, Option<P<Expr>>),
1231 /// An array literal constructed from one repeated element.
1233 /// E.g., `[1; 5]`. The expression is the element to be
1234 /// repeated; the constant is the number of times to repeat it.
1235 Repeat(P<Expr>, AnonConst),
1237 /// No-op: used solely so we can pretty-print faithfully.
1240 /// A try expression (`expr?`).
1243 /// A `yield`, with an optional value to be yielded.
1244 Yield(Option<P<Expr>>),
1246 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1250 /// The explicit `Self` type in a "qualified path". The actual
1251 /// path, including the trait and the associated item, is stored
1252 /// separately. `position` represents the index of the associated
1253 /// item qualified with this `Self` type.
1255 /// ```ignore (only-for-syntax-highlight)
1256 /// <Vec<T> as a::b::Trait>::AssociatedItem
1257 /// ^~~~~ ~~~~~~~~~~~~~~^
1260 /// <Vec<T>>::AssociatedItem
1264 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1268 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1269 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1270 /// 0`, this is an empty span.
1271 pub path_span: Span,
1272 pub position: usize,
1275 /// A capture clause.
1276 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1277 pub enum CaptureBy {
1282 /// The movability of a generator / closure literal.
1283 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1284 pub enum Movability {
1289 /// Whether an `await` comes from `await!` or `.await` syntax.
1290 /// FIXME: this should be removed when support for legacy `await!` is removed.
1291 /// https://github.com/rust-lang/rust/issues/60610
1292 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1293 pub enum AwaitOrigin {
1298 pub type Mac = Spanned<Mac_>;
1300 /// Represents a macro invocation. The `Path` indicates which macro
1301 /// is being invoked, and the vector of token-trees contains the source
1302 /// of the macro invocation.
1304 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1305 /// stored in the enclosing item.
1306 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1309 pub delim: MacDelimiter,
1310 pub tts: TokenStream,
1313 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1314 pub enum MacDelimiter {
1321 pub fn stream(&self) -> TokenStream {
1326 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1327 pub struct MacroDef {
1328 pub tokens: TokenStream,
1333 pub fn stream(&self) -> TokenStream {
1334 self.tokens.clone().into()
1338 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1340 /// A regular string, like `"foo"`.
1342 /// A raw string, like `r##"foo"##`.
1344 /// The value is the number of `#` symbols used.
1349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1351 /// The original literal token as written in source code.
1352 pub token: token::Lit,
1353 /// The original literal suffix as written in source code.
1354 pub suffix: Option<Symbol>,
1355 /// The "semantic" representation of the literal lowered from the original tokens.
1356 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1357 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1362 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1363 pub enum LitIntType {
1371 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1372 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1374 /// A string literal (`"foo"`).
1375 Str(Symbol, StrStyle),
1376 /// A byte string (`b"foo"`).
1377 ByteStr(Lrc<Vec<u8>>),
1378 /// A byte char (`b'f'`).
1380 /// A character literal (`'a'`).
1382 /// An integer literal (`1`).
1383 Int(u128, LitIntType),
1384 /// A float literal (`1f64` or `1E10f64`).
1385 Float(Symbol, FloatTy),
1386 /// A float literal without a suffix (`1.0 or 1.0E10`).
1387 FloatUnsuffixed(Symbol),
1388 /// A boolean literal.
1390 /// A recovered character literal that contains mutliple `char`s, most likely a typo.
1395 /// Returns `true` if this literal is a string.
1396 pub fn is_str(&self) -> bool {
1398 LitKind::Str(..) => true,
1403 /// Returns `true` if this literal is byte literal string.
1404 pub fn is_bytestr(&self) -> bool {
1406 LitKind::ByteStr(_) => true,
1411 /// Returns `true` if this is a numeric literal.
1412 pub fn is_numeric(&self) -> bool {
1414 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1419 /// Returns `true` if this literal has no suffix.
1420 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1421 pub fn is_unsuffixed(&self) -> bool {
1423 // unsuffixed variants
1425 | LitKind::ByteStr(..)
1429 | LitKind::Int(_, LitIntType::Unsuffixed)
1430 | LitKind::FloatUnsuffixed(..)
1431 | LitKind::Bool(..) => true,
1432 // suffixed variants
1433 LitKind::Int(_, LitIntType::Signed(..))
1434 | LitKind::Int(_, LitIntType::Unsigned(..))
1435 | LitKind::Float(..) => false,
1439 /// Returns `true` if this literal has a suffix.
1440 pub fn is_suffixed(&self) -> bool {
1441 !self.is_unsuffixed()
1445 // N.B., If you change this, you'll probably want to change the corresponding
1446 // type structure in `middle/ty.rs` as well.
1447 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1450 pub mutbl: Mutability,
1453 /// Represents a method's signature in a trait declaration,
1454 /// or in an implementation.
1455 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1456 pub struct MethodSig {
1457 pub header: FnHeader,
1458 pub decl: P<FnDecl>,
1461 /// Represents an item declaration within a trait declaration,
1462 /// possibly including a default implementation. A trait item is
1463 /// either required (meaning it doesn't have an implementation, just a
1464 /// signature) or provided (meaning it has a default implementation).
1465 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1466 pub struct TraitItem {
1469 pub attrs: Vec<Attribute>,
1470 pub generics: Generics,
1471 pub node: TraitItemKind,
1473 /// See `Item::tokens` for what this is.
1474 pub tokens: Option<TokenStream>,
1477 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1478 pub enum TraitItemKind {
1479 Const(P<Ty>, Option<P<Expr>>),
1480 Method(MethodSig, Option<P<Block>>),
1481 Type(GenericBounds, Option<P<Ty>>),
1485 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1486 pub struct ImplItem {
1489 pub vis: Visibility,
1490 pub defaultness: Defaultness,
1491 pub attrs: Vec<Attribute>,
1492 pub generics: Generics,
1493 pub node: ImplItemKind,
1495 /// See `Item::tokens` for what this is.
1496 pub tokens: Option<TokenStream>,
1499 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1500 pub enum ImplItemKind {
1501 Const(P<Ty>, P<Expr>),
1502 Method(MethodSig, P<Block>),
1504 Existential(GenericBounds),
1508 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1518 impl fmt::Debug for IntTy {
1519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1520 fmt::Display::fmt(self, f)
1524 impl fmt::Display for IntTy {
1525 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1526 write!(f, "{}", self.ty_to_string())
1531 pub fn ty_to_string(&self) -> &'static str {
1533 IntTy::Isize => "isize",
1535 IntTy::I16 => "i16",
1536 IntTy::I32 => "i32",
1537 IntTy::I64 => "i64",
1538 IntTy::I128 => "i128",
1542 pub fn val_to_string(&self, val: i128) -> String {
1543 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1544 // are parsed as `u128`, so we wouldn't want to print an extra negative
1546 format!("{}{}", val as u128, self.ty_to_string())
1549 pub fn bit_width(&self) -> Option<usize> {
1551 IntTy::Isize => return None,
1561 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1572 pub fn ty_to_string(&self) -> &'static str {
1574 UintTy::Usize => "usize",
1576 UintTy::U16 => "u16",
1577 UintTy::U32 => "u32",
1578 UintTy::U64 => "u64",
1579 UintTy::U128 => "u128",
1583 pub fn val_to_string(&self, val: u128) -> String {
1584 format!("{}{}", val, self.ty_to_string())
1587 pub fn bit_width(&self) -> Option<usize> {
1589 UintTy::Usize => return None,
1594 UintTy::U128 => 128,
1599 impl fmt::Debug for UintTy {
1600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1601 fmt::Display::fmt(self, f)
1605 impl fmt::Display for UintTy {
1606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1607 write!(f, "{}", self.ty_to_string())
1611 // Bind a type to an associated type: `A = Foo`.
1612 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1613 pub struct TypeBinding {
1620 #[derive(Clone, RustcEncodable, RustcDecodable)]
1627 impl fmt::Debug for Ty {
1628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1629 write!(f, "type({})", pprust::ty_to_string(self))
1633 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1634 pub struct BareFnTy {
1635 pub unsafety: Unsafety,
1637 pub generic_params: Vec<GenericParam>,
1638 pub decl: P<FnDecl>,
1641 /// The various kinds of type recognized by the compiler.
1642 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1644 /// A variable-length slice (`[T]`).
1646 /// A fixed length array (`[T; n]`).
1647 Array(P<Ty>, AnonConst),
1648 /// A raw pointer (`*const T` or `*mut T`).
1650 /// A reference (`&'a T` or `&'a mut T`).
1651 Rptr(Option<Lifetime>, MutTy),
1652 /// A bare function (e.g., `fn(usize) -> bool`).
1653 BareFn(P<BareFnTy>),
1654 /// The never type (`!`).
1656 /// A tuple (`(A, B, C, D,...)`).
1658 /// A path (`module::module::...::Type`), optionally
1659 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1661 /// Type parameters are stored in the `Path` itself.
1662 Path(Option<QSelf>, Path),
1663 /// A trait object type `Bound1 + Bound2 + Bound3`
1664 /// where `Bound` is a trait or a lifetime.
1665 TraitObject(GenericBounds, TraitObjectSyntax),
1666 /// An `impl Bound1 + Bound2 + Bound3` type
1667 /// where `Bound` is a trait or a lifetime.
1669 /// The `NodeId` exists to prevent lowering from having to
1670 /// generate `NodeId`s on the fly, which would complicate
1671 /// the generation of `existential type` items significantly.
1672 ImplTrait(NodeId, GenericBounds),
1673 /// No-op; kept solely so that we can pretty-print faithfully.
1677 /// This means the type should be inferred instead of it having been
1678 /// specified. This can appear anywhere in a type.
1680 /// Inferred type of a `self` or `&self` argument in a method.
1682 /// A macro in the type position.
1684 /// Placeholder for a kind that has failed to be defined.
1686 /// Placeholder for a `va_list`.
1691 pub fn is_implicit_self(&self) -> bool {
1692 if let TyKind::ImplicitSelf = *self {
1699 pub fn is_unit(&self) -> bool {
1700 if let TyKind::Tup(ref tys) = *self {
1708 /// Syntax used to declare a trait object.
1709 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1710 pub enum TraitObjectSyntax {
1715 /// Inline assembly dialect.
1717 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1718 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1719 pub enum AsmDialect {
1724 /// Inline assembly.
1726 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1727 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1728 pub struct InlineAsmOutput {
1729 pub constraint: Symbol,
1732 pub is_indirect: bool,
1735 /// Inline assembly.
1737 /// E.g., `asm!("NOP");`.
1738 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1739 pub struct InlineAsm {
1741 pub asm_str_style: StrStyle,
1742 pub outputs: Vec<InlineAsmOutput>,
1743 pub inputs: Vec<(Symbol, P<Expr>)>,
1744 pub clobbers: Vec<Symbol>,
1746 pub alignstack: bool,
1747 pub dialect: AsmDialect,
1748 pub ctxt: SyntaxContext,
1751 /// An argument in a function header.
1753 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1754 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1759 pub source: ArgSource,
1762 /// The source of an argument in a function header.
1763 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1764 pub enum ArgSource {
1765 /// Argument as written by the user.
1767 /// Argument from `async fn` lowering, contains the original binding pattern.
1771 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1773 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1774 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1776 /// `self`, `mut self`
1778 /// `&'lt self`, `&'lt mut self`
1779 Region(Option<Lifetime>, Mutability),
1780 /// `self: TYPE`, `mut self: TYPE`
1781 Explicit(P<Ty>, Mutability),
1784 pub type ExplicitSelf = Spanned<SelfKind>;
1787 pub fn to_self(&self) -> Option<ExplicitSelf> {
1788 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1789 if ident.name == keywords::SelfLower.name() {
1790 return match self.ty.node {
1791 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1792 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1793 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1796 self.pat.span.to(self.ty.span),
1797 SelfKind::Explicit(self.ty.clone(), mutbl),
1805 pub fn is_self(&self) -> bool {
1806 if let PatKind::Ident(_, ident, _) = self.pat.node {
1807 ident.name == keywords::SelfLower.name()
1813 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1814 let span = eself.span.to(eself_ident.span);
1815 let infer_ty = P(Ty {
1817 node: TyKind::ImplicitSelf,
1820 let arg = |mutbl, ty| Arg {
1823 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1828 source: ArgSource::Normal,
1831 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1832 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1833 SelfKind::Region(lt, mutbl) => arg(
1834 Mutability::Immutable,
1851 /// Header (not the body) of a function declaration.
1853 /// E.g., `fn foo(bar: baz)`.
1854 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1856 pub inputs: Vec<Arg>,
1857 pub output: FunctionRetTy,
1858 pub c_variadic: bool,
1862 pub fn get_self(&self) -> Option<ExplicitSelf> {
1863 self.inputs.get(0).and_then(Arg::to_self)
1865 pub fn has_self(&self) -> bool {
1866 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1870 /// Is the trait definition an auto trait?
1871 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1877 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1883 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1884 pub struct AsyncArgument {
1887 /// `__arg0: <ty>` argument to replace existing function argument `<pat>: <ty>`. Only if
1888 /// argument is not a simple binding.
1889 pub arg: Option<Arg>,
1890 /// `let __arg0 = __arg0;` statement to be inserted at the start of the block.
1891 pub move_stmt: Stmt,
1892 /// `let <pat> = __arg0;` statement to be inserted at the start of the block, after matching
1893 /// move statement. Only if argument is not a simple binding.
1894 pub pat_stmt: Option<Stmt>,
1897 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1901 return_impl_trait_id: NodeId,
1902 /// This field stores the arguments and statements that are used in HIR lowering to
1903 /// ensure that `async fn` arguments are dropped at the correct time.
1905 /// The argument and statements here are generated at parse time as they are required in
1906 /// both the hir lowering, def collection and name resolution and this stops them needing
1907 /// to be created in each place.
1908 arguments: Vec<AsyncArgument>,
1914 pub fn is_async(&self) -> bool {
1915 if let IsAsync::Async { .. } = *self {
1922 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1923 pub fn opt_return_id(&self) -> Option<NodeId> {
1926 return_impl_trait_id,
1928 } => Some(*return_impl_trait_id),
1929 IsAsync::NotAsync => None,
1934 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1935 pub enum Constness {
1940 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1941 pub enum Defaultness {
1946 impl fmt::Display for Unsafety {
1947 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1950 Unsafety::Normal => "normal",
1951 Unsafety::Unsafe => "unsafe",
1958 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1959 pub enum ImplPolarity {
1960 /// `impl Trait for Type`
1962 /// `impl !Trait for Type`
1966 impl fmt::Debug for ImplPolarity {
1967 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1969 ImplPolarity::Positive => "positive".fmt(f),
1970 ImplPolarity::Negative => "negative".fmt(f),
1975 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1976 pub enum FunctionRetTy {
1977 /// Returns type is not specified.
1979 /// Functions default to `()` and closures default to inference.
1980 /// Span points to where return type would be inserted.
1982 /// Everything else.
1986 impl FunctionRetTy {
1987 pub fn span(&self) -> Span {
1989 FunctionRetTy::Default(span) => span,
1990 FunctionRetTy::Ty(ref ty) => ty.span,
1995 /// Module declaration.
1997 /// E.g., `mod foo;` or `mod foo { .. }`.
1998 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2000 /// A span from the first token past `{` to the last token until `}`.
2001 /// For `mod foo;`, the inner span ranges from the first token
2002 /// to the last token in the external file.
2004 pub items: Vec<P<Item>>,
2005 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2009 /// Foreign module declaration.
2011 /// E.g., `extern { .. }` or `extern C { .. }`.
2012 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2013 pub struct ForeignMod {
2015 pub items: Vec<ForeignItem>,
2018 /// Global inline assembly.
2020 /// Also known as "module-level assembly" or "file-scoped assembly".
2021 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2022 pub struct GlobalAsm {
2024 pub ctxt: SyntaxContext,
2027 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2028 pub struct EnumDef {
2029 pub variants: Vec<Variant>,
2032 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2033 pub struct Variant_ {
2034 /// Name of the variant.
2036 /// Attributes of the variant.
2037 pub attrs: Vec<Attribute>,
2038 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2040 /// Fields and constructor id of the variant.
2041 pub data: VariantData,
2042 /// Explicit discriminant, e.g., `Foo = 1`.
2043 pub disr_expr: Option<AnonConst>,
2046 pub type Variant = Spanned<Variant_>;
2048 /// Part of `use` item to the right of its prefix.
2049 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2050 pub enum UseTreeKind {
2051 /// `use prefix` or `use prefix as rename`
2053 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2055 Simple(Option<Ident>, NodeId, NodeId),
2056 /// `use prefix::{...}`
2057 Nested(Vec<(UseTree, NodeId)>),
2062 /// A tree of paths sharing common prefixes.
2063 /// Used in `use` items both at top-level and inside of braces in import groups.
2064 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2065 pub struct UseTree {
2067 pub kind: UseTreeKind,
2072 pub fn ident(&self) -> Ident {
2074 UseTreeKind::Simple(Some(rename), ..) => rename,
2075 UseTreeKind::Simple(None, ..) => {
2079 .expect("empty prefix in a simple import")
2082 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2087 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2088 /// are contained as statements within items. These two cases need to be
2089 /// distinguished for pretty-printing.
2090 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
2091 pub enum AttrStyle {
2097 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
2099 pub struct AttrId(pub usize);
2101 impl Idx for AttrId {
2102 fn new(idx: usize) -> Self {
2105 fn index(self) -> usize {
2110 /// Metadata associated with an item.
2111 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
2112 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2113 pub struct Attribute {
2115 pub style: AttrStyle,
2117 pub tokens: TokenStream,
2118 pub is_sugared_doc: bool,
2122 /// `TraitRef`s appear in impls.
2124 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2125 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2126 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2127 /// same as the impl's `NodeId`).
2128 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2129 pub struct TraitRef {
2134 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2135 pub struct PolyTraitRef {
2136 /// The `'a` in `<'a> Foo<&'a T>`
2137 pub bound_generic_params: Vec<GenericParam>,
2139 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2140 pub trait_ref: TraitRef,
2146 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2148 bound_generic_params: generic_params,
2149 trait_ref: TraitRef {
2151 ref_id: DUMMY_NODE_ID,
2158 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2159 pub enum CrateSugar {
2160 /// Source is `pub(crate)`.
2163 /// Source is (just) `crate`.
2167 pub type Visibility = Spanned<VisibilityKind>;
2169 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2170 pub enum VisibilityKind {
2173 Restricted { path: P<Path>, id: NodeId },
2177 impl VisibilityKind {
2178 pub fn is_pub(&self) -> bool {
2179 if let VisibilityKind::Public = *self {
2187 /// Field of a struct.
2189 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2190 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2191 pub struct StructField {
2193 pub ident: Option<Ident>,
2194 pub vis: Visibility,
2197 pub attrs: Vec<Attribute>,
2200 /// Fields and constructor ids of enum variants and structs.
2201 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2202 pub enum VariantData {
2205 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2206 Struct(Vec<StructField>, bool),
2209 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2210 Tuple(Vec<StructField>, NodeId),
2213 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2218 /// Return the fields of this variant.
2219 pub fn fields(&self) -> &[StructField] {
2221 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2226 /// Return the `NodeId` of this variant's constructor, if it has one.
2227 pub fn ctor_id(&self) -> Option<NodeId> {
2229 VariantData::Struct(..) => None,
2230 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2237 /// The name might be a dummy name in case of anonymous items.
2238 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2241 pub attrs: Vec<Attribute>,
2244 pub vis: Visibility,
2247 /// Original tokens this item was parsed from. This isn't necessarily
2248 /// available for all items, although over time more and more items should
2249 /// have this be `Some`. Right now this is primarily used for procedural
2250 /// macros, notably custom attributes.
2252 /// Note that the tokens here do not include the outer attributes, but will
2253 /// include inner attributes.
2254 pub tokens: Option<TokenStream>,
2258 /// Return the span that encompasses the attributes.
2259 pub fn span_with_attributes(&self) -> Span {
2260 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2264 /// A function header.
2266 /// All the information between the visibility and the name of the function is
2267 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2268 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2269 pub struct FnHeader {
2270 pub unsafety: Unsafety,
2271 pub asyncness: Spanned<IsAsync>,
2272 pub constness: Spanned<Constness>,
2276 impl Default for FnHeader {
2277 fn default() -> FnHeader {
2279 unsafety: Unsafety::Normal,
2280 asyncness: dummy_spanned(IsAsync::NotAsync),
2281 constness: dummy_spanned(Constness::NotConst),
2287 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2289 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2291 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2292 ExternCrate(Option<Name>),
2293 /// A use declaration (`use` or `pub use`) item.
2295 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2297 /// A static item (`static` or `pub static`).
2299 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2300 Static(P<Ty>, Mutability, P<Expr>),
2301 /// A constant item (`const` or `pub const`).
2303 /// E.g., `const FOO: i32 = 42;`.
2304 Const(P<Ty>, P<Expr>),
2305 /// A function declaration (`fn` or `pub fn`).
2307 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2308 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2309 /// A module declaration (`mod` or `pub mod`).
2311 /// E.g., `mod foo;` or `mod foo { .. }`.
2313 /// An external module (`extern` or `pub extern`).
2315 /// E.g., `extern {}` or `extern "C" {}`.
2316 ForeignMod(ForeignMod),
2317 /// Module-level inline assembly (from `global_asm!()`).
2318 GlobalAsm(P<GlobalAsm>),
2319 /// A type alias (`type` or `pub type`).
2321 /// E.g., `type Foo = Bar<u8>;`.
2322 Ty(P<Ty>, Generics),
2323 /// An existential type declaration (`existential type`).
2325 /// E.g., `existential type Foo: Bar + Boo;`.
2326 Existential(GenericBounds, Generics),
2327 /// An enum definition (`enum` or `pub enum`).
2329 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2330 Enum(EnumDef, Generics),
2331 /// A struct definition (`struct` or `pub struct`).
2333 /// E.g., `struct Foo<A> { x: A }`.
2334 Struct(VariantData, Generics),
2335 /// A union definition (`union` or `pub union`).
2337 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2338 Union(VariantData, Generics),
2339 /// A Trait declaration (`trait` or `pub trait`).
2341 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2342 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2345 /// E.g., `trait Foo = Bar + Quux;`.
2346 TraitAlias(Generics, GenericBounds),
2347 /// An implementation.
2349 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2355 Option<TraitRef>, // (optional) trait this impl implements
2359 /// A macro invocation.
2361 /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2364 /// A macro definition.
2369 pub fn descriptive_variant(&self) -> &str {
2371 ItemKind::ExternCrate(..) => "extern crate",
2372 ItemKind::Use(..) => "use",
2373 ItemKind::Static(..) => "static item",
2374 ItemKind::Const(..) => "constant item",
2375 ItemKind::Fn(..) => "function",
2376 ItemKind::Mod(..) => "module",
2377 ItemKind::ForeignMod(..) => "foreign module",
2378 ItemKind::GlobalAsm(..) => "global asm",
2379 ItemKind::Ty(..) => "type alias",
2380 ItemKind::Existential(..) => "existential type",
2381 ItemKind::Enum(..) => "enum",
2382 ItemKind::Struct(..) => "struct",
2383 ItemKind::Union(..) => "union",
2384 ItemKind::Trait(..) => "trait",
2385 ItemKind::TraitAlias(..) => "trait alias",
2386 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2391 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2392 pub struct ForeignItem {
2394 pub attrs: Vec<Attribute>,
2395 pub node: ForeignItemKind,
2398 pub vis: Visibility,
2401 /// An item within an `extern` block.
2402 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2403 pub enum ForeignItemKind {
2404 /// A foreign function.
2405 Fn(P<FnDecl>, Generics),
2406 /// A foreign static item (`static ext: u8`).
2407 Static(P<Ty>, Mutability),
2410 /// A macro invocation.
2414 impl ForeignItemKind {
2415 pub fn descriptive_variant(&self) -> &str {
2417 ForeignItemKind::Fn(..) => "foreign function",
2418 ForeignItemKind::Static(..) => "foreign static item",
2419 ForeignItemKind::Ty => "foreign type",
2420 ForeignItemKind::Macro(..) => "macro in foreign module",
2430 // Are ASTs encodable?
2432 fn check_asts_encodable() {
2433 fn assert_encodable<T: serialize::Encodable>() {}
2434 assert_encodable::<Crate>();