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::print::pprust;
11 use crate::source_map::{dummy_spanned, respan, Spanned};
12 use crate::symbol::{keywords, Symbol};
13 use crate::tokenstream::TokenStream;
16 use rustc_data_structures::indexed_vec::Idx;
17 #[cfg(target_arch = "x86_64")]
18 use rustc_data_structures::static_assert;
19 use rustc_target::spec::abi::Abi;
20 use syntax_pos::{Span, DUMMY_SP};
22 use rustc_data_structures::fx::FxHashSet;
23 use rustc_data_structures::sync::Lrc;
24 use serialize::{self, Decoder, Encoder};
27 pub use rustc_target::abi::FloatTy;
29 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
34 impl fmt::Debug for Label {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 write!(f, "label({:?})", self.ident)
40 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
46 impl fmt::Debug for Lifetime {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 pprust::lifetime_to_string(self)
57 /// A "Path" is essentially Rust's notion of a name.
59 /// It's represented as a sequence of identifiers,
60 /// along with a bunch of supporting information.
62 /// E.g., `std::cmp::PartialEq`.
63 #[derive(Clone, RustcEncodable, RustcDecodable)]
66 /// The segments in the path: the things separated by `::`.
67 /// Global paths begin with `keywords::PathRoot`.
68 pub segments: Vec<PathSegment>,
71 impl<'a> PartialEq<&'a str> for Path {
72 fn eq(&self, string: &&'a str) -> bool {
73 self.segments.len() == 1 && self.segments[0].ident.name == *string
77 impl fmt::Debug for Path {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 write!(f, "path({})", pprust::path_to_string(self))
83 impl fmt::Display for Path {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 write!(f, "{}", pprust::path_to_string(self))
90 // Convert a span and an identifier to the corresponding
92 pub fn from_ident(ident: Ident) -> Path {
94 segments: vec![PathSegment::from_ident(ident)],
99 pub fn is_global(&self) -> bool {
100 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
104 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
106 /// E.g., `std`, `String` or `Box<T>`.
107 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
108 pub struct PathSegment {
109 /// The identifier portion of this path segment.
114 /// Type/lifetime parameters attached to this path. They come in
115 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
116 /// `None` means that no parameter list is supplied (`Path`),
117 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
118 /// but it can be empty (`Path<>`).
119 /// `P` is used as a size optimization for the common case with no parameters.
120 pub args: Option<P<GenericArgs>>,
124 pub fn from_ident(ident: Ident) -> Self {
125 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
127 pub fn path_root(span: Span) -> Self {
128 PathSegment::from_ident(Ident::new(keywords::PathRoot.name(), span))
132 /// Arguments of a path segment.
134 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
135 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
136 pub enum GenericArgs {
137 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
138 AngleBracketed(AngleBracketedArgs),
139 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
140 Parenthesized(ParenthesizedArgs),
144 pub fn is_parenthesized(&self) -> bool {
146 Parenthesized(..) => true,
151 pub fn is_angle_bracketed(&self) -> bool {
153 AngleBracketed(..) => true,
158 pub fn span(&self) -> Span {
160 AngleBracketed(ref data) => data.span,
161 Parenthesized(ref data) => data.span,
166 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
167 pub enum GenericArg {
172 /// A path like `Foo<'a, T>`
173 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
174 pub struct AngleBracketedArgs {
177 /// The arguments for this path segment.
178 pub args: Vec<GenericArg>,
179 /// Bindings (equality constraints) on associated types, if present.
181 /// E.g., `Foo<A=Bar>`.
182 pub bindings: Vec<TypeBinding>,
185 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
186 fn into(self) -> Option<P<GenericArgs>> {
187 Some(P(GenericArgs::AngleBracketed(self)))
191 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
192 fn into(self) -> Option<P<GenericArgs>> {
193 Some(P(GenericArgs::Parenthesized(self)))
197 /// A path like `Foo(A,B) -> C`
198 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
199 pub struct ParenthesizedArgs {
204 pub inputs: Vec<P<Ty>>,
207 pub output: Option<P<Ty>>,
210 impl ParenthesizedArgs {
211 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
214 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
220 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
222 use rustc_data_structures::indexed_vec::Idx;
223 use rustc_data_structures::newtype_index;
227 DEBUG_FORMAT = "NodeId({})"
232 pub use node_id_inner::NodeId;
235 pub fn placeholder_from_mark(mark: Mark) -> Self {
236 NodeId::from_u32(mark.as_u32())
239 pub fn placeholder_to_mark(self) -> Mark {
240 Mark::from_u32(self.as_u32())
244 impl fmt::Display for NodeId {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246 fmt::Display::fmt(&self.as_u32(), f)
250 impl serialize::UseSpecializedEncodable for NodeId {
251 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
252 s.emit_u32(self.as_u32())
256 impl serialize::UseSpecializedDecodable for NodeId {
257 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
258 d.read_u32().map(NodeId::from_u32)
262 /// Node id used to represent the root of the crate.
263 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
265 /// When parsing and doing expansions, we initially give all AST nodes this AST
266 /// node value. Then later, in the renumber pass, we renumber them to have
267 /// small, positive ids.
268 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
270 /// A modifier on a bound, currently this is only used for `?Sized`, where the
271 /// modifier is `Maybe`. Negative bounds should also be handled here.
272 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
273 pub enum TraitBoundModifier {
278 /// The AST represents all type param bounds as types.
279 /// `typeck::collect::compute_bounds` matches these against
280 /// the "special" built-in traits (see `middle::lang_items`) and
281 /// detects `Copy`, `Send` and `Sync`.
282 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
283 pub enum GenericBound {
284 Trait(PolyTraitRef, TraitBoundModifier),
289 pub fn span(&self) -> Span {
291 &GenericBound::Trait(ref t, ..) => t.span,
292 &GenericBound::Outlives(ref l) => l.ident.span,
297 pub type GenericBounds = Vec<GenericBound>;
299 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
300 pub enum GenericParamKind {
301 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
304 default: Option<P<Ty>>,
308 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
309 pub struct GenericParam {
312 pub attrs: ThinVec<Attribute>,
313 pub bounds: GenericBounds,
315 pub kind: GenericParamKind,
318 /// Represents lifetime, type and const parameters attached to a declaration of
319 /// a function, enum, trait, etc.
320 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
321 pub struct Generics {
322 pub params: Vec<GenericParam>,
323 pub where_clause: WhereClause,
327 impl Default for Generics {
328 /// Creates an instance of `Generics`.
329 fn default() -> Generics {
332 where_clause: WhereClause {
334 predicates: Vec::new(),
342 /// A `where` clause in a definition
343 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
344 pub struct WhereClause {
346 pub predicates: Vec<WherePredicate>,
350 /// A single predicate in a `where` clause
351 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
352 pub enum WherePredicate {
353 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
354 BoundPredicate(WhereBoundPredicate),
355 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
356 RegionPredicate(WhereRegionPredicate),
357 /// An equality predicate (unsupported).
358 EqPredicate(WhereEqPredicate),
361 impl WherePredicate {
362 pub fn span(&self) -> Span {
364 &WherePredicate::BoundPredicate(ref p) => p.span,
365 &WherePredicate::RegionPredicate(ref p) => p.span,
366 &WherePredicate::EqPredicate(ref p) => p.span,
373 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
374 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
375 pub struct WhereBoundPredicate {
377 /// Any generics from a `for` binding
378 pub bound_generic_params: Vec<GenericParam>,
379 /// The type being bounded
380 pub bounded_ty: P<Ty>,
381 /// Trait and lifetime bounds (`Clone+Send+'static`)
382 pub bounds: GenericBounds,
385 /// A lifetime predicate.
387 /// E.g., `'a: 'b + 'c`.
388 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
389 pub struct WhereRegionPredicate {
391 pub lifetime: Lifetime,
392 pub bounds: GenericBounds,
395 /// An equality predicate (unsupported).
398 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
399 pub struct WhereEqPredicate {
406 /// The set of `MetaItem`s that define the compilation environment of the crate,
407 /// used to drive conditional compilation.
408 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
410 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
413 pub attrs: Vec<Attribute>,
417 /// A spanned compile-time attribute list item.
418 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
420 /// Possible values inside of compile-time attribute lists.
422 /// E.g., the '..' in `#[name(..)]`.
423 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
424 pub enum NestedMetaItemKind {
425 /// A full MetaItem, for recursive meta items.
429 /// E.g., `"foo"`, `64`, `true`.
433 /// A spanned compile-time attribute item.
435 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
436 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
437 pub struct MetaItem {
439 pub node: MetaItemKind,
443 /// A compile-time attribute item.
445 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
446 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
447 pub enum MetaItemKind {
450 /// E.g., `test` as in `#[test]`.
454 /// E.g., `derive(..)` as in `#[derive(..)]`.
455 List(Vec<NestedMetaItem>),
456 /// Name value meta item.
458 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
462 /// A Block (`{ .. }`).
464 /// E.g., `{ .. }` as in `fn foo() { .. }`.
465 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
467 /// Statements in a block
468 pub stmts: Vec<Stmt>,
470 /// Distinguishes between `unsafe { ... }` and `{ ... }`
471 pub rules: BlockCheckMode,
475 #[derive(Clone, RustcEncodable, RustcDecodable)]
482 impl fmt::Debug for Pat {
483 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
489 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
490 let node = match &self.node {
491 PatKind::Wild => TyKind::Infer,
492 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
493 TyKind::Path(None, Path::from_ident(*ident))
495 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
496 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
497 PatKind::Ref(pat, mutbl) => pat
499 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
500 PatKind::Slice(pats, None, _) if pats.len() == 1 => {
501 pats[0].to_ty().map(TyKind::Slice)?
503 PatKind::Tuple(pats, None) => {
504 let mut tys = Vec::with_capacity(pats.len());
505 // FIXME(#48994) - could just be collected into an Option<Vec>
507 tys.push(pat.to_ty()?);
521 pub fn walk<F>(&self, it: &mut F) -> bool
523 F: FnMut(&Pat) -> bool,
530 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
531 PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
532 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
533 s.iter().all(|p| p.walk(it))
535 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
536 PatKind::Slice(ref before, ref slice, ref after) => {
537 before.iter().all(|p| p.walk(it))
538 && slice.iter().all(|p| p.walk(it))
539 && after.iter().all(|p| p.walk(it))
546 | PatKind::Mac(_) => true,
551 /// A single field in a struct pattern
553 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
554 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
555 /// except is_shorthand is true
556 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
557 pub struct FieldPat {
558 /// The identifier for the field
560 /// The pattern the field is destructured to
562 pub is_shorthand: bool,
563 pub attrs: ThinVec<Attribute>,
566 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
567 pub enum BindingMode {
572 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
574 Included(RangeSyntax),
578 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
579 pub enum RangeSyntax {
584 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
586 /// Represents a wildcard pattern (`_`).
589 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
590 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
591 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
592 /// during name resolution.
593 Ident(BindingMode, Ident, Option<P<Pat>>),
595 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
596 /// The `bool` is `true` in the presence of a `..`.
597 Struct(Path, Vec<Spanned<FieldPat>>, bool),
599 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
600 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
601 /// `0 <= position <= subpats.len()`.
602 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
604 /// A possibly qualified path pattern.
605 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
606 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
607 /// only legally refer to associated constants.
608 Path(Option<QSelf>, Path),
610 /// A tuple pattern (`(a, b)`).
611 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
612 /// `0 <= position <= subpats.len()`.
613 Tuple(Vec<P<Pat>>, Option<usize>),
616 /// A reference pattern (e.g., `&mut (a, b)`).
617 Ref(P<Pat>, Mutability),
620 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
621 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
622 /// `[a, b, ..i, y, z]` is represented as:
623 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
624 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
625 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
627 /// A macro pattern; pre-expansion.
632 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
634 pub enum Mutability {
639 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
641 /// The `+` operator (addition)
643 /// The `-` operator (subtraction)
645 /// The `*` operator (multiplication)
647 /// The `/` operator (division)
649 /// The `%` operator (modulus)
651 /// The `&&` operator (logical and)
653 /// The `||` operator (logical or)
655 /// The `^` operator (bitwise xor)
657 /// The `&` operator (bitwise and)
659 /// The `|` operator (bitwise or)
661 /// The `<<` operator (shift left)
663 /// The `>>` operator (shift right)
665 /// The `==` operator (equality)
667 /// The `<` operator (less than)
669 /// The `<=` operator (less than or equal to)
671 /// The `!=` operator (not equal to)
673 /// The `>=` operator (greater than or equal to)
675 /// The `>` operator (greater than)
680 pub fn to_string(&self) -> &'static str {
703 pub fn lazy(&self) -> bool {
705 BinOpKind::And | BinOpKind::Or => true,
710 pub fn is_shift(&self) -> bool {
712 BinOpKind::Shl | BinOpKind::Shr => true,
717 pub fn is_comparison(&self) -> bool {
720 Eq | Lt | Le | Ne | Gt | Ge => true,
721 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
725 /// Returns `true` if the binary operator takes its arguments by value
726 pub fn is_by_value(&self) -> bool {
727 !self.is_comparison()
731 pub type BinOp = Spanned<BinOpKind>;
733 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
735 /// The `*` operator for dereferencing
737 /// The `!` operator for logical inversion
739 /// The `-` operator for negation
744 /// Returns `true` if the unary operator takes its argument by value
745 pub fn is_by_value(u: UnOp) -> bool {
747 UnOp::Neg | UnOp::Not => true,
752 pub fn to_string(op: UnOp) -> &'static str {
762 #[derive(Clone, RustcEncodable, RustcDecodable)]
770 pub fn add_trailing_semicolon(mut self) -> Self {
771 self.node = match self.node {
772 StmtKind::Expr(expr) => StmtKind::Semi(expr),
773 StmtKind::Mac(mac) => {
774 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
781 pub fn is_item(&self) -> bool {
783 StmtKind::Item(_) => true,
788 pub fn is_expr(&self) -> bool {
790 StmtKind::Expr(_) => true,
796 impl fmt::Debug for Stmt {
797 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802 pprust::stmt_to_string(self)
807 #[derive(Clone, RustcEncodable, RustcDecodable)]
809 /// A local (let) binding.
812 /// An item definition.
815 /// Expr without trailing semi-colon.
817 /// Expr with a trailing semi-colon.
820 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
823 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
824 pub enum MacStmtStyle {
825 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
826 /// `foo!(...);`, `foo![...];`).
828 /// The macro statement had braces (e.g., `foo! { ... }`).
830 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
831 /// `foo!(...)`). All of these will end up being converted into macro
836 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
837 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
840 pub ty: Option<P<Ty>>,
841 /// Initializer expression to set the value, if any.
842 pub init: Option<P<Expr>>,
845 pub attrs: ThinVec<Attribute>,
848 /// An arm of a 'match'.
850 /// E.g., `0..=10 => { println!("match!") }` as in
854 /// 0..=10 => { println!("match!") },
855 /// _ => { println!("no match!") },
858 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
860 pub attrs: Vec<Attribute>,
861 pub pats: Vec<P<Pat>>,
862 pub guard: Option<Guard>,
866 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
871 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
876 pub is_shorthand: bool,
877 pub attrs: ThinVec<Attribute>,
880 pub type SpannedIdent = Spanned<Ident>;
882 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
883 pub enum BlockCheckMode {
885 Unsafe(UnsafeSource),
888 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
889 pub enum UnsafeSource {
894 /// A constant (expression) that's not an item or associated item,
895 /// but needs its own `DefId` for type-checking, const-eval, etc.
896 /// These are usually found nested inside types (e.g., array lengths)
897 /// or expressions (e.g., repeat counts), and also used to define
898 /// explicit discriminant values for enum variants.
899 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
900 pub struct AnonConst {
906 #[derive(Clone, RustcEncodable, RustcDecodable)]
911 pub attrs: ThinVec<Attribute>,
914 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
915 #[cfg(target_arch = "x86_64")]
916 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 88);
919 /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
921 pub fn returns(&self) -> bool {
922 if let ExprKind::Block(ref block, _) = self.node {
923 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
925 Some(&StmtKind::Expr(_)) => true,
926 Some(&StmtKind::Semi(ref expr)) => {
927 if let ExprKind::Ret(_) = expr.node {
928 // last statement is explicit return
934 // This is a block that doesn't end in either an implicit or explicit return
938 // This is not a block, it is a value
943 fn to_bound(&self) -> Option<GenericBound> {
945 ExprKind::Path(None, path) => Some(GenericBound::Trait(
946 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
947 TraitBoundModifier::None,
953 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
954 let node = match &self.node {
955 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
956 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
957 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
958 ExprKind::AddrOf(mutbl, expr) => expr
960 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
961 ExprKind::Repeat(expr, expr_len) => {
962 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
964 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
965 ExprKind::Tup(exprs) => {
968 .map(|expr| expr.to_ty())
969 .collect::<Option<Vec<_>>>()?;
972 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
973 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
974 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
989 pub fn precedence(&self) -> ExprPrecedence {
991 ExprKind::Box(_) => ExprPrecedence::Box,
992 ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
993 ExprKind::Array(_) => ExprPrecedence::Array,
994 ExprKind::Call(..) => ExprPrecedence::Call,
995 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
996 ExprKind::Tup(_) => ExprPrecedence::Tup,
997 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
998 ExprKind::Unary(..) => ExprPrecedence::Unary,
999 ExprKind::Lit(_) => ExprPrecedence::Lit,
1000 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1001 ExprKind::If(..) => ExprPrecedence::If,
1002 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
1003 ExprKind::While(..) => ExprPrecedence::While,
1004 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
1005 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1006 ExprKind::Loop(..) => ExprPrecedence::Loop,
1007 ExprKind::Match(..) => ExprPrecedence::Match,
1008 ExprKind::Closure(..) => ExprPrecedence::Closure,
1009 ExprKind::Block(..) => ExprPrecedence::Block,
1010 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1011 ExprKind::Async(..) => ExprPrecedence::Async,
1012 ExprKind::Assign(..) => ExprPrecedence::Assign,
1013 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1014 ExprKind::Field(..) => ExprPrecedence::Field,
1015 ExprKind::Index(..) => ExprPrecedence::Index,
1016 ExprKind::Range(..) => ExprPrecedence::Range,
1017 ExprKind::Path(..) => ExprPrecedence::Path,
1018 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1019 ExprKind::Break(..) => ExprPrecedence::Break,
1020 ExprKind::Continue(..) => ExprPrecedence::Continue,
1021 ExprKind::Ret(..) => ExprPrecedence::Ret,
1022 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1023 ExprKind::Mac(..) => ExprPrecedence::Mac,
1024 ExprKind::Struct(..) => ExprPrecedence::Struct,
1025 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1026 ExprKind::Paren(..) => ExprPrecedence::Paren,
1027 ExprKind::Try(..) => ExprPrecedence::Try,
1028 ExprKind::Yield(..) => ExprPrecedence::Yield,
1029 ExprKind::Err => ExprPrecedence::Err,
1034 impl fmt::Debug for Expr {
1035 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1040 /// Limit types of a range (inclusive or exclusive)
1041 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1042 pub enum RangeLimits {
1043 /// Inclusive at the beginning, exclusive at the end
1045 /// Inclusive at the beginning and end
1049 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1051 /// A `box x` expression.
1053 /// First expr is the place; second expr is the value.
1054 ObsoleteInPlace(P<Expr>, P<Expr>),
1055 /// An array (`[a, b, c, d]`)
1056 Array(Vec<P<Expr>>),
1059 /// The first field resolves to the function itself,
1060 /// and the second field is the list of arguments.
1061 /// This also represents calling the constructor of
1062 /// tuple-like ADTs such as tuple structs and enum variants.
1063 Call(P<Expr>, Vec<P<Expr>>),
1064 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1066 /// The `PathSegment` represents the method name and its generic arguments
1067 /// (within the angle brackets).
1068 /// The first element of the vector of an `Expr` is the expression that evaluates
1069 /// to the object on which the method is being called on (the receiver),
1070 /// and the remaining elements are the rest of the arguments.
1071 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1072 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1073 MethodCall(PathSegment, Vec<P<Expr>>),
1074 /// A tuple (e.g., `(a, b, c, d)`).
1076 /// A binary operation (e.g., `a + b`, `a * b`).
1077 Binary(BinOp, P<Expr>, P<Expr>),
1078 /// A unary operation (e.g., `!x`, `*x`).
1079 Unary(UnOp, P<Expr>),
1080 /// A literal (e.g., `1`, `"foo"`).
1082 /// A cast (e.g., `foo as f64`).
1083 Cast(P<Expr>, P<Ty>),
1084 Type(P<Expr>, P<Ty>),
1085 /// An `if` block, with an optional `else` block.
1087 /// `if expr { block } else { expr }`
1088 If(P<Expr>, P<Block>, Option<P<Expr>>),
1089 /// An `if let` expression with an optional else block
1091 /// `if let pat = expr { block } else { expr }`
1093 /// This is desugared to a `match` expression.
1094 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1095 /// A while loop, with an optional label
1097 /// `'label: while expr { block }`
1098 While(P<Expr>, P<Block>, Option<Label>),
1099 /// A `while let` loop, with an optional label.
1101 /// `'label: while let pat = expr { block }`
1103 /// This is desugared to a combination of `loop` and `match` expressions.
1104 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1105 /// A `for` loop, with an optional label.
1107 /// `'label: for pat in expr { block }`
1109 /// This is desugared to a combination of `loop` and `match` expressions.
1110 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1111 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1113 /// `'label: loop { block }`
1114 Loop(P<Block>, Option<Label>),
1115 /// A `match` block.
1116 Match(P<Expr>, Vec<Arm>),
1117 /// A closure (e.g., `move |a, b, c| a + b + c`).
1119 /// The final span is the span of the argument block `|...|`.
1120 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1121 /// A block (`'label: { ... }`).
1122 Block(P<Block>, Option<Label>),
1123 /// An async block (`async move { ... }`).
1125 /// The `NodeId` is the `NodeId` for the closure that results from
1126 /// desugaring an async block, just like the NodeId field in the
1127 /// `IsAsync` enum. This is necessary in order to create a def for the
1128 /// closure which can be used as a parent of any child defs. Defs
1129 /// created during lowering cannot be made the parent of any other
1130 /// preexisting defs.
1131 Async(CaptureBy, NodeId, P<Block>),
1132 /// A try block (`try { ... }`).
1135 /// An assignment (`a = foo()`).
1136 Assign(P<Expr>, P<Expr>),
1137 /// An assignment with an operator.
1140 AssignOp(BinOp, P<Expr>, P<Expr>),
1141 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1142 Field(P<Expr>, Ident),
1143 /// An indexing operation (e.g., `foo[2]`).
1144 Index(P<Expr>, P<Expr>),
1145 /// A range (e.g., `1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`).
1146 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1148 /// Variable reference, possibly containing `::` and/or type
1149 /// parameters (e.g., `foo::bar::<baz>`).
1151 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1152 Path(Option<QSelf>, Path),
1154 /// A referencing operation (`&a` or `&mut a`).
1155 AddrOf(Mutability, P<Expr>),
1156 /// A `break`, with an optional label to break, and an optional expression.
1157 Break(Option<Label>, Option<P<Expr>>),
1158 /// A `continue`, with an optional label.
1159 Continue(Option<Label>),
1160 /// A `return`, with an optional value to be returned.
1161 Ret(Option<P<Expr>>),
1163 /// Output of the `asm!()` macro.
1164 InlineAsm(P<InlineAsm>),
1166 /// A macro invocation; pre-expansion.
1169 /// A struct literal expression.
1171 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1172 /// where `base` is the `Option<Expr>`.
1173 Struct(Path, Vec<Field>, Option<P<Expr>>),
1175 /// An array literal constructed from one repeated element.
1177 /// E.g., `[1; 5]`. The expression is the element to be
1178 /// repeated; the constant is the number of times to repeat it.
1179 Repeat(P<Expr>, AnonConst),
1181 /// No-op: used solely so we can pretty-print faithfully.
1184 /// A try expression (`expr?`).
1187 /// A `yield`, with an optional value to be yielded.
1188 Yield(Option<P<Expr>>),
1190 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1194 /// The explicit `Self` type in a "qualified path". The actual
1195 /// path, including the trait and the associated item, is stored
1196 /// separately. `position` represents the index of the associated
1197 /// item qualified with this `Self` type.
1199 /// ```ignore (only-for-syntax-highlight)
1200 /// <Vec<T> as a::b::Trait>::AssociatedItem
1201 /// ^~~~~ ~~~~~~~~~~~~~~^
1204 /// <Vec<T>>::AssociatedItem
1208 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1212 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1213 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1214 /// 0`, this is an empty span.
1215 pub path_span: Span,
1216 pub position: usize,
1219 /// A capture clause.
1220 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1221 pub enum CaptureBy {
1226 /// The movability of a generator / closure literal.
1227 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1228 pub enum Movability {
1233 pub type Mac = Spanned<Mac_>;
1235 /// Represents a macro invocation. The `Path` indicates which macro
1236 /// is being invoked, and the vector of token-trees contains the source
1237 /// of the macro invocation.
1239 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1240 /// stored in the enclosing item.
1241 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1244 pub delim: MacDelimiter,
1245 pub tts: TokenStream,
1248 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1249 pub enum MacDelimiter {
1256 pub fn stream(&self) -> TokenStream {
1261 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1262 pub struct MacroDef {
1263 pub tokens: TokenStream,
1268 pub fn stream(&self) -> TokenStream {
1269 self.tokens.clone().into()
1273 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1275 /// A regular string, like `"foo"`.
1277 /// A raw string, like `r##"foo"##`.
1279 /// The value is the number of `#` symbols used.
1284 pub type Lit = Spanned<LitKind>;
1286 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1287 pub enum LitIntType {
1295 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1296 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1298 /// A string literal (`"foo"`).
1299 Str(Symbol, StrStyle),
1300 /// A byte string (`b"foo"`).
1301 ByteStr(Lrc<Vec<u8>>),
1302 /// A byte char (`b'f'`).
1304 /// A character literal (`'a'`).
1306 /// An integer literal (`1`).
1307 Int(u128, LitIntType),
1308 /// A float literal (`1f64` or `1E10f64`).
1309 Float(Symbol, FloatTy),
1310 /// A float literal without a suffix (`1.0 or 1.0E10`).
1311 FloatUnsuffixed(Symbol),
1312 /// A boolean literal.
1314 /// A recovered character literal that contains mutliple `char`s, most likely a typo.
1319 /// Returns `true` if this literal is a string.
1320 pub fn is_str(&self) -> bool {
1322 LitKind::Str(..) => true,
1327 /// Returns `true` if this literal is byte literal string.
1328 pub fn is_bytestr(&self) -> bool {
1330 LitKind::ByteStr(_) => true,
1335 /// Returns `true` if this is a numeric literal.
1336 pub fn is_numeric(&self) -> bool {
1338 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1343 /// Returns `true` if this literal has no suffix.
1344 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1345 pub fn is_unsuffixed(&self) -> bool {
1347 // unsuffixed variants
1349 | LitKind::ByteStr(..)
1353 | LitKind::Int(_, LitIntType::Unsuffixed)
1354 | LitKind::FloatUnsuffixed(..)
1355 | LitKind::Bool(..) => true,
1356 // suffixed variants
1357 LitKind::Int(_, LitIntType::Signed(..))
1358 | LitKind::Int(_, LitIntType::Unsigned(..))
1359 | LitKind::Float(..) => false,
1363 /// Returns `true` if this literal has a suffix.
1364 pub fn is_suffixed(&self) -> bool {
1365 !self.is_unsuffixed()
1369 // N.B., If you change this, you'll probably want to change the corresponding
1370 // type structure in `middle/ty.rs` as well.
1371 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1374 pub mutbl: Mutability,
1377 /// Represents a method's signature in a trait declaration,
1378 /// or in an implementation.
1379 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1380 pub struct MethodSig {
1381 pub header: FnHeader,
1382 pub decl: P<FnDecl>,
1385 /// Represents an item declaration within a trait declaration,
1386 /// possibly including a default implementation. A trait item is
1387 /// either required (meaning it doesn't have an implementation, just a
1388 /// signature) or provided (meaning it has a default implementation).
1389 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1390 pub struct TraitItem {
1393 pub attrs: Vec<Attribute>,
1394 pub generics: Generics,
1395 pub node: TraitItemKind,
1397 /// See `Item::tokens` for what this is.
1398 pub tokens: Option<TokenStream>,
1401 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1402 pub enum TraitItemKind {
1403 Const(P<Ty>, Option<P<Expr>>),
1404 Method(MethodSig, Option<P<Block>>),
1405 Type(GenericBounds, Option<P<Ty>>),
1409 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1410 pub struct ImplItem {
1413 pub vis: Visibility,
1414 pub defaultness: Defaultness,
1415 pub attrs: Vec<Attribute>,
1416 pub generics: Generics,
1417 pub node: ImplItemKind,
1419 /// See `Item::tokens` for what this is.
1420 pub tokens: Option<TokenStream>,
1423 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1424 pub enum ImplItemKind {
1425 Const(P<Ty>, P<Expr>),
1426 Method(MethodSig, P<Block>),
1428 Existential(GenericBounds),
1432 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1442 impl fmt::Debug for IntTy {
1443 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1444 fmt::Display::fmt(self, f)
1448 impl fmt::Display for IntTy {
1449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1450 write!(f, "{}", self.ty_to_string())
1455 pub fn ty_to_string(&self) -> &'static str {
1457 IntTy::Isize => "isize",
1459 IntTy::I16 => "i16",
1460 IntTy::I32 => "i32",
1461 IntTy::I64 => "i64",
1462 IntTy::I128 => "i128",
1466 pub fn val_to_string(&self, val: i128) -> String {
1467 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1468 // are parsed as `u128`, so we wouldn't want to print an extra negative
1470 format!("{}{}", val as u128, self.ty_to_string())
1473 pub fn bit_width(&self) -> Option<usize> {
1475 IntTy::Isize => return None,
1485 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1496 pub fn ty_to_string(&self) -> &'static str {
1498 UintTy::Usize => "usize",
1500 UintTy::U16 => "u16",
1501 UintTy::U32 => "u32",
1502 UintTy::U64 => "u64",
1503 UintTy::U128 => "u128",
1507 pub fn val_to_string(&self, val: u128) -> String {
1508 format!("{}{}", val, self.ty_to_string())
1511 pub fn bit_width(&self) -> Option<usize> {
1513 UintTy::Usize => return None,
1518 UintTy::U128 => 128,
1523 impl fmt::Debug for UintTy {
1524 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1525 fmt::Display::fmt(self, f)
1529 impl fmt::Display for UintTy {
1530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1531 write!(f, "{}", self.ty_to_string())
1535 // Bind a type to an associated type: `A = Foo`.
1536 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1537 pub struct TypeBinding {
1544 #[derive(Clone, RustcEncodable, RustcDecodable)]
1551 impl fmt::Debug for Ty {
1552 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1553 write!(f, "type({})", pprust::ty_to_string(self))
1557 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1558 pub struct BareFnTy {
1559 pub unsafety: Unsafety,
1561 pub generic_params: Vec<GenericParam>,
1562 pub decl: P<FnDecl>,
1565 /// The different kinds of types recognized by the compiler.
1566 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1568 /// A variable-length slice (`[T]`).
1570 /// A fixed length array (`[T; n]`).
1571 Array(P<Ty>, AnonConst),
1572 /// A raw pointer (`*const T` or `*mut T`).
1574 /// A reference (`&'a T` or `&'a mut T`).
1575 Rptr(Option<Lifetime>, MutTy),
1576 /// A bare function (e.g., `fn(usize) -> bool`).
1577 BareFn(P<BareFnTy>),
1578 /// The never type (`!`).
1580 /// A tuple (`(A, B, C, D,...)`).
1582 /// A path (`module::module::...::Type`), optionally
1583 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1585 /// Type parameters are stored in the `Path` itself.
1586 Path(Option<QSelf>, Path),
1587 /// A trait object type `Bound1 + Bound2 + Bound3`
1588 /// where `Bound` is a trait or a lifetime.
1589 TraitObject(GenericBounds, TraitObjectSyntax),
1590 /// An `impl Bound1 + Bound2 + Bound3` type
1591 /// where `Bound` is a trait or a lifetime.
1593 /// The `NodeId` exists to prevent lowering from having to
1594 /// generate `NodeId`s on the fly, which would complicate
1595 /// the generation of `existential type` items significantly.
1596 ImplTrait(NodeId, GenericBounds),
1597 /// No-op; kept solely so that we can pretty-print faithfully.
1601 /// This means the type should be inferred instead of it having been
1602 /// specified. This can appear anywhere in a type.
1604 /// Inferred type of a `self` or `&self` argument in a method.
1606 /// A macro in the type position.
1608 /// Placeholder for a kind that has failed to be defined.
1613 pub fn is_implicit_self(&self) -> bool {
1614 if let TyKind::ImplicitSelf = *self {
1621 pub fn is_unit(&self) -> bool {
1622 if let TyKind::Tup(ref tys) = *self {
1630 /// Syntax used to declare a trait object.
1631 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1632 pub enum TraitObjectSyntax {
1637 /// Inline assembly dialect.
1639 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1640 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1641 pub enum AsmDialect {
1646 /// Inline assembly.
1648 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1649 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1650 pub struct InlineAsmOutput {
1651 pub constraint: Symbol,
1654 pub is_indirect: bool,
1657 /// Inline assembly.
1659 /// E.g., `asm!("NOP");`.
1660 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1661 pub struct InlineAsm {
1663 pub asm_str_style: StrStyle,
1664 pub outputs: Vec<InlineAsmOutput>,
1665 pub inputs: Vec<(Symbol, P<Expr>)>,
1666 pub clobbers: Vec<Symbol>,
1668 pub alignstack: bool,
1669 pub dialect: AsmDialect,
1670 pub ctxt: SyntaxContext,
1673 /// An argument in a function header.
1675 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1676 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1683 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1685 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1686 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1688 /// `self`, `mut self`
1690 /// `&'lt self`, `&'lt mut self`
1691 Region(Option<Lifetime>, Mutability),
1692 /// `self: TYPE`, `mut self: TYPE`
1693 Explicit(P<Ty>, Mutability),
1696 pub type ExplicitSelf = Spanned<SelfKind>;
1699 pub fn to_self(&self) -> Option<ExplicitSelf> {
1700 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1701 if ident.name == keywords::SelfLower.name() {
1702 return match self.ty.node {
1703 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1704 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1705 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1708 self.pat.span.to(self.ty.span),
1709 SelfKind::Explicit(self.ty.clone(), mutbl),
1717 pub fn is_self(&self) -> bool {
1718 if let PatKind::Ident(_, ident, _) = self.pat.node {
1719 ident.name == keywords::SelfLower.name()
1725 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1726 let span = eself.span.to(eself_ident.span);
1727 let infer_ty = P(Ty {
1729 node: TyKind::ImplicitSelf,
1732 let arg = |mutbl, ty| Arg {
1735 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1742 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1743 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1744 SelfKind::Region(lt, mutbl) => arg(
1745 Mutability::Immutable,
1762 /// Header (not the body) of a function declaration.
1764 /// E.g., `fn foo(bar: baz)`.
1765 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1767 pub inputs: Vec<Arg>,
1768 pub output: FunctionRetTy,
1773 pub fn get_self(&self) -> Option<ExplicitSelf> {
1774 self.inputs.get(0).and_then(Arg::to_self)
1776 pub fn has_self(&self) -> bool {
1777 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1781 /// Is the trait definition an auto trait?
1782 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1788 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1794 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1798 return_impl_trait_id: NodeId,
1804 pub fn is_async(self) -> bool {
1805 if let IsAsync::Async { .. } = self {
1812 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1813 pub fn opt_return_id(self) -> Option<NodeId> {
1816 return_impl_trait_id,
1818 } => Some(return_impl_trait_id),
1819 IsAsync::NotAsync => None,
1824 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1825 pub enum Constness {
1830 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1831 pub enum Defaultness {
1836 impl fmt::Display for Unsafety {
1837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1840 Unsafety::Normal => "normal",
1841 Unsafety::Unsafe => "unsafe",
1848 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1849 pub enum ImplPolarity {
1850 /// `impl Trait for Type`
1852 /// `impl !Trait for Type`
1856 impl fmt::Debug for ImplPolarity {
1857 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1859 ImplPolarity::Positive => "positive".fmt(f),
1860 ImplPolarity::Negative => "negative".fmt(f),
1865 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1866 pub enum FunctionRetTy {
1867 /// Return type is not specified.
1869 /// Functions default to `()` and closures default to inference.
1870 /// Span points to where return type would be inserted.
1872 /// Everything else.
1876 impl FunctionRetTy {
1877 pub fn span(&self) -> Span {
1879 FunctionRetTy::Default(span) => span,
1880 FunctionRetTy::Ty(ref ty) => ty.span,
1885 /// Module declaration.
1887 /// E.g., `mod foo;` or `mod foo { .. }`.
1888 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1890 /// A span from the first token past `{` to the last token until `}`.
1891 /// For `mod foo;`, the inner span ranges from the first token
1892 /// to the last token in the external file.
1894 pub items: Vec<P<Item>>,
1895 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
1899 /// Foreign module declaration.
1901 /// E.g., `extern { .. }` or `extern C { .. }`.
1902 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1903 pub struct ForeignMod {
1905 pub items: Vec<ForeignItem>,
1908 /// Global inline assembly.
1910 /// Also known as "module-level assembly" or "file-scoped assembly".
1911 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1912 pub struct GlobalAsm {
1914 pub ctxt: SyntaxContext,
1917 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1918 pub struct EnumDef {
1919 pub variants: Vec<Variant>,
1922 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1923 pub struct Variant_ {
1925 pub attrs: Vec<Attribute>,
1926 pub data: VariantData,
1927 /// Explicit discriminant, e.g., `Foo = 1`.
1928 pub disr_expr: Option<AnonConst>,
1931 pub type Variant = Spanned<Variant_>;
1933 /// Part of `use` item to the right of its prefix.
1934 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1935 pub enum UseTreeKind {
1936 /// `use prefix` or `use prefix as rename`
1938 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1940 Simple(Option<Ident>, NodeId, NodeId),
1941 /// `use prefix::{...}`
1942 Nested(Vec<(UseTree, NodeId)>),
1947 /// A tree of paths sharing common prefixes.
1948 /// Used in `use` items both at top-level and inside of braces in import groups.
1949 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1950 pub struct UseTree {
1952 pub kind: UseTreeKind,
1957 pub fn ident(&self) -> Ident {
1959 UseTreeKind::Simple(Some(rename), ..) => rename,
1960 UseTreeKind::Simple(None, ..) => {
1964 .expect("empty prefix in a simple import")
1967 _ => panic!("`UseTree::ident` can only be used on a simple import"),
1972 /// Distinguishes between `Attribute`s that decorate items and Attributes that
1973 /// are contained as statements within items. These two cases need to be
1974 /// distinguished for pretty-printing.
1975 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1976 pub enum AttrStyle {
1982 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
1984 pub struct AttrId(pub usize);
1986 impl Idx for AttrId {
1987 fn new(idx: usize) -> Self {
1990 fn index(self) -> usize {
1995 /// Metadata associated with an item.
1996 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
1997 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1998 pub struct Attribute {
2000 pub style: AttrStyle,
2002 pub tokens: TokenStream,
2003 pub is_sugared_doc: bool,
2007 /// `TraitRef`s appear in impls.
2009 /// Resolve maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2010 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2011 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2012 /// same as the impl's node-id).
2013 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2014 pub struct TraitRef {
2019 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2020 pub struct PolyTraitRef {
2021 /// The `'a` in `<'a> Foo<&'a T>`
2022 pub bound_generic_params: Vec<GenericParam>,
2024 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2025 pub trait_ref: TraitRef,
2031 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2033 bound_generic_params: generic_params,
2034 trait_ref: TraitRef {
2036 ref_id: DUMMY_NODE_ID,
2043 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2044 pub enum CrateSugar {
2045 /// Source is `pub(crate)`.
2048 /// Source is (just) `crate`.
2052 pub type Visibility = Spanned<VisibilityKind>;
2054 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2055 pub enum VisibilityKind {
2058 Restricted { path: P<Path>, id: NodeId },
2062 impl VisibilityKind {
2063 pub fn is_pub(&self) -> bool {
2064 if let VisibilityKind::Public = *self {
2072 /// Field of a struct.
2074 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2075 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2076 pub struct StructField {
2078 pub ident: Option<Ident>,
2079 pub vis: Visibility,
2082 pub attrs: Vec<Attribute>,
2085 /// Fields and Ids of enum variants and structs
2087 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2088 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2089 /// One shared Id can be successfully used for these two purposes.
2090 /// Id of the whole enum lives in `Item`.
2092 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2093 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2094 /// the variant itself" from enum variants.
2095 /// Id of the whole struct lives in `Item`.
2096 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2097 pub enum VariantData {
2100 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2101 Struct(Vec<StructField>, NodeId),
2104 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2105 Tuple(Vec<StructField>, NodeId),
2108 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2113 pub fn fields(&self) -> &[StructField] {
2115 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2119 pub fn id(&self) -> NodeId {
2121 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2124 pub fn is_struct(&self) -> bool {
2125 if let VariantData::Struct(..) = *self {
2131 pub fn is_tuple(&self) -> bool {
2132 if let VariantData::Tuple(..) = *self {
2138 pub fn is_unit(&self) -> bool {
2139 if let VariantData::Unit(..) = *self {
2149 /// The name might be a dummy name in case of anonymous items.
2150 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2153 pub attrs: Vec<Attribute>,
2156 pub vis: Visibility,
2159 /// Original tokens this item was parsed from. This isn't necessarily
2160 /// available for all items, although over time more and more items should
2161 /// have this be `Some`. Right now this is primarily used for procedural
2162 /// macros, notably custom attributes.
2164 /// Note that the tokens here do not include the outer attributes, but will
2165 /// include inner attributes.
2166 pub tokens: Option<TokenStream>,
2170 /// Return the span that encompasses the attributes.
2171 pub fn span_with_attributes(&self) -> Span {
2172 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span()))
2176 /// A function header.
2178 /// All the information between the visibility and the name of the function is
2179 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2180 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2181 pub struct FnHeader {
2182 pub unsafety: Unsafety,
2183 pub asyncness: IsAsync,
2184 pub constness: Spanned<Constness>,
2188 impl Default for FnHeader {
2189 fn default() -> FnHeader {
2191 unsafety: Unsafety::Normal,
2192 asyncness: IsAsync::NotAsync,
2193 constness: dummy_spanned(Constness::NotConst),
2199 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2201 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2203 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2204 ExternCrate(Option<Name>),
2205 /// A use declaration (`use` or `pub use`) item.
2207 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2209 /// A static item (`static` or `pub static`).
2211 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2212 Static(P<Ty>, Mutability, P<Expr>),
2213 /// A constant item (`const` or `pub const`).
2215 /// E.g., `const FOO: i32 = 42;`.
2216 Const(P<Ty>, P<Expr>),
2217 /// A function declaration (`fn` or `pub fn`).
2219 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2220 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2221 /// A module declaration (`mod` or `pub mod`).
2223 /// E.g., `mod foo;` or `mod foo { .. }`.
2225 /// An external module (`extern` or `pub extern`).
2227 /// E.g., `extern {}` or `extern "C" {}`.
2228 ForeignMod(ForeignMod),
2229 /// Module-level inline assembly (from `global_asm!()`).
2230 GlobalAsm(P<GlobalAsm>),
2231 /// A type alias (`type` or `pub type`).
2233 /// E.g., `type Foo = Bar<u8>;`.
2234 Ty(P<Ty>, Generics),
2235 /// An existential type declaration (`existential type`).
2237 /// E.g., `existential type Foo: Bar + Boo;`.
2238 Existential(GenericBounds, Generics),
2239 /// An enum definition (`enum` or `pub enum`).
2241 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2242 Enum(EnumDef, Generics),
2243 /// A struct definition (`struct` or `pub struct`).
2245 /// E.g., `struct Foo<A> { x: A }`.
2246 Struct(VariantData, Generics),
2247 /// A union definition (`union` or `pub union`).
2249 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2250 Union(VariantData, Generics),
2251 /// A Trait declaration (`trait` or `pub trait`).
2253 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2254 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2257 /// E.g., `trait Foo = Bar + Quux;`.
2258 TraitAlias(Generics, GenericBounds),
2259 /// An implementation.
2261 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2267 Option<TraitRef>, // (optional) trait this impl implements
2271 /// A macro invocation.
2273 /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2276 /// A macro definition.
2281 pub fn descriptive_variant(&self) -> &str {
2283 ItemKind::ExternCrate(..) => "extern crate",
2284 ItemKind::Use(..) => "use",
2285 ItemKind::Static(..) => "static item",
2286 ItemKind::Const(..) => "constant item",
2287 ItemKind::Fn(..) => "function",
2288 ItemKind::Mod(..) => "module",
2289 ItemKind::ForeignMod(..) => "foreign module",
2290 ItemKind::GlobalAsm(..) => "global asm",
2291 ItemKind::Ty(..) => "type alias",
2292 ItemKind::Existential(..) => "existential type",
2293 ItemKind::Enum(..) => "enum",
2294 ItemKind::Struct(..) => "struct",
2295 ItemKind::Union(..) => "union",
2296 ItemKind::Trait(..) => "trait",
2297 ItemKind::TraitAlias(..) => "trait alias",
2298 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2303 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2304 pub struct ForeignItem {
2306 pub attrs: Vec<Attribute>,
2307 pub node: ForeignItemKind,
2310 pub vis: Visibility,
2313 /// An item within an `extern` block.
2314 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2315 pub enum ForeignItemKind {
2316 /// A foreign function.
2317 Fn(P<FnDecl>, Generics),
2318 /// A foreign static item (`static ext: u8`), with optional mutability.
2319 /// (The boolean is `true` for mutable items).
2320 Static(P<Ty>, bool),
2323 /// A macro invocation.
2327 impl ForeignItemKind {
2328 pub fn descriptive_variant(&self) -> &str {
2330 ForeignItemKind::Fn(..) => "foreign function",
2331 ForeignItemKind::Static(..) => "foreign static item",
2332 ForeignItemKind::Ty => "foreign type",
2333 ForeignItemKind::Macro(..) => "macro in foreign module",
2343 // Are ASTs encodable?
2345 fn check_asts_encodable() {
2346 fn assert_encodable<T: serialize::Encodable>() {}
2347 assert_encodable::<Crate>();