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::{ExpnId, SyntaxContext};
9 use crate::parse::token::{self, DelimToken};
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 rustc_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 {
58 impl fmt::Display for Lifetime {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 write!(f, "{}", self.ident.name.as_str())
64 /// A "Path" is essentially Rust's notion of a name.
66 /// It's represented as a sequence of identifiers,
67 /// along with a bunch of supporting information.
69 /// E.g., `std::cmp::PartialEq`.
70 #[derive(Clone, RustcEncodable, RustcDecodable)]
73 /// The segments in the path: the things separated by `::`.
74 /// Global paths begin with `kw::PathRoot`.
75 pub segments: Vec<PathSegment>,
78 impl PartialEq<Symbol> for Path {
79 fn eq(&self, symbol: &Symbol) -> bool {
80 self.segments.len() == 1 && {
81 self.segments[0].ident.name == *symbol
86 impl fmt::Debug for Path {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 write!(f, "path({})", pprust::path_to_string(self))
92 impl fmt::Display for Path {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 write!(f, "{}", pprust::path_to_string(self))
99 // Convert a span and an identifier to the corresponding
101 pub fn from_ident(ident: Ident) -> Path {
103 segments: vec![PathSegment::from_ident(ident)],
108 pub fn is_global(&self) -> bool {
109 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
113 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
115 /// E.g., `std`, `String` or `Box<T>`.
116 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
117 pub struct PathSegment {
118 /// The identifier portion of this path segment.
123 /// Type/lifetime parameters attached to this path. They come in
124 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
125 /// `None` means that no parameter list is supplied (`Path`),
126 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
127 /// but it can be empty (`Path<>`).
128 /// `P` is used as a size optimization for the common case with no parameters.
129 pub args: Option<P<GenericArgs>>,
133 pub fn from_ident(ident: Ident) -> Self {
134 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
136 pub fn path_root(span: Span) -> Self {
137 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
141 /// The arguments of a path segment.
143 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
144 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
145 pub enum GenericArgs {
146 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
147 AngleBracketed(AngleBracketedArgs),
148 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
149 Parenthesized(ParenthesizedArgs),
153 pub fn is_parenthesized(&self) -> bool {
155 Parenthesized(..) => true,
160 pub fn is_angle_bracketed(&self) -> bool {
162 AngleBracketed(..) => true,
167 pub fn span(&self) -> Span {
169 AngleBracketed(ref data) => data.span,
170 Parenthesized(ref data) => data.span,
175 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
176 pub enum GenericArg {
183 pub fn span(&self) -> Span {
185 GenericArg::Lifetime(lt) => lt.ident.span,
186 GenericArg::Type(ty) => ty.span,
187 GenericArg::Const(ct) => ct.value.span,
192 /// A path like `Foo<'a, T>`.
193 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
194 pub struct AngleBracketedArgs {
195 /// The overall span.
197 /// The arguments for this path segment.
198 pub args: Vec<GenericArg>,
199 /// Constraints on associated types, if any.
200 /// E.g., `Foo<A = Bar, B: Baz>`.
201 pub constraints: Vec<AssocTyConstraint>,
204 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
205 fn into(self) -> Option<P<GenericArgs>> {
206 Some(P(GenericArgs::AngleBracketed(self)))
210 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
211 fn into(self) -> Option<P<GenericArgs>> {
212 Some(P(GenericArgs::Parenthesized(self)))
216 /// A path like `Foo(A, B) -> C`.
217 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
218 pub struct ParenthesizedArgs {
223 pub inputs: Vec<P<Ty>>,
226 pub output: Option<P<Ty>>,
229 impl ParenthesizedArgs {
230 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
233 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
239 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
241 use rustc_data_structures::indexed_vec::Idx;
242 use rustc_data_structures::newtype_index;
246 DEBUG_FORMAT = "NodeId({})"
251 pub use node_id_inner::NodeId;
254 pub fn placeholder_from_expn_id(expn_id: ExpnId) -> Self {
255 NodeId::from_u32(expn_id.as_u32())
258 pub fn placeholder_to_expn_id(self) -> ExpnId {
259 ExpnId::from_u32(self.as_u32())
263 impl fmt::Display for NodeId {
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 fmt::Display::fmt(&self.as_u32(), f)
269 impl rustc_serialize::UseSpecializedEncodable for NodeId {
270 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
271 s.emit_u32(self.as_u32())
275 impl rustc_serialize::UseSpecializedDecodable for NodeId {
276 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
277 d.read_u32().map(NodeId::from_u32)
281 /// `NodeId` used to represent the root of the crate.
282 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
284 /// When parsing and doing expansions, we initially give all AST nodes this AST
285 /// node value. Then later, in the renumber pass, we renumber them to have
286 /// small, positive ids.
287 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
289 /// A modifier on a bound, currently this is only used for `?Sized`, where the
290 /// modifier is `Maybe`. Negative bounds should also be handled here.
291 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
292 pub enum TraitBoundModifier {
297 /// The AST represents all type param bounds as types.
298 /// `typeck::collect::compute_bounds` matches these against
299 /// the "special" built-in traits (see `middle::lang_items`) and
300 /// detects `Copy`, `Send` and `Sync`.
301 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
302 pub enum GenericBound {
303 Trait(PolyTraitRef, TraitBoundModifier),
308 pub fn span(&self) -> Span {
310 &GenericBound::Trait(ref t, ..) => t.span,
311 &GenericBound::Outlives(ref l) => l.ident.span,
316 pub type GenericBounds = Vec<GenericBound>;
318 /// Specifies the enforced ordering for generic parameters. In the future,
319 /// if we wanted to relax this order, we could override `PartialEq` and
320 /// `PartialOrd`, to allow the kinds to be unordered.
321 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
322 pub enum ParamKindOrd {
328 impl fmt::Display for ParamKindOrd {
329 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331 ParamKindOrd::Lifetime => "lifetime".fmt(f),
332 ParamKindOrd::Type => "type".fmt(f),
333 ParamKindOrd::Const => "const".fmt(f),
338 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
339 pub enum GenericParamKind {
340 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
342 Type { default: Option<P<Ty>> },
346 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
347 pub struct GenericParam {
350 pub attrs: ThinVec<Attribute>,
351 pub bounds: GenericBounds,
353 pub kind: GenericParamKind,
356 /// Represents lifetime, type and const parameters attached to a declaration of
357 /// a function, enum, trait, etc.
358 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
359 pub struct Generics {
360 pub params: Vec<GenericParam>,
361 pub where_clause: WhereClause,
365 impl Default for Generics {
366 /// Creates an instance of `Generics`.
367 fn default() -> Generics {
370 where_clause: WhereClause {
371 predicates: Vec::new(),
379 /// A where-clause in a definition.
380 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
381 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>,
888 /// An arm of a 'match'.
890 /// E.g., `0..=10 => { println!("match!") }` as in
894 /// 0..=10 => { println!("match!") },
895 /// _ => { println!("no match!") },
898 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
900 pub attrs: Vec<Attribute>,
901 pub pats: Vec<P<Pat>>,
902 pub guard: Option<P<Expr>>,
907 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
912 pub is_shorthand: bool,
913 pub attrs: ThinVec<Attribute>,
916 pub type SpannedIdent = Spanned<Ident>;
918 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
919 pub enum BlockCheckMode {
921 Unsafe(UnsafeSource),
924 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
925 pub enum UnsafeSource {
930 /// A constant (expression) that's not an item or associated item,
931 /// but needs its own `DefId` for type-checking, const-eval, etc.
932 /// These are usually found nested inside types (e.g., array lengths)
933 /// or expressions (e.g., repeat counts), and also used to define
934 /// explicit discriminant values for enum variants.
935 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
936 pub struct AnonConst {
942 #[derive(Clone, RustcEncodable, RustcDecodable)]
947 pub attrs: ThinVec<Attribute>,
950 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
951 #[cfg(target_arch = "x86_64")]
952 static_assert_size!(Expr, 96);
955 /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
957 pub fn returns(&self) -> bool {
958 if let ExprKind::Block(ref block, _) = self.node {
959 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
961 Some(&StmtKind::Expr(_)) => true,
962 Some(&StmtKind::Semi(ref expr)) => {
963 if let ExprKind::Ret(_) = expr.node {
964 // last statement is explicit return
970 // This is a block that doesn't end in either an implicit or explicit return
974 // This is not a block, it is a value
979 fn to_bound(&self) -> Option<GenericBound> {
981 ExprKind::Path(None, path) => Some(GenericBound::Trait(
982 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
983 TraitBoundModifier::None,
989 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
990 let node = match &self.node {
991 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
992 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
993 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
994 ExprKind::AddrOf(mutbl, expr) => expr
996 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
997 ExprKind::Repeat(expr, expr_len) => {
998 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1000 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1001 ExprKind::Tup(exprs) => {
1004 .map(|expr| expr.to_ty())
1005 .collect::<Option<Vec<_>>>()?;
1008 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1009 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1010 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1025 pub fn precedence(&self) -> ExprPrecedence {
1027 ExprKind::Box(_) => ExprPrecedence::Box,
1028 ExprKind::Array(_) => ExprPrecedence::Array,
1029 ExprKind::Call(..) => ExprPrecedence::Call,
1030 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1031 ExprKind::Tup(_) => ExprPrecedence::Tup,
1032 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1033 ExprKind::Unary(..) => ExprPrecedence::Unary,
1034 ExprKind::Lit(_) => ExprPrecedence::Lit,
1035 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1036 ExprKind::Let(..) => ExprPrecedence::Let,
1037 ExprKind::If(..) => ExprPrecedence::If,
1038 ExprKind::While(..) => ExprPrecedence::While,
1039 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1040 ExprKind::Loop(..) => ExprPrecedence::Loop,
1041 ExprKind::Match(..) => ExprPrecedence::Match,
1042 ExprKind::Closure(..) => ExprPrecedence::Closure,
1043 ExprKind::Block(..) => ExprPrecedence::Block,
1044 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1045 ExprKind::Async(..) => ExprPrecedence::Async,
1046 ExprKind::Await(..) => ExprPrecedence::Await,
1047 ExprKind::Assign(..) => ExprPrecedence::Assign,
1048 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1049 ExprKind::Field(..) => ExprPrecedence::Field,
1050 ExprKind::Index(..) => ExprPrecedence::Index,
1051 ExprKind::Range(..) => ExprPrecedence::Range,
1052 ExprKind::Path(..) => ExprPrecedence::Path,
1053 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1054 ExprKind::Break(..) => ExprPrecedence::Break,
1055 ExprKind::Continue(..) => ExprPrecedence::Continue,
1056 ExprKind::Ret(..) => ExprPrecedence::Ret,
1057 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1058 ExprKind::Mac(..) => ExprPrecedence::Mac,
1059 ExprKind::Struct(..) => ExprPrecedence::Struct,
1060 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1061 ExprKind::Paren(..) => ExprPrecedence::Paren,
1062 ExprKind::Try(..) => ExprPrecedence::Try,
1063 ExprKind::Yield(..) => ExprPrecedence::Yield,
1064 ExprKind::Err => ExprPrecedence::Err,
1069 impl fmt::Debug for Expr {
1070 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1071 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1075 /// Limit types of a range (inclusive or exclusive)
1076 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1077 pub enum RangeLimits {
1078 /// Inclusive at the beginning, exclusive at the end
1080 /// Inclusive at the beginning and end
1084 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1086 /// A `box x` expression.
1088 /// An array (`[a, b, c, d]`)
1089 Array(Vec<P<Expr>>),
1092 /// The first field resolves to the function itself,
1093 /// and the second field is the list of arguments.
1094 /// This also represents calling the constructor of
1095 /// tuple-like ADTs such as tuple structs and enum variants.
1096 Call(P<Expr>, Vec<P<Expr>>),
1097 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1099 /// The `PathSegment` represents the method name and its generic arguments
1100 /// (within the angle brackets).
1101 /// The first element of the vector of an `Expr` is the expression that evaluates
1102 /// to the object on which the method is being called on (the receiver),
1103 /// and the remaining elements are the rest of the arguments.
1104 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1105 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1106 MethodCall(PathSegment, Vec<P<Expr>>),
1107 /// A tuple (e.g., `(a, b, c, d)`).
1109 /// A binary operation (e.g., `a + b`, `a * b`).
1110 Binary(BinOp, P<Expr>, P<Expr>),
1111 /// A unary operation (e.g., `!x`, `*x`).
1112 Unary(UnOp, P<Expr>),
1113 /// A literal (e.g., `1`, `"foo"`).
1115 /// A cast (e.g., `foo as f64`).
1116 Cast(P<Expr>, P<Ty>),
1117 /// A type ascription (e.g., `42: usize`).
1118 Type(P<Expr>, P<Ty>),
1119 /// A `let pats = expr` expression that is only semantically allowed in the condition
1120 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1122 /// The `Vec<P<Pat>>` is for or-patterns at the top level.
1123 /// FIXME(54883): Change this to just `P<Pat>`.
1124 Let(Vec<P<Pat>>, P<Expr>),
1125 /// An `if` block, with an optional `else` block.
1127 /// `if expr { block } else { expr }`
1128 If(P<Expr>, P<Block>, Option<P<Expr>>),
1129 /// A while loop, with an optional label.
1131 /// `'label: while expr { block }`
1132 While(P<Expr>, P<Block>, Option<Label>),
1133 /// A `for` loop, with an optional label.
1135 /// `'label: for pat in expr { block }`
1137 /// This is desugared to a combination of `loop` and `match` expressions.
1138 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1139 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1141 /// `'label: loop { block }`
1142 Loop(P<Block>, Option<Label>),
1143 /// A `match` block.
1144 Match(P<Expr>, Vec<Arm>),
1145 /// A closure (e.g., `move |a, b, c| a + b + c`).
1147 /// The final span is the span of the argument block `|...|`.
1148 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1149 /// A block (`'label: { ... }`).
1150 Block(P<Block>, Option<Label>),
1151 /// An async block (`async move { ... }`).
1153 /// The `NodeId` is the `NodeId` for the closure that results from
1154 /// desugaring an async block, just like the NodeId field in the
1155 /// `IsAsync` enum. This is necessary in order to create a def for the
1156 /// closure which can be used as a parent of any child defs. Defs
1157 /// created during lowering cannot be made the parent of any other
1158 /// preexisting defs.
1159 Async(CaptureBy, NodeId, P<Block>),
1160 /// An await expression (`my_future.await`).
1161 Await(AwaitOrigin, P<Expr>),
1163 /// A try block (`try { ... }`).
1166 /// An assignment (`a = foo()`).
1167 Assign(P<Expr>, P<Expr>),
1168 /// An assignment with an operator.
1171 AssignOp(BinOp, P<Expr>, P<Expr>),
1172 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1173 Field(P<Expr>, Ident),
1174 /// An indexing operation (e.g., `foo[2]`).
1175 Index(P<Expr>, P<Expr>),
1176 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1177 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1179 /// Variable reference, possibly containing `::` and/or type
1180 /// parameters (e.g., `foo::bar::<baz>`).
1182 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1183 Path(Option<QSelf>, Path),
1185 /// A referencing operation (`&a` or `&mut a`).
1186 AddrOf(Mutability, P<Expr>),
1187 /// A `break`, with an optional label to break, and an optional expression.
1188 Break(Option<Label>, Option<P<Expr>>),
1189 /// A `continue`, with an optional label.
1190 Continue(Option<Label>),
1191 /// A `return`, with an optional value to be returned.
1192 Ret(Option<P<Expr>>),
1194 /// Output of the `asm!()` macro.
1195 InlineAsm(P<InlineAsm>),
1197 /// A macro invocation; pre-expansion.
1200 /// A struct literal expression.
1202 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1203 /// where `base` is the `Option<Expr>`.
1204 Struct(Path, Vec<Field>, Option<P<Expr>>),
1206 /// An array literal constructed from one repeated element.
1208 /// E.g., `[1; 5]`. The expression is the element to be
1209 /// repeated; the constant is the number of times to repeat it.
1210 Repeat(P<Expr>, AnonConst),
1212 /// No-op: used solely so we can pretty-print faithfully.
1215 /// A try expression (`expr?`).
1218 /// A `yield`, with an optional value to be yielded.
1219 Yield(Option<P<Expr>>),
1221 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1225 /// The explicit `Self` type in a "qualified path". The actual
1226 /// path, including the trait and the associated item, is stored
1227 /// separately. `position` represents the index of the associated
1228 /// item qualified with this `Self` type.
1230 /// ```ignore (only-for-syntax-highlight)
1231 /// <Vec<T> as a::b::Trait>::AssociatedItem
1232 /// ^~~~~ ~~~~~~~~~~~~~~^
1235 /// <Vec<T>>::AssociatedItem
1239 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1243 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1244 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1245 /// 0`, this is an empty span.
1246 pub path_span: Span,
1247 pub position: usize,
1250 /// A capture clause.
1251 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1252 pub enum CaptureBy {
1257 /// The movability of a generator / closure literal.
1258 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1259 pub enum Movability {
1264 /// Whether an `await` comes from `await!` or `.await` syntax.
1265 /// FIXME: this should be removed when support for legacy `await!` is removed.
1266 /// https://github.com/rust-lang/rust/issues/60610
1267 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1268 pub enum AwaitOrigin {
1273 pub type Mac = Spanned<Mac_>;
1275 /// Represents a macro invocation. The `Path` indicates which macro
1276 /// is being invoked, and the vector of token-trees contains the source
1277 /// of the macro invocation.
1279 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1280 /// stored in the enclosing item.
1281 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1284 pub delim: MacDelimiter,
1285 pub tts: TokenStream,
1288 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1289 pub enum MacDelimiter {
1296 pub fn stream(&self) -> TokenStream {
1302 crate fn to_token(self) -> DelimToken {
1304 MacDelimiter::Parenthesis => DelimToken::Paren,
1305 MacDelimiter::Bracket => DelimToken::Bracket,
1306 MacDelimiter::Brace => DelimToken::Brace,
1311 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1312 pub struct MacroDef {
1313 pub tokens: TokenStream,
1318 pub fn stream(&self) -> TokenStream {
1319 self.tokens.clone().into()
1323 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1325 /// A regular string, like `"foo"`.
1327 /// A raw string, like `r##"foo"##`.
1329 /// The value is the number of `#` symbols used.
1334 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1336 /// The original literal token as written in source code.
1337 pub token: token::Lit,
1338 /// The "semantic" representation of the literal lowered from the original tokens.
1339 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1340 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1345 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1346 pub enum LitIntType {
1354 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1355 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1357 /// A string literal (`"foo"`).
1358 Str(Symbol, StrStyle),
1359 /// A byte string (`b"foo"`).
1360 ByteStr(Lrc<Vec<u8>>),
1361 /// A byte char (`b'f'`).
1363 /// A character literal (`'a'`).
1365 /// An integer literal (`1`).
1366 Int(u128, LitIntType),
1367 /// A float literal (`1f64` or `1E10f64`).
1368 Float(Symbol, FloatTy),
1369 /// A float literal without a suffix (`1.0 or 1.0E10`).
1370 FloatUnsuffixed(Symbol),
1371 /// A boolean literal.
1373 /// Placeholder for a literal that wasn't well-formed in some way.
1378 /// Returns `true` if this literal is a string.
1379 pub fn is_str(&self) -> bool {
1381 LitKind::Str(..) => true,
1386 /// Returns `true` if this literal is byte literal string.
1387 pub fn is_bytestr(&self) -> bool {
1389 LitKind::ByteStr(_) => true,
1394 /// Returns `true` if this is a numeric literal.
1395 pub fn is_numeric(&self) -> bool {
1397 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1402 /// Returns `true` if this literal has no suffix.
1403 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1404 pub fn is_unsuffixed(&self) -> bool {
1406 // unsuffixed variants
1408 | LitKind::ByteStr(..)
1411 | LitKind::Int(_, LitIntType::Unsuffixed)
1412 | LitKind::FloatUnsuffixed(..)
1414 | LitKind::Err(..) => true,
1415 // suffixed variants
1416 LitKind::Int(_, LitIntType::Signed(..))
1417 | LitKind::Int(_, LitIntType::Unsigned(..))
1418 | LitKind::Float(..) => false,
1422 /// Returns `true` if this literal has a suffix.
1423 pub fn is_suffixed(&self) -> bool {
1424 !self.is_unsuffixed()
1428 // N.B., If you change this, you'll probably want to change the corresponding
1429 // type structure in `middle/ty.rs` as well.
1430 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1433 pub mutbl: Mutability,
1436 /// Represents a method's signature in a trait declaration,
1437 /// or in an implementation.
1438 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1439 pub struct MethodSig {
1440 pub header: FnHeader,
1441 pub decl: P<FnDecl>,
1444 /// Represents an item declaration within a trait declaration,
1445 /// possibly including a default implementation. A trait item is
1446 /// either required (meaning it doesn't have an implementation, just a
1447 /// signature) or provided (meaning it has a default implementation).
1448 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1449 pub struct TraitItem {
1452 pub attrs: Vec<Attribute>,
1453 pub generics: Generics,
1454 pub node: TraitItemKind,
1456 /// See `Item::tokens` for what this is.
1457 pub tokens: Option<TokenStream>,
1460 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1461 pub enum TraitItemKind {
1462 Const(P<Ty>, Option<P<Expr>>),
1463 Method(MethodSig, Option<P<Block>>),
1464 Type(GenericBounds, Option<P<Ty>>),
1468 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1469 pub struct ImplItem {
1472 pub vis: Visibility,
1473 pub defaultness: Defaultness,
1474 pub attrs: Vec<Attribute>,
1475 pub generics: Generics,
1476 pub node: ImplItemKind,
1478 /// See `Item::tokens` for what this is.
1479 pub tokens: Option<TokenStream>,
1482 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1483 pub enum ImplItemKind {
1484 Const(P<Ty>, P<Expr>),
1485 Method(MethodSig, P<Block>),
1487 Existential(GenericBounds),
1491 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1501 impl fmt::Debug for IntTy {
1502 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1503 fmt::Display::fmt(self, f)
1507 impl fmt::Display for IntTy {
1508 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1509 write!(f, "{}", self.ty_to_string())
1514 pub fn ty_to_string(&self) -> &'static str {
1516 IntTy::Isize => "isize",
1518 IntTy::I16 => "i16",
1519 IntTy::I32 => "i32",
1520 IntTy::I64 => "i64",
1521 IntTy::I128 => "i128",
1525 pub fn to_symbol(&self) -> Symbol {
1527 IntTy::Isize => sym::isize,
1528 IntTy::I8 => sym::i8,
1529 IntTy::I16 => sym::i16,
1530 IntTy::I32 => sym::i32,
1531 IntTy::I64 => sym::i64,
1532 IntTy::I128 => sym::i128,
1536 pub fn val_to_string(&self, val: i128) -> String {
1537 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1538 // are parsed as `u128`, so we wouldn't want to print an extra negative
1540 format!("{}{}", val as u128, self.ty_to_string())
1543 pub fn bit_width(&self) -> Option<usize> {
1545 IntTy::Isize => return None,
1555 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1566 pub fn ty_to_string(&self) -> &'static str {
1568 UintTy::Usize => "usize",
1570 UintTy::U16 => "u16",
1571 UintTy::U32 => "u32",
1572 UintTy::U64 => "u64",
1573 UintTy::U128 => "u128",
1577 pub fn to_symbol(&self) -> Symbol {
1579 UintTy::Usize => sym::usize,
1580 UintTy::U8 => sym::u8,
1581 UintTy::U16 => sym::u16,
1582 UintTy::U32 => sym::u32,
1583 UintTy::U64 => sym::u64,
1584 UintTy::U128 => sym::u128,
1588 pub fn val_to_string(&self, val: u128) -> String {
1589 format!("{}{}", val, self.ty_to_string())
1592 pub fn bit_width(&self) -> Option<usize> {
1594 UintTy::Usize => return None,
1599 UintTy::U128 => 128,
1604 impl fmt::Debug for UintTy {
1605 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1606 fmt::Display::fmt(self, f)
1610 impl fmt::Display for UintTy {
1611 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1612 write!(f, "{}", self.ty_to_string())
1616 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1617 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1618 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1619 pub struct AssocTyConstraint {
1622 pub kind: AssocTyConstraintKind,
1626 /// The kinds of an `AssocTyConstraint`.
1627 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1628 pub enum AssocTyConstraintKind {
1629 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1633 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1635 bounds: GenericBounds,
1639 #[derive(Clone, RustcEncodable, RustcDecodable)]
1646 impl fmt::Debug for Ty {
1647 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1648 write!(f, "type({})", pprust::ty_to_string(self))
1652 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1653 pub struct BareFnTy {
1654 pub unsafety: Unsafety,
1656 pub generic_params: Vec<GenericParam>,
1657 pub decl: P<FnDecl>,
1660 /// The various kinds of type recognized by the compiler.
1661 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1663 /// A variable-length slice (`[T]`).
1665 /// A fixed length array (`[T; n]`).
1666 Array(P<Ty>, AnonConst),
1667 /// A raw pointer (`*const T` or `*mut T`).
1669 /// A reference (`&'a T` or `&'a mut T`).
1670 Rptr(Option<Lifetime>, MutTy),
1671 /// A bare function (e.g., `fn(usize) -> bool`).
1672 BareFn(P<BareFnTy>),
1673 /// The never type (`!`).
1675 /// A tuple (`(A, B, C, D,...)`).
1677 /// A path (`module::module::...::Type`), optionally
1678 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1680 /// Type parameters are stored in the `Path` itself.
1681 Path(Option<QSelf>, Path),
1682 /// A trait object type `Bound1 + Bound2 + Bound3`
1683 /// where `Bound` is a trait or a lifetime.
1684 TraitObject(GenericBounds, TraitObjectSyntax),
1685 /// An `impl Bound1 + Bound2 + Bound3` type
1686 /// where `Bound` is a trait or a lifetime.
1688 /// The `NodeId` exists to prevent lowering from having to
1689 /// generate `NodeId`s on the fly, which would complicate
1690 /// the generation of `existential type` items significantly.
1691 ImplTrait(NodeId, GenericBounds),
1692 /// No-op; kept solely so that we can pretty-print faithfully.
1696 /// This means the type should be inferred instead of it having been
1697 /// specified. This can appear anywhere in a type.
1699 /// Inferred type of a `self` or `&self` argument in a method.
1701 /// A macro in the type position.
1703 /// Placeholder for a kind that has failed to be defined.
1705 /// Placeholder for a `va_list`.
1710 pub fn is_implicit_self(&self) -> bool {
1711 if let TyKind::ImplicitSelf = *self {
1718 pub fn is_unit(&self) -> bool {
1719 if let TyKind::Tup(ref tys) = *self {
1727 /// Syntax used to declare a trait object.
1728 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1729 pub enum TraitObjectSyntax {
1734 /// Inline assembly dialect.
1736 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1737 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1738 pub enum AsmDialect {
1743 /// Inline assembly.
1745 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1746 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1747 pub struct InlineAsmOutput {
1748 pub constraint: Symbol,
1751 pub is_indirect: bool,
1754 /// Inline assembly.
1756 /// E.g., `asm!("NOP");`.
1757 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1758 pub struct InlineAsm {
1760 pub asm_str_style: StrStyle,
1761 pub outputs: Vec<InlineAsmOutput>,
1762 pub inputs: Vec<(Symbol, P<Expr>)>,
1763 pub clobbers: Vec<Symbol>,
1765 pub alignstack: bool,
1766 pub dialect: AsmDialect,
1767 pub ctxt: SyntaxContext,
1770 /// An argument in a function header.
1772 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1773 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1775 pub attrs: ThinVec<Attribute>,
1781 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1783 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1784 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1786 /// `self`, `mut self`
1788 /// `&'lt self`, `&'lt mut self`
1789 Region(Option<Lifetime>, Mutability),
1790 /// `self: TYPE`, `mut self: TYPE`
1791 Explicit(P<Ty>, Mutability),
1794 pub type ExplicitSelf = Spanned<SelfKind>;
1797 pub fn to_self(&self) -> Option<ExplicitSelf> {
1798 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1799 if ident.name == kw::SelfLower {
1800 return match self.ty.node {
1801 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1802 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1803 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1806 self.pat.span.to(self.ty.span),
1807 SelfKind::Explicit(self.ty.clone(), mutbl),
1815 pub fn is_self(&self) -> bool {
1816 if let PatKind::Ident(_, ident, _) = self.pat.node {
1817 ident.name == kw::SelfLower
1823 pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1824 let span = eself.span.to(eself_ident.span);
1825 let infer_ty = P(Ty {
1827 node: TyKind::ImplicitSelf,
1830 let arg = |mutbl, ty| Arg {
1834 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1841 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1842 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1843 SelfKind::Region(lt, mutbl) => arg(
1844 Mutability::Immutable,
1861 /// A header (not the body) of a function declaration.
1863 /// E.g., `fn foo(bar: baz)`.
1864 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1866 pub inputs: Vec<Arg>,
1867 pub output: FunctionRetTy,
1868 pub c_variadic: bool,
1872 pub fn get_self(&self) -> Option<ExplicitSelf> {
1873 self.inputs.get(0).and_then(Arg::to_self)
1875 pub fn has_self(&self) -> bool {
1876 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1880 /// Is the trait definition an auto trait?
1881 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1887 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1893 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1897 return_impl_trait_id: NodeId,
1903 pub fn is_async(self) -> bool {
1904 if let IsAsync::Async { .. } = self {
1911 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1912 pub fn opt_return_id(self) -> Option<NodeId> {
1915 return_impl_trait_id,
1917 } => Some(return_impl_trait_id),
1918 IsAsync::NotAsync => None,
1923 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1924 pub enum Constness {
1929 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1930 pub enum Defaultness {
1935 impl fmt::Display for Unsafety {
1936 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1939 Unsafety::Normal => "normal",
1940 Unsafety::Unsafe => "unsafe",
1947 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1948 pub enum ImplPolarity {
1949 /// `impl Trait for Type`
1951 /// `impl !Trait for Type`
1955 impl fmt::Debug for ImplPolarity {
1956 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1958 ImplPolarity::Positive => "positive".fmt(f),
1959 ImplPolarity::Negative => "negative".fmt(f),
1964 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1965 pub enum FunctionRetTy {
1966 /// Returns type is not specified.
1968 /// Functions default to `()` and closures default to inference.
1969 /// Span points to where return type would be inserted.
1971 /// Everything else.
1975 impl FunctionRetTy {
1976 pub fn span(&self) -> Span {
1978 FunctionRetTy::Default(span) => span,
1979 FunctionRetTy::Ty(ref ty) => ty.span,
1984 /// Module declaration.
1986 /// E.g., `mod foo;` or `mod foo { .. }`.
1987 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1989 /// A span from the first token past `{` to the last token until `}`.
1990 /// For `mod foo;`, the inner span ranges from the first token
1991 /// to the last token in the external file.
1993 pub items: Vec<P<Item>>,
1994 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
1998 /// Foreign module declaration.
2000 /// E.g., `extern { .. }` or `extern C { .. }`.
2001 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2002 pub struct ForeignMod {
2004 pub items: Vec<ForeignItem>,
2007 /// Global inline assembly.
2009 /// Also known as "module-level assembly" or "file-scoped assembly".
2010 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2011 pub struct GlobalAsm {
2013 pub ctxt: SyntaxContext,
2016 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2017 pub struct EnumDef {
2018 pub variants: Vec<Variant>,
2021 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2022 pub struct Variant_ {
2023 /// Name of the variant.
2025 /// Attributes of the variant.
2026 pub attrs: Vec<Attribute>,
2027 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2029 /// Fields and constructor id of the variant.
2030 pub data: VariantData,
2031 /// Explicit discriminant, e.g., `Foo = 1`.
2032 pub disr_expr: Option<AnonConst>,
2035 pub type Variant = Spanned<Variant_>;
2037 /// Part of `use` item to the right of its prefix.
2038 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2039 pub enum UseTreeKind {
2040 /// `use prefix` or `use prefix as rename`
2042 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2044 Simple(Option<Ident>, NodeId, NodeId),
2045 /// `use prefix::{...}`
2046 Nested(Vec<(UseTree, NodeId)>),
2051 /// A tree of paths sharing common prefixes.
2052 /// Used in `use` items both at top-level and inside of braces in import groups.
2053 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2054 pub struct UseTree {
2056 pub kind: UseTreeKind,
2061 pub fn ident(&self) -> Ident {
2063 UseTreeKind::Simple(Some(rename), ..) => rename,
2064 UseTreeKind::Simple(None, ..) => {
2068 .expect("empty prefix in a simple import")
2071 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2076 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2077 /// are contained as statements within items. These two cases need to be
2078 /// distinguished for pretty-printing.
2079 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
2080 pub enum AttrStyle {
2086 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
2088 pub struct AttrId(pub usize);
2090 impl Idx for AttrId {
2091 fn new(idx: usize) -> Self {
2094 fn index(self) -> usize {
2099 /// Metadata associated with an item.
2100 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
2101 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2102 pub struct Attribute {
2104 pub style: AttrStyle,
2106 pub tokens: TokenStream,
2107 pub is_sugared_doc: bool,
2111 /// `TraitRef`s appear in impls.
2113 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2114 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2115 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2116 /// same as the impl's `NodeId`).
2117 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2118 pub struct TraitRef {
2123 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2124 pub struct PolyTraitRef {
2125 /// The `'a` in `<'a> Foo<&'a T>`.
2126 pub bound_generic_params: Vec<GenericParam>,
2128 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2129 pub trait_ref: TraitRef,
2135 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2137 bound_generic_params: generic_params,
2138 trait_ref: TraitRef {
2140 ref_id: DUMMY_NODE_ID,
2147 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2148 pub enum CrateSugar {
2149 /// Source is `pub(crate)`.
2152 /// Source is (just) `crate`.
2156 pub type Visibility = Spanned<VisibilityKind>;
2158 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2159 pub enum VisibilityKind {
2162 Restricted { path: P<Path>, id: NodeId },
2166 impl VisibilityKind {
2167 pub fn is_pub(&self) -> bool {
2168 if let VisibilityKind::Public = *self {
2176 /// Field of a struct.
2178 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2179 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2180 pub struct StructField {
2182 pub ident: Option<Ident>,
2183 pub vis: Visibility,
2186 pub attrs: Vec<Attribute>,
2189 /// Fields and constructor ids of enum variants and structs.
2190 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2191 pub enum VariantData {
2194 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2195 Struct(Vec<StructField>, bool),
2198 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2199 Tuple(Vec<StructField>, NodeId),
2202 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2207 /// Return the fields of this variant.
2208 pub fn fields(&self) -> &[StructField] {
2210 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2215 /// Return the `NodeId` of this variant's constructor, if it has one.
2216 pub fn ctor_id(&self) -> Option<NodeId> {
2218 VariantData::Struct(..) => None,
2219 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2226 /// The name might be a dummy name in case of anonymous items.
2227 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2230 pub attrs: Vec<Attribute>,
2233 pub vis: Visibility,
2236 /// Original tokens this item was parsed from. This isn't necessarily
2237 /// available for all items, although over time more and more items should
2238 /// have this be `Some`. Right now this is primarily used for procedural
2239 /// macros, notably custom attributes.
2241 /// Note that the tokens here do not include the outer attributes, but will
2242 /// include inner attributes.
2243 pub tokens: Option<TokenStream>,
2247 /// Return the span that encompasses the attributes.
2248 pub fn span_with_attributes(&self) -> Span {
2249 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2253 /// A function header.
2255 /// All the information between the visibility and the name of the function is
2256 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2257 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2258 pub struct FnHeader {
2259 pub unsafety: Unsafety,
2260 pub asyncness: Spanned<IsAsync>,
2261 pub constness: Spanned<Constness>,
2265 impl Default for FnHeader {
2266 fn default() -> FnHeader {
2268 unsafety: Unsafety::Normal,
2269 asyncness: dummy_spanned(IsAsync::NotAsync),
2270 constness: dummy_spanned(Constness::NotConst),
2276 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2278 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2280 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2281 ExternCrate(Option<Name>),
2282 /// A use declaration (`use` or `pub use`) item.
2284 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2286 /// A static item (`static` or `pub static`).
2288 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2289 Static(P<Ty>, Mutability, P<Expr>),
2290 /// A constant item (`const` or `pub const`).
2292 /// E.g., `const FOO: i32 = 42;`.
2293 Const(P<Ty>, P<Expr>),
2294 /// A function declaration (`fn` or `pub fn`).
2296 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2297 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2298 /// A module declaration (`mod` or `pub mod`).
2300 /// E.g., `mod foo;` or `mod foo { .. }`.
2302 /// An external module (`extern` or `pub extern`).
2304 /// E.g., `extern {}` or `extern "C" {}`.
2305 ForeignMod(ForeignMod),
2306 /// Module-level inline assembly (from `global_asm!()`).
2307 GlobalAsm(P<GlobalAsm>),
2308 /// A type alias (`type` or `pub type`).
2310 /// E.g., `type Foo = Bar<u8>;`.
2311 Ty(P<Ty>, Generics),
2312 /// An existential type declaration (`existential type`).
2314 /// E.g., `existential type Foo: Bar + Boo;`.
2315 Existential(GenericBounds, Generics),
2316 /// An enum definition (`enum` or `pub enum`).
2318 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2319 Enum(EnumDef, Generics),
2320 /// A struct definition (`struct` or `pub struct`).
2322 /// E.g., `struct Foo<A> { x: A }`.
2323 Struct(VariantData, Generics),
2324 /// A union definition (`union` or `pub union`).
2326 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2327 Union(VariantData, Generics),
2328 /// A Trait declaration (`trait` or `pub trait`).
2330 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2331 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2334 /// E.g., `trait Foo = Bar + Quux;`.
2335 TraitAlias(Generics, GenericBounds),
2336 /// An implementation.
2338 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2344 Option<TraitRef>, // (optional) trait this impl implements
2348 /// A macro invocation.
2350 /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2353 /// A macro definition.
2358 pub fn descriptive_variant(&self) -> &str {
2360 ItemKind::ExternCrate(..) => "extern crate",
2361 ItemKind::Use(..) => "use",
2362 ItemKind::Static(..) => "static item",
2363 ItemKind::Const(..) => "constant item",
2364 ItemKind::Fn(..) => "function",
2365 ItemKind::Mod(..) => "module",
2366 ItemKind::ForeignMod(..) => "foreign module",
2367 ItemKind::GlobalAsm(..) => "global asm",
2368 ItemKind::Ty(..) => "type alias",
2369 ItemKind::Existential(..) => "existential type",
2370 ItemKind::Enum(..) => "enum",
2371 ItemKind::Struct(..) => "struct",
2372 ItemKind::Union(..) => "union",
2373 ItemKind::Trait(..) => "trait",
2374 ItemKind::TraitAlias(..) => "trait alias",
2375 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2380 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2381 pub struct ForeignItem {
2383 pub attrs: Vec<Attribute>,
2384 pub node: ForeignItemKind,
2387 pub vis: Visibility,
2390 /// An item within an `extern` block.
2391 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2392 pub enum ForeignItemKind {
2393 /// A foreign function.
2394 Fn(P<FnDecl>, Generics),
2395 /// A foreign static item (`static ext: u8`).
2396 Static(P<Ty>, Mutability),
2399 /// A macro invocation.
2403 impl ForeignItemKind {
2404 pub fn descriptive_variant(&self) -> &str {
2406 ForeignItemKind::Fn(..) => "foreign function",
2407 ForeignItemKind::Static(..) => "foreign static item",
2408 ForeignItemKind::Ty => "foreign type",
2409 ForeignItemKind::Macro(..) => "macro in foreign module",
2418 // Are ASTs encodable?
2420 fn check_asts_encodable() {
2421 fn assert_encodable<T: rustc_serialize::Encodable>() {}
2422 assert_encodable::<Crate>();