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 /// Bindings (equality constraints) on associated types, if present.
194 /// E.g., `Foo<A = Bar>`.
195 pub bindings: Vec<TypeBinding>,
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 {
366 predicates: Vec::new(),
374 /// A where-clause in a definition.
375 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
376 pub struct WhereClause {
378 pub predicates: Vec<WherePredicate>,
382 /// A single predicate in a where-clause.
383 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
384 pub enum WherePredicate {
385 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
386 BoundPredicate(WhereBoundPredicate),
387 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
388 RegionPredicate(WhereRegionPredicate),
389 /// An equality predicate (unsupported).
390 EqPredicate(WhereEqPredicate),
393 impl WherePredicate {
394 pub fn span(&self) -> Span {
396 &WherePredicate::BoundPredicate(ref p) => p.span,
397 &WherePredicate::RegionPredicate(ref p) => p.span,
398 &WherePredicate::EqPredicate(ref p) => p.span,
405 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
406 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
407 pub struct WhereBoundPredicate {
409 /// Any generics from a `for` binding
410 pub bound_generic_params: Vec<GenericParam>,
411 /// The type being bounded
412 pub bounded_ty: P<Ty>,
413 /// Trait and lifetime bounds (`Clone+Send+'static`)
414 pub bounds: GenericBounds,
417 /// A lifetime predicate.
419 /// E.g., `'a: 'b + 'c`.
420 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
421 pub struct WhereRegionPredicate {
423 pub lifetime: Lifetime,
424 pub bounds: GenericBounds,
427 /// An equality predicate (unsupported).
430 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
431 pub struct WhereEqPredicate {
438 /// The set of `MetaItem`s that define the compilation environment of the crate,
439 /// used to drive conditional compilation.
440 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
442 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
445 pub attrs: Vec<Attribute>,
449 /// Possible values inside of compile-time attribute lists.
451 /// E.g., the '..' in `#[name(..)]`.
452 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
453 pub enum NestedMetaItem {
454 /// A full MetaItem, for recursive meta items.
458 /// E.g., `"foo"`, `64`, `true`.
462 /// A spanned compile-time attribute item.
464 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
465 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
466 pub struct MetaItem {
468 pub node: MetaItemKind,
472 /// A compile-time attribute item.
474 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
475 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
476 pub enum MetaItemKind {
479 /// E.g., `test` as in `#[test]`.
483 /// E.g., `derive(..)` as in `#[derive(..)]`.
484 List(Vec<NestedMetaItem>),
485 /// Name value meta item.
487 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
491 /// A Block (`{ .. }`).
493 /// E.g., `{ .. }` as in `fn foo() { .. }`.
494 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
496 /// Statements in a block
497 pub stmts: Vec<Stmt>,
499 /// Distinguishes between `unsafe { ... }` and `{ ... }`
500 pub rules: BlockCheckMode,
504 #[derive(Clone, RustcEncodable, RustcDecodable)]
511 impl fmt::Debug for Pat {
512 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
518 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
519 let node = match &self.node {
520 PatKind::Wild => TyKind::Infer,
521 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
522 TyKind::Path(None, Path::from_ident(*ident))
524 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
525 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
526 PatKind::Ref(pat, mutbl) => pat
528 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
529 PatKind::Slice(pats, None, _) if pats.len() == 1 => {
530 pats[0].to_ty().map(TyKind::Slice)?
532 PatKind::Tuple(pats, None) => {
533 let mut tys = Vec::with_capacity(pats.len());
534 // FIXME(#48994) - could just be collected into an Option<Vec>
536 tys.push(pat.to_ty()?);
550 pub fn walk<F>(&self, it: &mut F) -> bool
552 F: FnMut(&Pat) -> bool,
559 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
560 PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
561 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
562 s.iter().all(|p| p.walk(it))
564 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
565 PatKind::Slice(ref before, ref slice, ref after) => {
566 before.iter().all(|p| p.walk(it))
567 && slice.iter().all(|p| p.walk(it))
568 && after.iter().all(|p| p.walk(it))
575 | PatKind::Mac(_) => true,
580 /// A single field in a struct pattern
582 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
583 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
584 /// except is_shorthand is true
585 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
586 pub struct FieldPat {
587 /// The identifier for the field
589 /// The pattern the field is destructured to
591 pub is_shorthand: bool,
592 pub attrs: ThinVec<Attribute>,
595 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
596 pub enum BindingMode {
601 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
603 Included(RangeSyntax),
607 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
608 pub enum RangeSyntax {
613 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
615 /// Represents a wildcard pattern (`_`).
618 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
619 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
620 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
621 /// during name resolution.
622 Ident(BindingMode, Ident, Option<P<Pat>>),
624 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
625 /// The `bool` is `true` in the presence of a `..`.
626 Struct(Path, Vec<Spanned<FieldPat>>, /* recovered */ bool),
628 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
629 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
630 /// `0 <= position <= subpats.len()`.
631 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
633 /// A possibly qualified path pattern.
634 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
635 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
636 /// only legally refer to associated constants.
637 Path(Option<QSelf>, Path),
639 /// A tuple pattern (`(a, b)`).
640 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
641 /// `0 <= position <= subpats.len()`.
642 Tuple(Vec<P<Pat>>, Option<usize>),
647 /// A reference pattern (e.g., `&mut (a, b)`).
648 Ref(P<Pat>, Mutability),
653 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
654 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
656 /// `[a, b, ..i, y, z]` is represented as:
657 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
658 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
660 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
663 /// A macro pattern; pre-expansion.
668 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
670 pub enum Mutability {
675 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
677 /// The `+` operator (addition)
679 /// The `-` operator (subtraction)
681 /// The `*` operator (multiplication)
683 /// The `/` operator (division)
685 /// The `%` operator (modulus)
687 /// The `&&` operator (logical and)
689 /// The `||` operator (logical or)
691 /// The `^` operator (bitwise xor)
693 /// The `&` operator (bitwise and)
695 /// The `|` operator (bitwise or)
697 /// The `<<` operator (shift left)
699 /// The `>>` operator (shift right)
701 /// The `==` operator (equality)
703 /// The `<` operator (less than)
705 /// The `<=` operator (less than or equal to)
707 /// The `!=` operator (not equal to)
709 /// The `>=` operator (greater than or equal to)
711 /// The `>` operator (greater than)
716 pub fn to_string(&self) -> &'static str {
739 pub fn lazy(&self) -> bool {
741 BinOpKind::And | BinOpKind::Or => true,
746 pub fn is_shift(&self) -> bool {
748 BinOpKind::Shl | BinOpKind::Shr => true,
753 pub fn is_comparison(&self) -> bool {
756 Eq | Lt | Le | Ne | Gt | Ge => true,
757 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
761 /// Returns `true` if the binary operator takes its arguments by value
762 pub fn is_by_value(&self) -> bool {
763 !self.is_comparison()
767 pub type BinOp = Spanned<BinOpKind>;
769 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
771 /// The `*` operator for dereferencing
773 /// The `!` operator for logical inversion
775 /// The `-` operator for negation
780 /// Returns `true` if the unary operator takes its argument by value
781 pub fn is_by_value(u: UnOp) -> bool {
783 UnOp::Neg | UnOp::Not => true,
788 pub fn to_string(op: UnOp) -> &'static str {
798 #[derive(Clone, RustcEncodable, RustcDecodable)]
806 pub fn add_trailing_semicolon(mut self) -> Self {
807 self.node = match self.node {
808 StmtKind::Expr(expr) => StmtKind::Semi(expr),
809 StmtKind::Mac(mac) => {
810 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
817 pub fn is_item(&self) -> bool {
819 StmtKind::Item(_) => true,
824 pub fn is_expr(&self) -> bool {
826 StmtKind::Expr(_) => true,
832 impl fmt::Debug for Stmt {
833 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838 pprust::stmt_to_string(self)
843 #[derive(Clone, RustcEncodable, RustcDecodable)]
845 /// A local (let) binding.
848 /// An item definition.
851 /// Expr without trailing semi-colon.
853 /// Expr with a trailing semi-colon.
856 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
859 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
860 pub enum MacStmtStyle {
861 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
862 /// `foo!(...);`, `foo![...];`).
864 /// The macro statement had braces (e.g., `foo! { ... }`).
866 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
867 /// `foo!(...)`). All of these will end up being converted into macro
872 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
873 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
876 pub ty: Option<P<Ty>>,
877 /// Initializer expression to set the value, if any.
878 pub init: Option<P<Expr>>,
881 pub attrs: ThinVec<Attribute>,
882 /// Origin of this local variable.
883 pub source: LocalSource,
886 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
887 pub enum LocalSource {
888 /// Local was parsed from source.
890 /// Within `ast::IsAsync::Async`, a local is generated that will contain the moved arguments
891 /// of an `async fn`.
895 /// An arm of a 'match'.
897 /// E.g., `0..=10 => { println!("match!") }` as in
901 /// 0..=10 => { println!("match!") },
902 /// _ => { println!("no match!") },
905 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
907 pub attrs: Vec<Attribute>,
908 pub pats: Vec<P<Pat>>,
909 pub guard: Option<Guard>,
914 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
919 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
924 pub is_shorthand: bool,
925 pub attrs: ThinVec<Attribute>,
928 pub type SpannedIdent = Spanned<Ident>;
930 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
931 pub enum BlockCheckMode {
933 Unsafe(UnsafeSource),
936 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
937 pub enum UnsafeSource {
942 /// A constant (expression) that's not an item or associated item,
943 /// but needs its own `DefId` for type-checking, const-eval, etc.
944 /// These are usually found nested inside types (e.g., array lengths)
945 /// or expressions (e.g., repeat counts), and also used to define
946 /// explicit discriminant values for enum variants.
947 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
948 pub struct AnonConst {
954 #[derive(Clone, RustcEncodable, RustcDecodable)]
959 pub attrs: ThinVec<Attribute>,
962 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
963 #[cfg(target_arch = "x86_64")]
964 static_assert_size!(Expr, 96);
967 /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
969 pub fn returns(&self) -> bool {
970 if let ExprKind::Block(ref block, _) = self.node {
971 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
973 Some(&StmtKind::Expr(_)) => true,
974 Some(&StmtKind::Semi(ref expr)) => {
975 if let ExprKind::Ret(_) = expr.node {
976 // last statement is explicit return
982 // This is a block that doesn't end in either an implicit or explicit return
986 // This is not a block, it is a value
991 fn to_bound(&self) -> Option<GenericBound> {
993 ExprKind::Path(None, path) => Some(GenericBound::Trait(
994 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
995 TraitBoundModifier::None,
1001 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
1002 let node = match &self.node {
1003 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1004 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1005 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1006 ExprKind::AddrOf(mutbl, expr) => expr
1008 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
1009 ExprKind::Repeat(expr, expr_len) => {
1010 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1012 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1013 ExprKind::Tup(exprs) => {
1016 .map(|expr| expr.to_ty())
1017 .collect::<Option<Vec<_>>>()?;
1020 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1021 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1022 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1037 pub fn precedence(&self) -> ExprPrecedence {
1039 ExprKind::Box(_) => ExprPrecedence::Box,
1040 ExprKind::Array(_) => ExprPrecedence::Array,
1041 ExprKind::Call(..) => ExprPrecedence::Call,
1042 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1043 ExprKind::Tup(_) => ExprPrecedence::Tup,
1044 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1045 ExprKind::Unary(..) => ExprPrecedence::Unary,
1046 ExprKind::Lit(_) => ExprPrecedence::Lit,
1047 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1048 ExprKind::If(..) => ExprPrecedence::If,
1049 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
1050 ExprKind::While(..) => ExprPrecedence::While,
1051 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
1052 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1053 ExprKind::Loop(..) => ExprPrecedence::Loop,
1054 ExprKind::Match(..) => ExprPrecedence::Match,
1055 ExprKind::Closure(..) => ExprPrecedence::Closure,
1056 ExprKind::Block(..) => ExprPrecedence::Block,
1057 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1058 ExprKind::Async(..) => ExprPrecedence::Async,
1059 ExprKind::Await(..) => ExprPrecedence::Await,
1060 ExprKind::Assign(..) => ExprPrecedence::Assign,
1061 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1062 ExprKind::Field(..) => ExprPrecedence::Field,
1063 ExprKind::Index(..) => ExprPrecedence::Index,
1064 ExprKind::Range(..) => ExprPrecedence::Range,
1065 ExprKind::Path(..) => ExprPrecedence::Path,
1066 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1067 ExprKind::Break(..) => ExprPrecedence::Break,
1068 ExprKind::Continue(..) => ExprPrecedence::Continue,
1069 ExprKind::Ret(..) => ExprPrecedence::Ret,
1070 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1071 ExprKind::Mac(..) => ExprPrecedence::Mac,
1072 ExprKind::Struct(..) => ExprPrecedence::Struct,
1073 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1074 ExprKind::Paren(..) => ExprPrecedence::Paren,
1075 ExprKind::Try(..) => ExprPrecedence::Try,
1076 ExprKind::Yield(..) => ExprPrecedence::Yield,
1077 ExprKind::Err => ExprPrecedence::Err,
1082 impl fmt::Debug for Expr {
1083 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1084 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1088 /// Limit types of a range (inclusive or exclusive)
1089 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1090 pub enum RangeLimits {
1091 /// Inclusive at the beginning, exclusive at the end
1093 /// Inclusive at the beginning and end
1097 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1099 /// A `box x` expression.
1101 /// An array (`[a, b, c, d]`)
1102 Array(Vec<P<Expr>>),
1105 /// The first field resolves to the function itself,
1106 /// and the second field is the list of arguments.
1107 /// This also represents calling the constructor of
1108 /// tuple-like ADTs such as tuple structs and enum variants.
1109 Call(P<Expr>, Vec<P<Expr>>),
1110 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1112 /// The `PathSegment` represents the method name and its generic arguments
1113 /// (within the angle brackets).
1114 /// The first element of the vector of an `Expr` is the expression that evaluates
1115 /// to the object on which the method is being called on (the receiver),
1116 /// and the remaining elements are the rest of the arguments.
1117 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1118 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1119 MethodCall(PathSegment, Vec<P<Expr>>),
1120 /// A tuple (e.g., `(a, b, c, d)`).
1122 /// A binary operation (e.g., `a + b`, `a * b`).
1123 Binary(BinOp, P<Expr>, P<Expr>),
1124 /// A unary operation (e.g., `!x`, `*x`).
1125 Unary(UnOp, P<Expr>),
1126 /// A literal (e.g., `1`, `"foo"`).
1128 /// A cast (e.g., `foo as f64`).
1129 Cast(P<Expr>, P<Ty>),
1130 /// A type ascription (e.g., `42: usize`).
1131 Type(P<Expr>, P<Ty>),
1132 /// An `if` block, with an optional `else` block.
1134 /// `if expr { block } else { expr }`
1135 If(P<Expr>, P<Block>, Option<P<Expr>>),
1136 /// An `if let` expression with an optional else block
1138 /// `if let pat = expr { block } else { expr }`
1140 /// This is desugared to a `match` expression.
1141 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1142 /// A while loop, with an optional label
1144 /// `'label: while expr { block }`
1145 While(P<Expr>, P<Block>, Option<Label>),
1146 /// A `while let` loop, with an optional label.
1148 /// `'label: while let pat = expr { block }`
1150 /// This is desugared to a combination of `loop` and `match` expressions.
1151 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1152 /// A `for` loop, with an optional label.
1154 /// `'label: for pat in expr { block }`
1156 /// This is desugared to a combination of `loop` and `match` expressions.
1157 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1158 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1160 /// `'label: loop { block }`
1161 Loop(P<Block>, Option<Label>),
1162 /// A `match` block.
1163 Match(P<Expr>, Vec<Arm>),
1164 /// A closure (e.g., `move |a, b, c| a + b + c`).
1166 /// The final span is the span of the argument block `|...|`.
1167 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1168 /// A block (`'label: { ... }`).
1169 Block(P<Block>, Option<Label>),
1170 /// An async block (`async move { ... }`).
1172 /// The `NodeId` is the `NodeId` for the closure that results from
1173 /// desugaring an async block, just like the NodeId field in the
1174 /// `IsAsync` enum. This is necessary in order to create a def for the
1175 /// closure which can be used as a parent of any child defs. Defs
1176 /// created during lowering cannot be made the parent of any other
1177 /// preexisting defs.
1178 Async(CaptureBy, NodeId, P<Block>),
1179 /// An await expression (`my_future.await`).
1180 Await(AwaitOrigin, P<Expr>),
1182 /// A try block (`try { ... }`).
1185 /// An assignment (`a = foo()`).
1186 Assign(P<Expr>, P<Expr>),
1187 /// An assignment with an operator.
1190 AssignOp(BinOp, P<Expr>, P<Expr>),
1191 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1192 Field(P<Expr>, Ident),
1193 /// An indexing operation (e.g., `foo[2]`).
1194 Index(P<Expr>, P<Expr>),
1195 /// A range (e.g., `1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`).
1196 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1198 /// Variable reference, possibly containing `::` and/or type
1199 /// parameters (e.g., `foo::bar::<baz>`).
1201 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1202 Path(Option<QSelf>, Path),
1204 /// A referencing operation (`&a` or `&mut a`).
1205 AddrOf(Mutability, P<Expr>),
1206 /// A `break`, with an optional label to break, and an optional expression.
1207 Break(Option<Label>, Option<P<Expr>>),
1208 /// A `continue`, with an optional label.
1209 Continue(Option<Label>),
1210 /// A `return`, with an optional value to be returned.
1211 Ret(Option<P<Expr>>),
1213 /// Output of the `asm!()` macro.
1214 InlineAsm(P<InlineAsm>),
1216 /// A macro invocation; pre-expansion.
1219 /// A struct literal expression.
1221 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1222 /// where `base` is the `Option<Expr>`.
1223 Struct(Path, Vec<Field>, Option<P<Expr>>),
1225 /// An array literal constructed from one repeated element.
1227 /// E.g., `[1; 5]`. The expression is the element to be
1228 /// repeated; the constant is the number of times to repeat it.
1229 Repeat(P<Expr>, AnonConst),
1231 /// No-op: used solely so we can pretty-print faithfully.
1234 /// A try expression (`expr?`).
1237 /// A `yield`, with an optional value to be yielded.
1238 Yield(Option<P<Expr>>),
1240 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1244 /// The explicit `Self` type in a "qualified path". The actual
1245 /// path, including the trait and the associated item, is stored
1246 /// separately. `position` represents the index of the associated
1247 /// item qualified with this `Self` type.
1249 /// ```ignore (only-for-syntax-highlight)
1250 /// <Vec<T> as a::b::Trait>::AssociatedItem
1251 /// ^~~~~ ~~~~~~~~~~~~~~^
1254 /// <Vec<T>>::AssociatedItem
1258 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1262 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1263 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1264 /// 0`, this is an empty span.
1265 pub path_span: Span,
1266 pub position: usize,
1269 /// A capture clause.
1270 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1271 pub enum CaptureBy {
1276 /// The movability of a generator / closure literal.
1277 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1278 pub enum Movability {
1283 /// Whether an `await` comes from `await!` or `.await` syntax.
1284 /// FIXME: this should be removed when support for legacy `await!` is removed.
1285 /// https://github.com/rust-lang/rust/issues/60610
1286 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1287 pub enum AwaitOrigin {
1292 pub type Mac = Spanned<Mac_>;
1294 /// Represents a macro invocation. The `Path` indicates which macro
1295 /// is being invoked, and the vector of token-trees contains the source
1296 /// of the macro invocation.
1298 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1299 /// stored in the enclosing item.
1300 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1303 pub delim: MacDelimiter,
1304 pub tts: TokenStream,
1307 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1308 pub enum MacDelimiter {
1315 pub fn stream(&self) -> TokenStream {
1320 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1321 pub struct MacroDef {
1322 pub tokens: TokenStream,
1327 pub fn stream(&self) -> TokenStream {
1328 self.tokens.clone().into()
1332 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1334 /// A regular string, like `"foo"`.
1336 /// A raw string, like `r##"foo"##`.
1338 /// The value is the number of `#` symbols used.
1343 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1345 /// The original literal token as written in source code.
1346 pub token: token::Lit,
1347 /// The "semantic" representation of the literal lowered from the original tokens.
1348 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1349 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1354 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1355 pub enum LitIntType {
1363 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1364 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1366 /// A string literal (`"foo"`).
1367 Str(Symbol, StrStyle),
1368 /// A byte string (`b"foo"`).
1369 ByteStr(Lrc<Vec<u8>>),
1370 /// A byte char (`b'f'`).
1372 /// A character literal (`'a'`).
1374 /// An integer literal (`1`).
1375 Int(u128, LitIntType),
1376 /// A float literal (`1f64` or `1E10f64`).
1377 Float(Symbol, FloatTy),
1378 /// A float literal without a suffix (`1.0 or 1.0E10`).
1379 FloatUnsuffixed(Symbol),
1380 /// A boolean literal.
1382 /// A recovered character literal that contains mutliple `char`s, most likely a typo.
1387 /// Returns `true` if this literal is a string.
1388 pub fn is_str(&self) -> bool {
1390 LitKind::Str(..) => true,
1395 /// Returns `true` if this literal is byte literal string.
1396 pub fn is_bytestr(&self) -> bool {
1398 LitKind::ByteStr(_) => true,
1403 /// Returns `true` if this is a numeric literal.
1404 pub fn is_numeric(&self) -> bool {
1406 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1411 /// Returns `true` if this literal has no suffix.
1412 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1413 pub fn is_unsuffixed(&self) -> bool {
1415 // unsuffixed variants
1417 | LitKind::ByteStr(..)
1421 | LitKind::Int(_, LitIntType::Unsuffixed)
1422 | LitKind::FloatUnsuffixed(..)
1423 | LitKind::Bool(..) => true,
1424 // suffixed variants
1425 LitKind::Int(_, LitIntType::Signed(..))
1426 | LitKind::Int(_, LitIntType::Unsigned(..))
1427 | LitKind::Float(..) => false,
1431 /// Returns `true` if this literal has a suffix.
1432 pub fn is_suffixed(&self) -> bool {
1433 !self.is_unsuffixed()
1437 // N.B., If you change this, you'll probably want to change the corresponding
1438 // type structure in `middle/ty.rs` as well.
1439 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1442 pub mutbl: Mutability,
1445 /// Represents a method's signature in a trait declaration,
1446 /// or in an implementation.
1447 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1448 pub struct MethodSig {
1449 pub header: FnHeader,
1450 pub decl: P<FnDecl>,
1453 /// Represents an item declaration within a trait declaration,
1454 /// possibly including a default implementation. A trait item is
1455 /// either required (meaning it doesn't have an implementation, just a
1456 /// signature) or provided (meaning it has a default implementation).
1457 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1458 pub struct TraitItem {
1461 pub attrs: Vec<Attribute>,
1462 pub generics: Generics,
1463 pub node: TraitItemKind,
1465 /// See `Item::tokens` for what this is.
1466 pub tokens: Option<TokenStream>,
1469 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1470 pub enum TraitItemKind {
1471 Const(P<Ty>, Option<P<Expr>>),
1472 Method(MethodSig, Option<P<Block>>),
1473 Type(GenericBounds, Option<P<Ty>>),
1477 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1478 pub struct ImplItem {
1481 pub vis: Visibility,
1482 pub defaultness: Defaultness,
1483 pub attrs: Vec<Attribute>,
1484 pub generics: Generics,
1485 pub node: ImplItemKind,
1487 /// See `Item::tokens` for what this is.
1488 pub tokens: Option<TokenStream>,
1491 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1492 pub enum ImplItemKind {
1493 Const(P<Ty>, P<Expr>),
1494 Method(MethodSig, P<Block>),
1496 Existential(GenericBounds),
1500 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1510 impl fmt::Debug for IntTy {
1511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1512 fmt::Display::fmt(self, f)
1516 impl fmt::Display for IntTy {
1517 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1518 write!(f, "{}", self.ty_to_string())
1523 pub fn ty_to_string(&self) -> &'static str {
1525 IntTy::Isize => "isize",
1527 IntTy::I16 => "i16",
1528 IntTy::I32 => "i32",
1529 IntTy::I64 => "i64",
1530 IntTy::I128 => "i128",
1534 pub fn to_symbol(&self) -> Symbol {
1536 IntTy::Isize => sym::isize,
1537 IntTy::I8 => sym::i8,
1538 IntTy::I16 => sym::i16,
1539 IntTy::I32 => sym::i32,
1540 IntTy::I64 => sym::i64,
1541 IntTy::I128 => sym::i128,
1545 pub fn val_to_string(&self, val: i128) -> String {
1546 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1547 // are parsed as `u128`, so we wouldn't want to print an extra negative
1549 format!("{}{}", val as u128, self.ty_to_string())
1552 pub fn bit_width(&self) -> Option<usize> {
1554 IntTy::Isize => return None,
1564 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1575 pub fn ty_to_string(&self) -> &'static str {
1577 UintTy::Usize => "usize",
1579 UintTy::U16 => "u16",
1580 UintTy::U32 => "u32",
1581 UintTy::U64 => "u64",
1582 UintTy::U128 => "u128",
1586 pub fn to_symbol(&self) -> Symbol {
1588 UintTy::Usize => sym::usize,
1589 UintTy::U8 => sym::u8,
1590 UintTy::U16 => sym::u16,
1591 UintTy::U32 => sym::u32,
1592 UintTy::U64 => sym::u64,
1593 UintTy::U128 => sym::u128,
1597 pub fn val_to_string(&self, val: u128) -> String {
1598 format!("{}{}", val, self.ty_to_string())
1601 pub fn bit_width(&self) -> Option<usize> {
1603 UintTy::Usize => return None,
1608 UintTy::U128 => 128,
1613 impl fmt::Debug for UintTy {
1614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1615 fmt::Display::fmt(self, f)
1619 impl fmt::Display for UintTy {
1620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1621 write!(f, "{}", self.ty_to_string())
1625 // Bind a type to an associated type: `A = Foo`.
1626 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1627 pub struct TypeBinding {
1634 #[derive(Clone, RustcEncodable, RustcDecodable)]
1641 impl fmt::Debug for Ty {
1642 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1643 write!(f, "type({})", pprust::ty_to_string(self))
1647 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1648 pub struct BareFnTy {
1649 pub unsafety: Unsafety,
1651 pub generic_params: Vec<GenericParam>,
1652 pub decl: P<FnDecl>,
1655 /// The various kinds of type recognized by the compiler.
1656 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1658 /// A variable-length slice (`[T]`).
1660 /// A fixed length array (`[T; n]`).
1661 Array(P<Ty>, AnonConst),
1662 /// A raw pointer (`*const T` or `*mut T`).
1664 /// A reference (`&'a T` or `&'a mut T`).
1665 Rptr(Option<Lifetime>, MutTy),
1666 /// A bare function (e.g., `fn(usize) -> bool`).
1667 BareFn(P<BareFnTy>),
1668 /// The never type (`!`).
1670 /// A tuple (`(A, B, C, D,...)`).
1672 /// A path (`module::module::...::Type`), optionally
1673 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1675 /// Type parameters are stored in the `Path` itself.
1676 Path(Option<QSelf>, Path),
1677 /// A trait object type `Bound1 + Bound2 + Bound3`
1678 /// where `Bound` is a trait or a lifetime.
1679 TraitObject(GenericBounds, TraitObjectSyntax),
1680 /// An `impl Bound1 + Bound2 + Bound3` type
1681 /// where `Bound` is a trait or a lifetime.
1683 /// The `NodeId` exists to prevent lowering from having to
1684 /// generate `NodeId`s on the fly, which would complicate
1685 /// the generation of `existential type` items significantly.
1686 ImplTrait(NodeId, GenericBounds),
1687 /// No-op; kept solely so that we can pretty-print faithfully.
1691 /// This means the type should be inferred instead of it having been
1692 /// specified. This can appear anywhere in a type.
1694 /// Inferred type of a `self` or `&self` argument in a method.
1696 /// A macro in the type position.
1698 /// Placeholder for a kind that has failed to be defined.
1700 /// Placeholder for a `va_list`.
1705 pub fn is_implicit_self(&self) -> bool {
1706 if let TyKind::ImplicitSelf = *self {
1713 pub fn is_unit(&self) -> bool {
1714 if let TyKind::Tup(ref tys) = *self {
1722 /// Syntax used to declare a trait object.
1723 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1724 pub enum TraitObjectSyntax {
1729 /// Inline assembly dialect.
1731 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1732 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1733 pub enum AsmDialect {
1738 /// Inline assembly.
1740 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1741 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1742 pub struct InlineAsmOutput {
1743 pub constraint: Symbol,
1746 pub is_indirect: bool,
1749 /// Inline assembly.
1751 /// E.g., `asm!("NOP");`.
1752 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1753 pub struct InlineAsm {
1755 pub asm_str_style: StrStyle,
1756 pub outputs: Vec<InlineAsmOutput>,
1757 pub inputs: Vec<(Symbol, P<Expr>)>,
1758 pub clobbers: Vec<Symbol>,
1760 pub alignstack: bool,
1761 pub dialect: AsmDialect,
1762 pub ctxt: SyntaxContext,
1765 /// An argument in a function header.
1767 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1768 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1773 pub source: ArgSource,
1776 /// The source of an argument in a function header.
1777 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1778 pub enum ArgSource {
1779 /// Argument as written by the user.
1781 /// Argument from `async fn` lowering, contains the original binding pattern.
1785 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1787 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1788 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1790 /// `self`, `mut self`
1792 /// `&'lt self`, `&'lt mut self`
1793 Region(Option<Lifetime>, Mutability),
1794 /// `self: TYPE`, `mut self: TYPE`
1795 Explicit(P<Ty>, Mutability),
1798 pub type ExplicitSelf = Spanned<SelfKind>;
1801 pub fn to_self(&self) -> Option<ExplicitSelf> {
1802 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1803 if ident.name == kw::SelfLower {
1804 return match self.ty.node {
1805 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1806 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1807 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1810 self.pat.span.to(self.ty.span),
1811 SelfKind::Explicit(self.ty.clone(), mutbl),
1819 pub fn is_self(&self) -> bool {
1820 if let PatKind::Ident(_, ident, _) = self.pat.node {
1821 ident.name == kw::SelfLower
1827 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1828 let span = eself.span.to(eself_ident.span);
1829 let infer_ty = P(Ty {
1831 node: TyKind::ImplicitSelf,
1834 let arg = |mutbl, ty| Arg {
1837 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1842 source: ArgSource::Normal,
1845 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1846 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1847 SelfKind::Region(lt, mutbl) => arg(
1848 Mutability::Immutable,
1865 /// Header (not the body) of a function declaration.
1867 /// E.g., `fn foo(bar: baz)`.
1868 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1870 pub inputs: Vec<Arg>,
1871 pub output: FunctionRetTy,
1872 pub c_variadic: bool,
1876 pub fn get_self(&self) -> Option<ExplicitSelf> {
1877 self.inputs.get(0).and_then(Arg::to_self)
1879 pub fn has_self(&self) -> bool {
1880 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1884 /// Is the trait definition an auto trait?
1885 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1891 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1897 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1898 pub struct AsyncArgument {
1901 /// `__arg0: <ty>` argument to replace existing function argument `<pat>: <ty>`. Only if
1902 /// argument is not a simple binding.
1903 pub arg: Option<Arg>,
1904 /// `let __arg0 = __arg0;` statement to be inserted at the start of the block.
1905 pub move_stmt: Stmt,
1906 /// `let <pat> = __arg0;` statement to be inserted at the start of the block, after matching
1907 /// move statement. Only if argument is not a simple binding.
1908 pub pat_stmt: Option<Stmt>,
1911 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1915 return_impl_trait_id: NodeId,
1916 /// This field stores the arguments and statements that are used in HIR lowering to
1917 /// ensure that `async fn` arguments are dropped at the correct time.
1919 /// The argument and statements here are generated at parse time as they are required in
1920 /// both the hir lowering, def collection and name resolution and this stops them needing
1921 /// to be created in each place.
1922 arguments: Vec<AsyncArgument>,
1928 pub fn is_async(&self) -> bool {
1929 if let IsAsync::Async { .. } = *self {
1936 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1937 pub fn opt_return_id(&self) -> Option<NodeId> {
1940 return_impl_trait_id,
1942 } => Some(*return_impl_trait_id),
1943 IsAsync::NotAsync => None,
1948 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1949 pub enum Constness {
1954 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1955 pub enum Defaultness {
1960 impl fmt::Display for Unsafety {
1961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1964 Unsafety::Normal => "normal",
1965 Unsafety::Unsafe => "unsafe",
1972 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1973 pub enum ImplPolarity {
1974 /// `impl Trait for Type`
1976 /// `impl !Trait for Type`
1980 impl fmt::Debug for ImplPolarity {
1981 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1983 ImplPolarity::Positive => "positive".fmt(f),
1984 ImplPolarity::Negative => "negative".fmt(f),
1989 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1990 pub enum FunctionRetTy {
1991 /// Returns type is not specified.
1993 /// Functions default to `()` and closures default to inference.
1994 /// Span points to where return type would be inserted.
1996 /// Everything else.
2000 impl FunctionRetTy {
2001 pub fn span(&self) -> Span {
2003 FunctionRetTy::Default(span) => span,
2004 FunctionRetTy::Ty(ref ty) => ty.span,
2009 /// Module declaration.
2011 /// E.g., `mod foo;` or `mod foo { .. }`.
2012 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2014 /// A span from the first token past `{` to the last token until `}`.
2015 /// For `mod foo;`, the inner span ranges from the first token
2016 /// to the last token in the external file.
2018 pub items: Vec<P<Item>>,
2019 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2023 /// Foreign module declaration.
2025 /// E.g., `extern { .. }` or `extern C { .. }`.
2026 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2027 pub struct ForeignMod {
2029 pub items: Vec<ForeignItem>,
2032 /// Global inline assembly.
2034 /// Also known as "module-level assembly" or "file-scoped assembly".
2035 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2036 pub struct GlobalAsm {
2038 pub ctxt: SyntaxContext,
2041 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2042 pub struct EnumDef {
2043 pub variants: Vec<Variant>,
2046 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2047 pub struct Variant_ {
2048 /// Name of the variant.
2050 /// Attributes of the variant.
2051 pub attrs: Vec<Attribute>,
2052 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2054 /// Fields and constructor id of the variant.
2055 pub data: VariantData,
2056 /// Explicit discriminant, e.g., `Foo = 1`.
2057 pub disr_expr: Option<AnonConst>,
2060 pub type Variant = Spanned<Variant_>;
2062 /// Part of `use` item to the right of its prefix.
2063 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2064 pub enum UseTreeKind {
2065 /// `use prefix` or `use prefix as rename`
2067 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2069 Simple(Option<Ident>, NodeId, NodeId),
2070 /// `use prefix::{...}`
2071 Nested(Vec<(UseTree, NodeId)>),
2076 /// A tree of paths sharing common prefixes.
2077 /// Used in `use` items both at top-level and inside of braces in import groups.
2078 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2079 pub struct UseTree {
2081 pub kind: UseTreeKind,
2086 pub fn ident(&self) -> Ident {
2088 UseTreeKind::Simple(Some(rename), ..) => rename,
2089 UseTreeKind::Simple(None, ..) => {
2093 .expect("empty prefix in a simple import")
2096 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2101 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2102 /// are contained as statements within items. These two cases need to be
2103 /// distinguished for pretty-printing.
2104 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
2105 pub enum AttrStyle {
2111 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
2113 pub struct AttrId(pub usize);
2115 impl Idx for AttrId {
2116 fn new(idx: usize) -> Self {
2119 fn index(self) -> usize {
2124 /// Metadata associated with an item.
2125 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
2126 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2127 pub struct Attribute {
2129 pub style: AttrStyle,
2131 pub tokens: TokenStream,
2132 pub is_sugared_doc: bool,
2136 /// `TraitRef`s appear in impls.
2138 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2139 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2140 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2141 /// same as the impl's `NodeId`).
2142 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2143 pub struct TraitRef {
2148 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2149 pub struct PolyTraitRef {
2150 /// The `'a` in `<'a> Foo<&'a T>`.
2151 pub bound_generic_params: Vec<GenericParam>,
2153 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2154 pub trait_ref: TraitRef,
2160 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2162 bound_generic_params: generic_params,
2163 trait_ref: TraitRef {
2165 ref_id: DUMMY_NODE_ID,
2172 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2173 pub enum CrateSugar {
2174 /// Source is `pub(crate)`.
2177 /// Source is (just) `crate`.
2181 pub type Visibility = Spanned<VisibilityKind>;
2183 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2184 pub enum VisibilityKind {
2187 Restricted { path: P<Path>, id: NodeId },
2191 impl VisibilityKind {
2192 pub fn is_pub(&self) -> bool {
2193 if let VisibilityKind::Public = *self {
2201 /// Field of a struct.
2203 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2204 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2205 pub struct StructField {
2207 pub ident: Option<Ident>,
2208 pub vis: Visibility,
2211 pub attrs: Vec<Attribute>,
2214 /// Fields and constructor ids of enum variants and structs.
2215 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2216 pub enum VariantData {
2219 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2220 Struct(Vec<StructField>, bool),
2223 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2224 Tuple(Vec<StructField>, NodeId),
2227 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2232 /// Return the fields of this variant.
2233 pub fn fields(&self) -> &[StructField] {
2235 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2240 /// Return the `NodeId` of this variant's constructor, if it has one.
2241 pub fn ctor_id(&self) -> Option<NodeId> {
2243 VariantData::Struct(..) => None,
2244 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2251 /// The name might be a dummy name in case of anonymous items.
2252 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2255 pub attrs: Vec<Attribute>,
2258 pub vis: Visibility,
2261 /// Original tokens this item was parsed from. This isn't necessarily
2262 /// available for all items, although over time more and more items should
2263 /// have this be `Some`. Right now this is primarily used for procedural
2264 /// macros, notably custom attributes.
2266 /// Note that the tokens here do not include the outer attributes, but will
2267 /// include inner attributes.
2268 pub tokens: Option<TokenStream>,
2272 /// Return the span that encompasses the attributes.
2273 pub fn span_with_attributes(&self) -> Span {
2274 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2278 /// A function header.
2280 /// All the information between the visibility and the name of the function is
2281 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2282 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2283 pub struct FnHeader {
2284 pub unsafety: Unsafety,
2285 pub asyncness: Spanned<IsAsync>,
2286 pub constness: Spanned<Constness>,
2290 impl Default for FnHeader {
2291 fn default() -> FnHeader {
2293 unsafety: Unsafety::Normal,
2294 asyncness: dummy_spanned(IsAsync::NotAsync),
2295 constness: dummy_spanned(Constness::NotConst),
2301 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2303 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2305 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2306 ExternCrate(Option<Name>),
2307 /// A use declaration (`use` or `pub use`) item.
2309 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2311 /// A static item (`static` or `pub static`).
2313 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2314 Static(P<Ty>, Mutability, P<Expr>),
2315 /// A constant item (`const` or `pub const`).
2317 /// E.g., `const FOO: i32 = 42;`.
2318 Const(P<Ty>, P<Expr>),
2319 /// A function declaration (`fn` or `pub fn`).
2321 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2322 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2323 /// A module declaration (`mod` or `pub mod`).
2325 /// E.g., `mod foo;` or `mod foo { .. }`.
2327 /// An external module (`extern` or `pub extern`).
2329 /// E.g., `extern {}` or `extern "C" {}`.
2330 ForeignMod(ForeignMod),
2331 /// Module-level inline assembly (from `global_asm!()`).
2332 GlobalAsm(P<GlobalAsm>),
2333 /// A type alias (`type` or `pub type`).
2335 /// E.g., `type Foo = Bar<u8>;`.
2336 Ty(P<Ty>, Generics),
2337 /// An existential type declaration (`existential type`).
2339 /// E.g., `existential type Foo: Bar + Boo;`.
2340 Existential(GenericBounds, Generics),
2341 /// An enum definition (`enum` or `pub enum`).
2343 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2344 Enum(EnumDef, Generics),
2345 /// A struct definition (`struct` or `pub struct`).
2347 /// E.g., `struct Foo<A> { x: A }`.
2348 Struct(VariantData, Generics),
2349 /// A union definition (`union` or `pub union`).
2351 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2352 Union(VariantData, Generics),
2353 /// A Trait declaration (`trait` or `pub trait`).
2355 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2356 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2359 /// E.g., `trait Foo = Bar + Quux;`.
2360 TraitAlias(Generics, GenericBounds),
2361 /// An implementation.
2363 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2369 Option<TraitRef>, // (optional) trait this impl implements
2373 /// A macro invocation.
2375 /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2378 /// A macro definition.
2383 pub fn descriptive_variant(&self) -> &str {
2385 ItemKind::ExternCrate(..) => "extern crate",
2386 ItemKind::Use(..) => "use",
2387 ItemKind::Static(..) => "static item",
2388 ItemKind::Const(..) => "constant item",
2389 ItemKind::Fn(..) => "function",
2390 ItemKind::Mod(..) => "module",
2391 ItemKind::ForeignMod(..) => "foreign module",
2392 ItemKind::GlobalAsm(..) => "global asm",
2393 ItemKind::Ty(..) => "type alias",
2394 ItemKind::Existential(..) => "existential type",
2395 ItemKind::Enum(..) => "enum",
2396 ItemKind::Struct(..) => "struct",
2397 ItemKind::Union(..) => "union",
2398 ItemKind::Trait(..) => "trait",
2399 ItemKind::TraitAlias(..) => "trait alias",
2400 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2405 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2406 pub struct ForeignItem {
2408 pub attrs: Vec<Attribute>,
2409 pub node: ForeignItemKind,
2412 pub vis: Visibility,
2415 /// An item within an `extern` block.
2416 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2417 pub enum ForeignItemKind {
2418 /// A foreign function.
2419 Fn(P<FnDecl>, Generics),
2420 /// A foreign static item (`static ext: u8`).
2421 Static(P<Ty>, Mutability),
2424 /// A macro invocation.
2428 impl ForeignItemKind {
2429 pub fn descriptive_variant(&self) -> &str {
2431 ForeignItemKind::Fn(..) => "foreign function",
2432 ForeignItemKind::Static(..) => "foreign static item",
2433 ForeignItemKind::Ty => "foreign type",
2434 ForeignItemKind::Macro(..) => "macro in foreign module",
2444 // Are ASTs encodable?
2446 fn check_asts_encodable() {
2447 fn assert_encodable<T: serialize::Encodable>() {}
2448 assert_encodable::<Crate>();