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::{kw, sym, 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_size;
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 `kw::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 self.segments[0].ident.name == *symbol
80 impl fmt::Debug for Path {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 write!(f, "path({})", pprust::path_to_string(self))
86 impl fmt::Display for Path {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 write!(f, "{}", pprust::path_to_string(self))
93 // Convert a span and an identifier to the corresponding
95 pub fn from_ident(ident: Ident) -> Path {
97 segments: vec![PathSegment::from_ident(ident)],
102 pub fn is_global(&self) -> bool {
103 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
107 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
109 /// E.g., `std`, `String` or `Box<T>`.
110 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
111 pub struct PathSegment {
112 /// The identifier portion of this path segment.
117 /// Type/lifetime parameters attached to this path. They come in
118 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
119 /// `None` means that no parameter list is supplied (`Path`),
120 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
121 /// but it can be empty (`Path<>`).
122 /// `P` is used as a size optimization for the common case with no parameters.
123 pub args: Option<P<GenericArgs>>,
127 pub fn from_ident(ident: Ident) -> Self {
128 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
130 pub fn path_root(span: Span) -> Self {
131 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
135 /// The arguments of a path segment.
137 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
138 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
139 pub enum GenericArgs {
140 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
141 AngleBracketed(AngleBracketedArgs),
142 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
143 Parenthesized(ParenthesizedArgs),
147 pub fn is_parenthesized(&self) -> bool {
149 Parenthesized(..) => true,
154 pub fn is_angle_bracketed(&self) -> bool {
156 AngleBracketed(..) => true,
161 pub fn span(&self) -> Span {
163 AngleBracketed(ref data) => data.span,
164 Parenthesized(ref data) => data.span,
169 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
170 pub enum GenericArg {
177 pub fn span(&self) -> Span {
179 GenericArg::Lifetime(lt) => lt.ident.span,
180 GenericArg::Type(ty) => ty.span,
181 GenericArg::Const(ct) => ct.value.span,
186 /// A path like `Foo<'a, T>`.
187 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
188 pub struct AngleBracketedArgs {
189 /// The overall span.
191 /// The arguments for this path segment.
192 pub args: Vec<GenericArg>,
193 /// Constraints on associated types, if any.
194 /// E.g., `Foo<A = Bar, B: Baz>`.
195 pub constraints: Vec<AssocTyConstraint>,
198 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
199 fn into(self) -> Option<P<GenericArgs>> {
200 Some(P(GenericArgs::AngleBracketed(self)))
204 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
205 fn into(self) -> Option<P<GenericArgs>> {
206 Some(P(GenericArgs::Parenthesized(self)))
210 /// A path like `Foo(A, B) -> C`.
211 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
212 pub struct ParenthesizedArgs {
217 pub inputs: Vec<P<Ty>>,
220 pub output: Option<P<Ty>>,
223 impl ParenthesizedArgs {
224 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
227 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
233 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
235 use rustc_data_structures::indexed_vec::Idx;
236 use rustc_data_structures::newtype_index;
240 DEBUG_FORMAT = "NodeId({})"
245 pub use node_id_inner::NodeId;
248 pub fn placeholder_from_mark(mark: Mark) -> Self {
249 NodeId::from_u32(mark.as_u32())
252 pub fn placeholder_to_mark(self) -> Mark {
253 Mark::from_u32(self.as_u32())
257 impl fmt::Display for NodeId {
258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259 fmt::Display::fmt(&self.as_u32(), f)
263 impl serialize::UseSpecializedEncodable for NodeId {
264 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
265 s.emit_u32(self.as_u32())
269 impl serialize::UseSpecializedDecodable for NodeId {
270 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
271 d.read_u32().map(NodeId::from_u32)
275 /// `NodeId` used to represent the root of the crate.
276 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
278 /// When parsing and doing expansions, we initially give all AST nodes this AST
279 /// node value. Then later, in the renumber pass, we renumber them to have
280 /// small, positive ids.
281 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
283 /// A modifier on a bound, currently this is only used for `?Sized`, where the
284 /// modifier is `Maybe`. Negative bounds should also be handled here.
285 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
286 pub enum TraitBoundModifier {
291 /// The AST represents all type param bounds as types.
292 /// `typeck::collect::compute_bounds` matches these against
293 /// the "special" built-in traits (see `middle::lang_items`) and
294 /// detects `Copy`, `Send` and `Sync`.
295 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
296 pub enum GenericBound {
297 Trait(PolyTraitRef, TraitBoundModifier),
302 pub fn span(&self) -> Span {
304 &GenericBound::Trait(ref t, ..) => t.span,
305 &GenericBound::Outlives(ref l) => l.ident.span,
310 pub type GenericBounds = Vec<GenericBound>;
312 /// Specifies the enforced ordering for generic parameters. In the future,
313 /// if we wanted to relax this order, we could override `PartialEq` and
314 /// `PartialOrd`, to allow the kinds to be unordered.
315 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
316 pub enum ParamKindOrd {
322 impl fmt::Display for ParamKindOrd {
323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325 ParamKindOrd::Lifetime => "lifetime".fmt(f),
326 ParamKindOrd::Type => "type".fmt(f),
327 ParamKindOrd::Const => "const".fmt(f),
332 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
333 pub enum GenericParamKind {
334 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
336 Type { default: Option<P<Ty>> },
340 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
341 pub struct GenericParam {
344 pub attrs: ThinVec<Attribute>,
345 pub bounds: GenericBounds,
347 pub kind: GenericParamKind,
350 /// Represents lifetime, type and const parameters attached to a declaration of
351 /// a function, enum, trait, etc.
352 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
353 pub struct Generics {
354 pub params: Vec<GenericParam>,
355 pub where_clause: WhereClause,
359 impl Default for Generics {
360 /// Creates an instance of `Generics`.
361 fn default() -> Generics {
364 where_clause: WhereClause {
365 predicates: Vec::new(),
373 /// A where-clause in a definition.
374 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
375 pub struct WhereClause {
376 pub predicates: Vec<WherePredicate>,
380 /// A single predicate in a where-clause.
381 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
382 pub enum WherePredicate {
383 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
384 BoundPredicate(WhereBoundPredicate),
385 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
386 RegionPredicate(WhereRegionPredicate),
387 /// An equality predicate (unsupported).
388 EqPredicate(WhereEqPredicate),
391 impl WherePredicate {
392 pub fn span(&self) -> Span {
394 &WherePredicate::BoundPredicate(ref p) => p.span,
395 &WherePredicate::RegionPredicate(ref p) => p.span,
396 &WherePredicate::EqPredicate(ref p) => p.span,
403 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
404 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
405 pub struct WhereBoundPredicate {
407 /// Any generics from a `for` binding
408 pub bound_generic_params: Vec<GenericParam>,
409 /// The type being bounded
410 pub bounded_ty: P<Ty>,
411 /// Trait and lifetime bounds (`Clone+Send+'static`)
412 pub bounds: GenericBounds,
415 /// A lifetime predicate.
417 /// E.g., `'a: 'b + 'c`.
418 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
419 pub struct WhereRegionPredicate {
421 pub lifetime: Lifetime,
422 pub bounds: GenericBounds,
425 /// An equality predicate (unsupported).
428 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
429 pub struct WhereEqPredicate {
436 /// The set of `MetaItem`s that define the compilation environment of the crate,
437 /// used to drive conditional compilation.
438 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
440 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
443 pub attrs: Vec<Attribute>,
447 /// Possible values inside of compile-time attribute lists.
449 /// E.g., the '..' in `#[name(..)]`.
450 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
451 pub enum NestedMetaItem {
452 /// A full MetaItem, for recursive meta items.
456 /// E.g., `"foo"`, `64`, `true`.
460 /// A spanned compile-time attribute item.
462 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
463 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
464 pub struct MetaItem {
466 pub node: MetaItemKind,
470 /// A compile-time attribute item.
472 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
473 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
474 pub enum MetaItemKind {
477 /// E.g., `test` as in `#[test]`.
481 /// E.g., `derive(..)` as in `#[derive(..)]`.
482 List(Vec<NestedMetaItem>),
483 /// Name value meta item.
485 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
489 /// A Block (`{ .. }`).
491 /// E.g., `{ .. }` as in `fn foo() { .. }`.
492 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
494 /// Statements in a block
495 pub stmts: Vec<Stmt>,
497 /// Distinguishes between `unsafe { ... }` and `{ ... }`
498 pub rules: BlockCheckMode,
502 #[derive(Clone, RustcEncodable, RustcDecodable)]
509 impl fmt::Debug for Pat {
510 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
516 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
517 let node = match &self.node {
518 PatKind::Wild => TyKind::Infer,
519 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
520 TyKind::Path(None, Path::from_ident(*ident))
522 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
523 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
524 PatKind::Ref(pat, mutbl) => pat
526 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
527 PatKind::Slice(pats, None, _) if pats.len() == 1 => {
528 pats[0].to_ty().map(TyKind::Slice)?
530 PatKind::Tuple(pats, None) => {
531 let mut tys = Vec::with_capacity(pats.len());
532 // FIXME(#48994) - could just be collected into an Option<Vec>
534 tys.push(pat.to_ty()?);
548 pub fn walk<F>(&self, it: &mut F) -> bool
550 F: FnMut(&Pat) -> bool,
557 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
558 PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
559 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
560 s.iter().all(|p| p.walk(it))
562 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
563 PatKind::Slice(ref before, ref slice, ref after) => {
564 before.iter().all(|p| p.walk(it))
565 && slice.iter().all(|p| p.walk(it))
566 && after.iter().all(|p| p.walk(it))
573 | PatKind::Mac(_) => true,
578 /// A single field in a struct pattern
580 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
581 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
582 /// except is_shorthand is true
583 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
584 pub struct FieldPat {
585 /// The identifier for the field
587 /// The pattern the field is destructured to
589 pub is_shorthand: bool,
590 pub attrs: ThinVec<Attribute>,
593 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
594 pub enum BindingMode {
599 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
601 Included(RangeSyntax),
605 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
606 pub enum RangeSyntax {
611 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
613 /// Represents a wildcard pattern (`_`).
616 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
617 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
618 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
619 /// during name resolution.
620 Ident(BindingMode, Ident, Option<P<Pat>>),
622 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
623 /// The `bool` is `true` in the presence of a `..`.
624 Struct(Path, Vec<Spanned<FieldPat>>, /* recovered */ bool),
626 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
627 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
628 /// `0 <= position <= subpats.len()`.
629 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
631 /// A possibly qualified path pattern.
632 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
633 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
634 /// only legally refer to associated constants.
635 Path(Option<QSelf>, Path),
637 /// A tuple pattern (`(a, b)`).
638 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
639 /// `0 <= position <= subpats.len()`.
640 Tuple(Vec<P<Pat>>, Option<usize>),
645 /// A reference pattern (e.g., `&mut (a, b)`).
646 Ref(P<Pat>, Mutability),
651 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
652 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
654 /// `[a, b, ..i, y, z]` is represented as:
655 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
656 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
658 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
661 /// A macro pattern; pre-expansion.
666 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
668 pub enum Mutability {
673 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
675 /// The `+` operator (addition)
677 /// The `-` operator (subtraction)
679 /// The `*` operator (multiplication)
681 /// The `/` operator (division)
683 /// The `%` operator (modulus)
685 /// The `&&` operator (logical and)
687 /// The `||` operator (logical or)
689 /// The `^` operator (bitwise xor)
691 /// The `&` operator (bitwise and)
693 /// The `|` operator (bitwise or)
695 /// The `<<` operator (shift left)
697 /// The `>>` operator (shift right)
699 /// The `==` operator (equality)
701 /// The `<` operator (less than)
703 /// The `<=` operator (less than or equal to)
705 /// The `!=` operator (not equal to)
707 /// The `>=` operator (greater than or equal to)
709 /// The `>` operator (greater than)
714 pub fn to_string(&self) -> &'static str {
737 pub fn lazy(&self) -> bool {
739 BinOpKind::And | BinOpKind::Or => true,
744 pub fn is_shift(&self) -> bool {
746 BinOpKind::Shl | BinOpKind::Shr => true,
751 pub fn is_comparison(&self) -> bool {
754 Eq | Lt | Le | Ne | Gt | Ge => true,
755 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
759 /// Returns `true` if the binary operator takes its arguments by value
760 pub fn is_by_value(&self) -> bool {
761 !self.is_comparison()
765 pub type BinOp = Spanned<BinOpKind>;
767 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
769 /// The `*` operator for dereferencing
771 /// The `!` operator for logical inversion
773 /// The `-` operator for negation
778 /// Returns `true` if the unary operator takes its argument by value
779 pub fn is_by_value(u: UnOp) -> bool {
781 UnOp::Neg | UnOp::Not => true,
786 pub fn to_string(op: UnOp) -> &'static str {
796 #[derive(Clone, RustcEncodable, RustcDecodable)]
804 pub fn add_trailing_semicolon(mut self) -> Self {
805 self.node = match self.node {
806 StmtKind::Expr(expr) => StmtKind::Semi(expr),
807 StmtKind::Mac(mac) => {
808 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
815 pub fn is_item(&self) -> bool {
817 StmtKind::Item(_) => true,
822 pub fn is_expr(&self) -> bool {
824 StmtKind::Expr(_) => true,
830 impl fmt::Debug for Stmt {
831 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
836 pprust::stmt_to_string(self)
841 #[derive(Clone, RustcEncodable, RustcDecodable)]
843 /// A local (let) binding.
846 /// An item definition.
849 /// Expr without trailing semi-colon.
851 /// Expr with a trailing semi-colon.
854 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
857 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
858 pub enum MacStmtStyle {
859 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
860 /// `foo!(...);`, `foo![...];`).
862 /// The macro statement had braces (e.g., `foo! { ... }`).
864 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
865 /// `foo!(...)`). All of these will end up being converted into macro
870 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
871 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
874 pub ty: Option<P<Ty>>,
875 /// Initializer expression to set the value, if any.
876 pub init: Option<P<Expr>>,
879 pub attrs: ThinVec<Attribute>,
882 /// An arm of a 'match'.
884 /// E.g., `0..=10 => { println!("match!") }` as in
888 /// 0..=10 => { println!("match!") },
889 /// _ => { println!("no match!") },
892 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
894 pub attrs: Vec<Attribute>,
895 pub pats: Vec<P<Pat>>,
896 pub guard: Option<P<Expr>>,
901 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
906 pub is_shorthand: bool,
907 pub attrs: ThinVec<Attribute>,
910 pub type SpannedIdent = Spanned<Ident>;
912 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
913 pub enum BlockCheckMode {
915 Unsafe(UnsafeSource),
918 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
919 pub enum UnsafeSource {
924 /// A constant (expression) that's not an item or associated item,
925 /// but needs its own `DefId` for type-checking, const-eval, etc.
926 /// These are usually found nested inside types (e.g., array lengths)
927 /// or expressions (e.g., repeat counts), and also used to define
928 /// explicit discriminant values for enum variants.
929 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
930 pub struct AnonConst {
936 #[derive(Clone, RustcEncodable, RustcDecodable)]
941 pub attrs: ThinVec<Attribute>,
944 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
945 #[cfg(target_arch = "x86_64")]
946 static_assert_size!(Expr, 96);
949 /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
951 pub fn returns(&self) -> bool {
952 if let ExprKind::Block(ref block, _) = self.node {
953 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
955 Some(&StmtKind::Expr(_)) => true,
956 Some(&StmtKind::Semi(ref expr)) => {
957 if let ExprKind::Ret(_) = expr.node {
958 // last statement is explicit return
964 // This is a block that doesn't end in either an implicit or explicit return
968 // This is not a block, it is a value
973 fn to_bound(&self) -> Option<GenericBound> {
975 ExprKind::Path(None, path) => Some(GenericBound::Trait(
976 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
977 TraitBoundModifier::None,
983 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
984 let node = match &self.node {
985 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
986 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
987 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
988 ExprKind::AddrOf(mutbl, expr) => expr
990 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
991 ExprKind::Repeat(expr, expr_len) => {
992 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
994 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
995 ExprKind::Tup(exprs) => {
998 .map(|expr| expr.to_ty())
999 .collect::<Option<Vec<_>>>()?;
1002 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1003 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1004 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1019 pub fn precedence(&self) -> ExprPrecedence {
1021 ExprKind::Box(_) => ExprPrecedence::Box,
1022 ExprKind::Array(_) => ExprPrecedence::Array,
1023 ExprKind::Call(..) => ExprPrecedence::Call,
1024 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1025 ExprKind::Tup(_) => ExprPrecedence::Tup,
1026 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1027 ExprKind::Unary(..) => ExprPrecedence::Unary,
1028 ExprKind::Lit(_) => ExprPrecedence::Lit,
1029 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1030 ExprKind::Let(..) => ExprPrecedence::Let,
1031 ExprKind::If(..) => ExprPrecedence::If,
1032 ExprKind::While(..) => ExprPrecedence::While,
1033 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1034 ExprKind::Loop(..) => ExprPrecedence::Loop,
1035 ExprKind::Match(..) => ExprPrecedence::Match,
1036 ExprKind::Closure(..) => ExprPrecedence::Closure,
1037 ExprKind::Block(..) => ExprPrecedence::Block,
1038 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1039 ExprKind::Async(..) => ExprPrecedence::Async,
1040 ExprKind::Await(..) => ExprPrecedence::Await,
1041 ExprKind::Assign(..) => ExprPrecedence::Assign,
1042 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1043 ExprKind::Field(..) => ExprPrecedence::Field,
1044 ExprKind::Index(..) => ExprPrecedence::Index,
1045 ExprKind::Range(..) => ExprPrecedence::Range,
1046 ExprKind::Path(..) => ExprPrecedence::Path,
1047 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1048 ExprKind::Break(..) => ExprPrecedence::Break,
1049 ExprKind::Continue(..) => ExprPrecedence::Continue,
1050 ExprKind::Ret(..) => ExprPrecedence::Ret,
1051 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1052 ExprKind::Mac(..) => ExprPrecedence::Mac,
1053 ExprKind::Struct(..) => ExprPrecedence::Struct,
1054 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1055 ExprKind::Paren(..) => ExprPrecedence::Paren,
1056 ExprKind::Try(..) => ExprPrecedence::Try,
1057 ExprKind::Yield(..) => ExprPrecedence::Yield,
1058 ExprKind::Err => ExprPrecedence::Err,
1063 impl fmt::Debug for Expr {
1064 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1065 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1069 /// Limit types of a range (inclusive or exclusive)
1070 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1071 pub enum RangeLimits {
1072 /// Inclusive at the beginning, exclusive at the end
1074 /// Inclusive at the beginning and end
1078 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1080 /// A `box x` expression.
1082 /// An array (`[a, b, c, d]`)
1083 Array(Vec<P<Expr>>),
1086 /// The first field resolves to the function itself,
1087 /// and the second field is the list of arguments.
1088 /// This also represents calling the constructor of
1089 /// tuple-like ADTs such as tuple structs and enum variants.
1090 Call(P<Expr>, Vec<P<Expr>>),
1091 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1093 /// The `PathSegment` represents the method name and its generic arguments
1094 /// (within the angle brackets).
1095 /// The first element of the vector of an `Expr` is the expression that evaluates
1096 /// to the object on which the method is being called on (the receiver),
1097 /// and the remaining elements are the rest of the arguments.
1098 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1099 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1100 MethodCall(PathSegment, Vec<P<Expr>>),
1101 /// A tuple (e.g., `(a, b, c, d)`).
1103 /// A binary operation (e.g., `a + b`, `a * b`).
1104 Binary(BinOp, P<Expr>, P<Expr>),
1105 /// A unary operation (e.g., `!x`, `*x`).
1106 Unary(UnOp, P<Expr>),
1107 /// A literal (e.g., `1`, `"foo"`).
1109 /// A cast (e.g., `foo as f64`).
1110 Cast(P<Expr>, P<Ty>),
1111 /// A type ascription (e.g., `42: usize`).
1112 Type(P<Expr>, P<Ty>),
1113 /// A `let pats = expr` expression that is only semantically allowed in the condition
1114 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1116 /// The `Vec<P<Pat>>` is for or-patterns at the top level.
1117 /// FIXME(54883): Change this to just `P<Pat>`.
1118 Let(Vec<P<Pat>>, P<Expr>),
1119 /// An `if` block, with an optional `else` block.
1121 /// `if expr { block } else { expr }`
1122 If(P<Expr>, P<Block>, Option<P<Expr>>),
1123 /// A while loop, with an optional label.
1125 /// `'label: while expr { block }`
1126 While(P<Expr>, P<Block>, Option<Label>),
1127 /// A `for` loop, with an optional label.
1129 /// `'label: for pat in expr { block }`
1131 /// This is desugared to a combination of `loop` and `match` expressions.
1132 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1133 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1135 /// `'label: loop { block }`
1136 Loop(P<Block>, Option<Label>),
1137 /// A `match` block.
1138 Match(P<Expr>, Vec<Arm>),
1139 /// A closure (e.g., `move |a, b, c| a + b + c`).
1141 /// The final span is the span of the argument block `|...|`.
1142 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1143 /// A block (`'label: { ... }`).
1144 Block(P<Block>, Option<Label>),
1145 /// An async block (`async move { ... }`).
1147 /// The `NodeId` is the `NodeId` for the closure that results from
1148 /// desugaring an async block, just like the NodeId field in the
1149 /// `IsAsync` enum. This is necessary in order to create a def for the
1150 /// closure which can be used as a parent of any child defs. Defs
1151 /// created during lowering cannot be made the parent of any other
1152 /// preexisting defs.
1153 Async(CaptureBy, NodeId, P<Block>),
1154 /// An await expression (`my_future.await`).
1155 Await(AwaitOrigin, P<Expr>),
1157 /// A try block (`try { ... }`).
1160 /// An assignment (`a = foo()`).
1161 Assign(P<Expr>, P<Expr>),
1162 /// An assignment with an operator.
1165 AssignOp(BinOp, P<Expr>, P<Expr>),
1166 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1167 Field(P<Expr>, Ident),
1168 /// An indexing operation (e.g., `foo[2]`).
1169 Index(P<Expr>, P<Expr>),
1170 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1171 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1173 /// Variable reference, possibly containing `::` and/or type
1174 /// parameters (e.g., `foo::bar::<baz>`).
1176 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1177 Path(Option<QSelf>, Path),
1179 /// A referencing operation (`&a` or `&mut a`).
1180 AddrOf(Mutability, P<Expr>),
1181 /// A `break`, with an optional label to break, and an optional expression.
1182 Break(Option<Label>, Option<P<Expr>>),
1183 /// A `continue`, with an optional label.
1184 Continue(Option<Label>),
1185 /// A `return`, with an optional value to be returned.
1186 Ret(Option<P<Expr>>),
1188 /// Output of the `asm!()` macro.
1189 InlineAsm(P<InlineAsm>),
1191 /// A macro invocation; pre-expansion.
1194 /// A struct literal expression.
1196 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1197 /// where `base` is the `Option<Expr>`.
1198 Struct(Path, Vec<Field>, Option<P<Expr>>),
1200 /// An array literal constructed from one repeated element.
1202 /// E.g., `[1; 5]`. The expression is the element to be
1203 /// repeated; the constant is the number of times to repeat it.
1204 Repeat(P<Expr>, AnonConst),
1206 /// No-op: used solely so we can pretty-print faithfully.
1209 /// A try expression (`expr?`).
1212 /// A `yield`, with an optional value to be yielded.
1213 Yield(Option<P<Expr>>),
1215 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1219 /// The explicit `Self` type in a "qualified path". The actual
1220 /// path, including the trait and the associated item, is stored
1221 /// separately. `position` represents the index of the associated
1222 /// item qualified with this `Self` type.
1224 /// ```ignore (only-for-syntax-highlight)
1225 /// <Vec<T> as a::b::Trait>::AssociatedItem
1226 /// ^~~~~ ~~~~~~~~~~~~~~^
1229 /// <Vec<T>>::AssociatedItem
1233 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1237 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1238 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1239 /// 0`, this is an empty span.
1240 pub path_span: Span,
1241 pub position: usize,
1244 /// A capture clause.
1245 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1246 pub enum CaptureBy {
1251 /// The movability of a generator / closure literal.
1252 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1253 pub enum Movability {
1258 /// Whether an `await` comes from `await!` or `.await` syntax.
1259 /// FIXME: this should be removed when support for legacy `await!` is removed.
1260 /// https://github.com/rust-lang/rust/issues/60610
1261 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1262 pub enum AwaitOrigin {
1267 pub type Mac = Spanned<Mac_>;
1269 /// Represents a macro invocation. The `Path` indicates which macro
1270 /// is being invoked, and the vector of token-trees contains the source
1271 /// of the macro invocation.
1273 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1274 /// stored in the enclosing item.
1275 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1278 pub delim: MacDelimiter,
1279 pub tts: TokenStream,
1282 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1283 pub enum MacDelimiter {
1290 pub fn stream(&self) -> TokenStream {
1295 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1296 pub struct MacroDef {
1297 pub tokens: TokenStream,
1302 pub fn stream(&self) -> TokenStream {
1303 self.tokens.clone().into()
1307 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1309 /// A regular string, like `"foo"`.
1311 /// A raw string, like `r##"foo"##`.
1313 /// The value is the number of `#` symbols used.
1318 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1320 /// The original literal token as written in source code.
1321 pub token: token::Lit,
1322 /// The "semantic" representation of the literal lowered from the original tokens.
1323 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1324 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1329 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1330 pub enum LitIntType {
1338 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1339 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1341 /// A string literal (`"foo"`).
1342 Str(Symbol, StrStyle),
1343 /// A byte string (`b"foo"`).
1344 ByteStr(Lrc<Vec<u8>>),
1345 /// A byte char (`b'f'`).
1347 /// A character literal (`'a'`).
1349 /// An integer literal (`1`).
1350 Int(u128, LitIntType),
1351 /// A float literal (`1f64` or `1E10f64`).
1352 Float(Symbol, FloatTy),
1353 /// A float literal without a suffix (`1.0 or 1.0E10`).
1354 FloatUnsuffixed(Symbol),
1355 /// A boolean literal.
1357 /// Placeholder for a literal that wasn't well-formed in some way.
1362 /// Returns `true` if this literal is a string.
1363 pub fn is_str(&self) -> bool {
1365 LitKind::Str(..) => true,
1370 /// Returns `true` if this literal is byte literal string.
1371 pub fn is_bytestr(&self) -> bool {
1373 LitKind::ByteStr(_) => true,
1378 /// Returns `true` if this is a numeric literal.
1379 pub fn is_numeric(&self) -> bool {
1381 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1386 /// Returns `true` if this literal has no suffix.
1387 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1388 pub fn is_unsuffixed(&self) -> bool {
1390 // unsuffixed variants
1392 | LitKind::ByteStr(..)
1395 | LitKind::Int(_, LitIntType::Unsuffixed)
1396 | LitKind::FloatUnsuffixed(..)
1398 | LitKind::Err(..) => true,
1399 // suffixed variants
1400 LitKind::Int(_, LitIntType::Signed(..))
1401 | LitKind::Int(_, LitIntType::Unsigned(..))
1402 | LitKind::Float(..) => false,
1406 /// Returns `true` if this literal has a suffix.
1407 pub fn is_suffixed(&self) -> bool {
1408 !self.is_unsuffixed()
1412 // N.B., If you change this, you'll probably want to change the corresponding
1413 // type structure in `middle/ty.rs` as well.
1414 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1417 pub mutbl: Mutability,
1420 /// Represents a method's signature in a trait declaration,
1421 /// or in an implementation.
1422 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1423 pub struct MethodSig {
1424 pub header: FnHeader,
1425 pub decl: P<FnDecl>,
1428 /// Represents an item declaration within a trait declaration,
1429 /// possibly including a default implementation. A trait item is
1430 /// either required (meaning it doesn't have an implementation, just a
1431 /// signature) or provided (meaning it has a default implementation).
1432 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1433 pub struct TraitItem {
1436 pub attrs: Vec<Attribute>,
1437 pub generics: Generics,
1438 pub node: TraitItemKind,
1440 /// See `Item::tokens` for what this is.
1441 pub tokens: Option<TokenStream>,
1444 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1445 pub enum TraitItemKind {
1446 Const(P<Ty>, Option<P<Expr>>),
1447 Method(MethodSig, Option<P<Block>>),
1448 Type(GenericBounds, Option<P<Ty>>),
1452 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1453 pub struct ImplItem {
1456 pub vis: Visibility,
1457 pub defaultness: Defaultness,
1458 pub attrs: Vec<Attribute>,
1459 pub generics: Generics,
1460 pub node: ImplItemKind,
1462 /// See `Item::tokens` for what this is.
1463 pub tokens: Option<TokenStream>,
1466 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1467 pub enum ImplItemKind {
1468 Const(P<Ty>, P<Expr>),
1469 Method(MethodSig, P<Block>),
1471 Existential(GenericBounds),
1475 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1485 impl fmt::Debug for IntTy {
1486 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1487 fmt::Display::fmt(self, f)
1491 impl fmt::Display for IntTy {
1492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1493 write!(f, "{}", self.ty_to_string())
1498 pub fn ty_to_string(&self) -> &'static str {
1500 IntTy::Isize => "isize",
1502 IntTy::I16 => "i16",
1503 IntTy::I32 => "i32",
1504 IntTy::I64 => "i64",
1505 IntTy::I128 => "i128",
1509 pub fn to_symbol(&self) -> Symbol {
1511 IntTy::Isize => sym::isize,
1512 IntTy::I8 => sym::i8,
1513 IntTy::I16 => sym::i16,
1514 IntTy::I32 => sym::i32,
1515 IntTy::I64 => sym::i64,
1516 IntTy::I128 => sym::i128,
1520 pub fn val_to_string(&self, val: i128) -> String {
1521 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1522 // are parsed as `u128`, so we wouldn't want to print an extra negative
1524 format!("{}{}", val as u128, self.ty_to_string())
1527 pub fn bit_width(&self) -> Option<usize> {
1529 IntTy::Isize => return None,
1539 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1550 pub fn ty_to_string(&self) -> &'static str {
1552 UintTy::Usize => "usize",
1554 UintTy::U16 => "u16",
1555 UintTy::U32 => "u32",
1556 UintTy::U64 => "u64",
1557 UintTy::U128 => "u128",
1561 pub fn to_symbol(&self) -> Symbol {
1563 UintTy::Usize => sym::usize,
1564 UintTy::U8 => sym::u8,
1565 UintTy::U16 => sym::u16,
1566 UintTy::U32 => sym::u32,
1567 UintTy::U64 => sym::u64,
1568 UintTy::U128 => sym::u128,
1572 pub fn val_to_string(&self, val: u128) -> String {
1573 format!("{}{}", val, self.ty_to_string())
1576 pub fn bit_width(&self) -> Option<usize> {
1578 UintTy::Usize => return None,
1583 UintTy::U128 => 128,
1588 impl fmt::Debug for UintTy {
1589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1590 fmt::Display::fmt(self, f)
1594 impl fmt::Display for UintTy {
1595 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1596 write!(f, "{}", self.ty_to_string())
1600 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1601 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1602 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1603 pub struct AssocTyConstraint {
1606 pub kind: AssocTyConstraintKind,
1610 /// The kinds of an `AssocTyConstraint`.
1611 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1612 pub enum AssocTyConstraintKind {
1613 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1617 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1619 bounds: GenericBounds,
1623 #[derive(Clone, RustcEncodable, RustcDecodable)]
1630 impl fmt::Debug for Ty {
1631 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1632 write!(f, "type({})", pprust::ty_to_string(self))
1636 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1637 pub struct BareFnTy {
1638 pub unsafety: Unsafety,
1640 pub generic_params: Vec<GenericParam>,
1641 pub decl: P<FnDecl>,
1644 /// The various kinds of type recognized by the compiler.
1645 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1647 /// A variable-length slice (`[T]`).
1649 /// A fixed length array (`[T; n]`).
1650 Array(P<Ty>, AnonConst),
1651 /// A raw pointer (`*const T` or `*mut T`).
1653 /// A reference (`&'a T` or `&'a mut T`).
1654 Rptr(Option<Lifetime>, MutTy),
1655 /// A bare function (e.g., `fn(usize) -> bool`).
1656 BareFn(P<BareFnTy>),
1657 /// The never type (`!`).
1659 /// A tuple (`(A, B, C, D,...)`).
1661 /// A path (`module::module::...::Type`), optionally
1662 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1664 /// Type parameters are stored in the `Path` itself.
1665 Path(Option<QSelf>, Path),
1666 /// A trait object type `Bound1 + Bound2 + Bound3`
1667 /// where `Bound` is a trait or a lifetime.
1668 TraitObject(GenericBounds, TraitObjectSyntax),
1669 /// An `impl Bound1 + Bound2 + Bound3` type
1670 /// where `Bound` is a trait or a lifetime.
1672 /// The `NodeId` exists to prevent lowering from having to
1673 /// generate `NodeId`s on the fly, which would complicate
1674 /// the generation of `existential type` items significantly.
1675 ImplTrait(NodeId, GenericBounds),
1676 /// No-op; kept solely so that we can pretty-print faithfully.
1680 /// This means the type should be inferred instead of it having been
1681 /// specified. This can appear anywhere in a type.
1683 /// Inferred type of a `self` or `&self` argument in a method.
1685 /// A macro in the type position.
1687 /// Placeholder for a kind that has failed to be defined.
1689 /// Placeholder for a `va_list`.
1694 pub fn is_implicit_self(&self) -> bool {
1695 if let TyKind::ImplicitSelf = *self {
1702 pub fn is_unit(&self) -> bool {
1703 if let TyKind::Tup(ref tys) = *self {
1711 /// Syntax used to declare a trait object.
1712 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1713 pub enum TraitObjectSyntax {
1718 /// Inline assembly dialect.
1720 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1721 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1722 pub enum AsmDialect {
1727 /// Inline assembly.
1729 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1730 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1731 pub struct InlineAsmOutput {
1732 pub constraint: Symbol,
1735 pub is_indirect: bool,
1738 /// Inline assembly.
1740 /// E.g., `asm!("NOP");`.
1741 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1742 pub struct InlineAsm {
1744 pub asm_str_style: StrStyle,
1745 pub outputs: Vec<InlineAsmOutput>,
1746 pub inputs: Vec<(Symbol, P<Expr>)>,
1747 pub clobbers: Vec<Symbol>,
1749 pub alignstack: bool,
1750 pub dialect: AsmDialect,
1751 pub ctxt: SyntaxContext,
1754 /// An argument in a function header.
1756 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1757 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1759 pub attrs: ThinVec<Attribute>,
1765 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1767 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1768 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1770 /// `self`, `mut self`
1772 /// `&'lt self`, `&'lt mut self`
1773 Region(Option<Lifetime>, Mutability),
1774 /// `self: TYPE`, `mut self: TYPE`
1775 Explicit(P<Ty>, Mutability),
1778 pub type ExplicitSelf = Spanned<SelfKind>;
1781 pub fn to_self(&self) -> Option<ExplicitSelf> {
1782 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1783 if ident.name == kw::SelfLower {
1784 return match self.ty.node {
1785 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1786 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1787 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1790 self.pat.span.to(self.ty.span),
1791 SelfKind::Explicit(self.ty.clone(), mutbl),
1799 pub fn is_self(&self) -> bool {
1800 if let PatKind::Ident(_, ident, _) = self.pat.node {
1801 ident.name == kw::SelfLower
1807 pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1808 let span = eself.span.to(eself_ident.span);
1809 let infer_ty = P(Ty {
1811 node: TyKind::ImplicitSelf,
1814 let arg = |mutbl, ty| Arg {
1818 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1825 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1826 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1827 SelfKind::Region(lt, mutbl) => arg(
1828 Mutability::Immutable,
1845 /// A header (not the body) of a function declaration.
1847 /// E.g., `fn foo(bar: baz)`.
1848 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1850 pub inputs: Vec<Arg>,
1851 pub output: FunctionRetTy,
1852 pub c_variadic: bool,
1856 pub fn get_self(&self) -> Option<ExplicitSelf> {
1857 self.inputs.get(0).and_then(Arg::to_self)
1859 pub fn has_self(&self) -> bool {
1860 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1864 /// Is the trait definition an auto trait?
1865 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1871 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1877 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1881 return_impl_trait_id: NodeId,
1887 pub fn is_async(self) -> bool {
1888 if let IsAsync::Async { .. } = self {
1895 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1896 pub fn opt_return_id(self) -> Option<NodeId> {
1899 return_impl_trait_id,
1901 } => Some(return_impl_trait_id),
1902 IsAsync::NotAsync => None,
1907 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1908 pub enum Constness {
1913 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1914 pub enum Defaultness {
1919 impl fmt::Display for Unsafety {
1920 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1923 Unsafety::Normal => "normal",
1924 Unsafety::Unsafe => "unsafe",
1931 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1932 pub enum ImplPolarity {
1933 /// `impl Trait for Type`
1935 /// `impl !Trait for Type`
1939 impl fmt::Debug for ImplPolarity {
1940 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1942 ImplPolarity::Positive => "positive".fmt(f),
1943 ImplPolarity::Negative => "negative".fmt(f),
1948 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1949 pub enum FunctionRetTy {
1950 /// Returns type is not specified.
1952 /// Functions default to `()` and closures default to inference.
1953 /// Span points to where return type would be inserted.
1955 /// Everything else.
1959 impl FunctionRetTy {
1960 pub fn span(&self) -> Span {
1962 FunctionRetTy::Default(span) => span,
1963 FunctionRetTy::Ty(ref ty) => ty.span,
1968 /// Module declaration.
1970 /// E.g., `mod foo;` or `mod foo { .. }`.
1971 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1973 /// A span from the first token past `{` to the last token until `}`.
1974 /// For `mod foo;`, the inner span ranges from the first token
1975 /// to the last token in the external file.
1977 pub items: Vec<P<Item>>,
1978 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
1982 /// Foreign module declaration.
1984 /// E.g., `extern { .. }` or `extern C { .. }`.
1985 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1986 pub struct ForeignMod {
1988 pub items: Vec<ForeignItem>,
1991 /// Global inline assembly.
1993 /// Also known as "module-level assembly" or "file-scoped assembly".
1994 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1995 pub struct GlobalAsm {
1997 pub ctxt: SyntaxContext,
2000 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2001 pub struct EnumDef {
2002 pub variants: Vec<Variant>,
2005 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2006 pub struct Variant_ {
2007 /// Name of the variant.
2009 /// Attributes of the variant.
2010 pub attrs: Vec<Attribute>,
2011 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2013 /// Fields and constructor id of the variant.
2014 pub data: VariantData,
2015 /// Explicit discriminant, e.g., `Foo = 1`.
2016 pub disr_expr: Option<AnonConst>,
2019 pub type Variant = Spanned<Variant_>;
2021 /// Part of `use` item to the right of its prefix.
2022 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2023 pub enum UseTreeKind {
2024 /// `use prefix` or `use prefix as rename`
2026 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2028 Simple(Option<Ident>, NodeId, NodeId),
2029 /// `use prefix::{...}`
2030 Nested(Vec<(UseTree, NodeId)>),
2035 /// A tree of paths sharing common prefixes.
2036 /// Used in `use` items both at top-level and inside of braces in import groups.
2037 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2038 pub struct UseTree {
2040 pub kind: UseTreeKind,
2045 pub fn ident(&self) -> Ident {
2047 UseTreeKind::Simple(Some(rename), ..) => rename,
2048 UseTreeKind::Simple(None, ..) => {
2052 .expect("empty prefix in a simple import")
2055 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2060 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2061 /// are contained as statements within items. These two cases need to be
2062 /// distinguished for pretty-printing.
2063 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
2064 pub enum AttrStyle {
2070 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
2072 pub struct AttrId(pub usize);
2074 impl Idx for AttrId {
2075 fn new(idx: usize) -> Self {
2078 fn index(self) -> usize {
2083 /// Metadata associated with an item.
2084 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
2085 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2086 pub struct Attribute {
2088 pub style: AttrStyle,
2090 pub tokens: TokenStream,
2091 pub is_sugared_doc: bool,
2095 /// `TraitRef`s appear in impls.
2097 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2098 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2099 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2100 /// same as the impl's `NodeId`).
2101 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2102 pub struct TraitRef {
2107 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2108 pub struct PolyTraitRef {
2109 /// The `'a` in `<'a> Foo<&'a T>`.
2110 pub bound_generic_params: Vec<GenericParam>,
2112 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2113 pub trait_ref: TraitRef,
2119 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2121 bound_generic_params: generic_params,
2122 trait_ref: TraitRef {
2124 ref_id: DUMMY_NODE_ID,
2131 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2132 pub enum CrateSugar {
2133 /// Source is `pub(crate)`.
2136 /// Source is (just) `crate`.
2140 pub type Visibility = Spanned<VisibilityKind>;
2142 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2143 pub enum VisibilityKind {
2146 Restricted { path: P<Path>, id: NodeId },
2150 impl VisibilityKind {
2151 pub fn is_pub(&self) -> bool {
2152 if let VisibilityKind::Public = *self {
2160 /// Field of a struct.
2162 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2163 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2164 pub struct StructField {
2166 pub ident: Option<Ident>,
2167 pub vis: Visibility,
2170 pub attrs: Vec<Attribute>,
2173 /// Fields and constructor ids of enum variants and structs.
2174 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2175 pub enum VariantData {
2178 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2179 Struct(Vec<StructField>, bool),
2182 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2183 Tuple(Vec<StructField>, NodeId),
2186 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2191 /// Return the fields of this variant.
2192 pub fn fields(&self) -> &[StructField] {
2194 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2199 /// Return the `NodeId` of this variant's constructor, if it has one.
2200 pub fn ctor_id(&self) -> Option<NodeId> {
2202 VariantData::Struct(..) => None,
2203 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2210 /// The name might be a dummy name in case of anonymous items.
2211 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2214 pub attrs: Vec<Attribute>,
2217 pub vis: Visibility,
2220 /// Original tokens this item was parsed from. This isn't necessarily
2221 /// available for all items, although over time more and more items should
2222 /// have this be `Some`. Right now this is primarily used for procedural
2223 /// macros, notably custom attributes.
2225 /// Note that the tokens here do not include the outer attributes, but will
2226 /// include inner attributes.
2227 pub tokens: Option<TokenStream>,
2231 /// Return the span that encompasses the attributes.
2232 pub fn span_with_attributes(&self) -> Span {
2233 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2237 /// A function header.
2239 /// All the information between the visibility and the name of the function is
2240 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2241 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2242 pub struct FnHeader {
2243 pub unsafety: Unsafety,
2244 pub asyncness: Spanned<IsAsync>,
2245 pub constness: Spanned<Constness>,
2249 impl Default for FnHeader {
2250 fn default() -> FnHeader {
2252 unsafety: Unsafety::Normal,
2253 asyncness: dummy_spanned(IsAsync::NotAsync),
2254 constness: dummy_spanned(Constness::NotConst),
2260 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2262 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2264 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2265 ExternCrate(Option<Name>),
2266 /// A use declaration (`use` or `pub use`) item.
2268 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2270 /// A static item (`static` or `pub static`).
2272 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2273 Static(P<Ty>, Mutability, P<Expr>),
2274 /// A constant item (`const` or `pub const`).
2276 /// E.g., `const FOO: i32 = 42;`.
2277 Const(P<Ty>, P<Expr>),
2278 /// A function declaration (`fn` or `pub fn`).
2280 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2281 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2282 /// A module declaration (`mod` or `pub mod`).
2284 /// E.g., `mod foo;` or `mod foo { .. }`.
2286 /// An external module (`extern` or `pub extern`).
2288 /// E.g., `extern {}` or `extern "C" {}`.
2289 ForeignMod(ForeignMod),
2290 /// Module-level inline assembly (from `global_asm!()`).
2291 GlobalAsm(P<GlobalAsm>),
2292 /// A type alias (`type` or `pub type`).
2294 /// E.g., `type Foo = Bar<u8>;`.
2295 Ty(P<Ty>, Generics),
2296 /// An existential type declaration (`existential type`).
2298 /// E.g., `existential type Foo: Bar + Boo;`.
2299 Existential(GenericBounds, Generics),
2300 /// An enum definition (`enum` or `pub enum`).
2302 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2303 Enum(EnumDef, Generics),
2304 /// A struct definition (`struct` or `pub struct`).
2306 /// E.g., `struct Foo<A> { x: A }`.
2307 Struct(VariantData, Generics),
2308 /// A union definition (`union` or `pub union`).
2310 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2311 Union(VariantData, Generics),
2312 /// A Trait declaration (`trait` or `pub trait`).
2314 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2315 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2318 /// E.g., `trait Foo = Bar + Quux;`.
2319 TraitAlias(Generics, GenericBounds),
2320 /// An implementation.
2322 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2328 Option<TraitRef>, // (optional) trait this impl implements
2332 /// A macro invocation.
2334 /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2337 /// A macro definition.
2342 pub fn descriptive_variant(&self) -> &str {
2344 ItemKind::ExternCrate(..) => "extern crate",
2345 ItemKind::Use(..) => "use",
2346 ItemKind::Static(..) => "static item",
2347 ItemKind::Const(..) => "constant item",
2348 ItemKind::Fn(..) => "function",
2349 ItemKind::Mod(..) => "module",
2350 ItemKind::ForeignMod(..) => "foreign module",
2351 ItemKind::GlobalAsm(..) => "global asm",
2352 ItemKind::Ty(..) => "type alias",
2353 ItemKind::Existential(..) => "existential type",
2354 ItemKind::Enum(..) => "enum",
2355 ItemKind::Struct(..) => "struct",
2356 ItemKind::Union(..) => "union",
2357 ItemKind::Trait(..) => "trait",
2358 ItemKind::TraitAlias(..) => "trait alias",
2359 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2364 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2365 pub struct ForeignItem {
2367 pub attrs: Vec<Attribute>,
2368 pub node: ForeignItemKind,
2371 pub vis: Visibility,
2374 /// An item within an `extern` block.
2375 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2376 pub enum ForeignItemKind {
2377 /// A foreign function.
2378 Fn(P<FnDecl>, Generics),
2379 /// A foreign static item (`static ext: u8`).
2380 Static(P<Ty>, Mutability),
2383 /// A macro invocation.
2387 impl ForeignItemKind {
2388 pub fn descriptive_variant(&self) -> &str {
2390 ForeignItemKind::Fn(..) => "foreign function",
2391 ForeignItemKind::Static(..) => "foreign static item",
2392 ForeignItemKind::Ty => "foreign type",
2393 ForeignItemKind::Macro(..) => "macro in foreign module",
2403 // Are ASTs encodable?
2405 fn check_asts_encodable() {
2406 fn assert_encodable<T: serialize::Encodable>() {}
2407 assert_encodable::<Crate>();