1 // The Rust abstract syntax tree.
3 pub use self::GenericArgs::*;
4 pub use self::UnsafeSource::*;
5 pub use symbol::{Ident, Symbol as Name};
6 pub use util::parser::ExprPrecedence;
8 use ext::hygiene::{Mark, SyntaxContext};
11 use rustc_data_structures::indexed_vec::Idx;
12 #[cfg(target_arch = "x86_64")]
13 use rustc_data_structures::static_assert;
14 use rustc_target::spec::abi::Abi;
15 use source_map::{dummy_spanned, respan, Spanned};
16 use symbol::{keywords, Symbol};
17 use syntax_pos::{Span, DUMMY_SP};
18 use tokenstream::TokenStream;
21 use rustc_data_structures::fx::FxHashSet;
22 use rustc_data_structures::sync::Lrc;
23 use serialize::{self, Decoder, Encoder};
26 pub use rustc_target::abi::FloatTy;
28 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
33 impl fmt::Debug for Label {
34 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
35 write!(f, "label({:?})", self.ident)
39 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
45 impl fmt::Debug for Lifetime {
46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51 pprust::lifetime_to_string(self)
56 /// A "Path" is essentially Rust's notion of a name.
58 /// It's represented as a sequence of identifiers,
59 /// along with a bunch of supporting information.
61 /// E.g., `std::cmp::PartialEq`.
62 #[derive(Clone, RustcEncodable, RustcDecodable)]
65 /// The segments in the path: the things separated by `::`.
66 /// Global paths begin with `keywords::PathRoot`.
67 pub segments: Vec<PathSegment>,
70 impl<'a> PartialEq<&'a str> for Path {
71 fn eq(&self, string: &&'a str) -> bool {
72 self.segments.len() == 1 && self.segments[0].ident.name == *string
76 impl fmt::Debug for Path {
77 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78 write!(f, "path({})", pprust::path_to_string(self))
82 impl fmt::Display for Path {
83 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84 write!(f, "{}", pprust::path_to_string(self))
89 // Convert a span and an identifier to the corresponding
91 pub fn from_ident(ident: Ident) -> Path {
93 segments: vec![PathSegment::from_ident(ident)],
98 pub fn is_global(&self) -> bool {
99 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
103 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
105 /// E.g., `std`, `String` or `Box<T>`.
106 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
107 pub struct PathSegment {
108 /// The identifier portion of this path segment.
113 /// Type/lifetime parameters attached to this path. They come in
114 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
115 /// `None` means that no parameter list is supplied (`Path`),
116 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
117 /// but it can be empty (`Path<>`).
118 /// `P` is used as a size optimization for the common case with no parameters.
119 pub args: Option<P<GenericArgs>>,
123 pub fn from_ident(ident: Ident) -> Self {
124 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
126 pub fn path_root(span: Span) -> Self {
127 PathSegment::from_ident(Ident::new(keywords::PathRoot.name(), span))
131 /// Arguments of a path segment.
133 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
134 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
135 pub enum GenericArgs {
136 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
137 AngleBracketed(AngleBracketedArgs),
138 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
139 Parenthesized(ParenthesizedArgs),
143 pub fn is_parenthesized(&self) -> bool {
145 Parenthesized(..) => true,
150 pub fn is_angle_bracketed(&self) -> bool {
152 AngleBracketed(..) => true,
157 pub fn span(&self) -> Span {
159 AngleBracketed(ref data) => data.span,
160 Parenthesized(ref data) => data.span,
165 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
166 pub enum GenericArg {
171 /// A path like `Foo<'a, T>`
172 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
173 pub struct AngleBracketedArgs {
176 /// The arguments for this path segment.
177 pub args: Vec<GenericArg>,
178 /// Bindings (equality constraints) on associated types, if present.
180 /// E.g., `Foo<A=Bar>`.
181 pub bindings: Vec<TypeBinding>,
184 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
185 fn into(self) -> Option<P<GenericArgs>> {
186 Some(P(GenericArgs::AngleBracketed(self)))
190 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
191 fn into(self) -> Option<P<GenericArgs>> {
192 Some(P(GenericArgs::Parenthesized(self)))
196 /// A path like `Foo(A,B) -> C`
197 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
198 pub struct ParenthesizedArgs {
203 pub inputs: Vec<P<Ty>>,
206 pub output: Option<P<Ty>>,
209 impl ParenthesizedArgs {
210 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
213 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
219 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
221 use rustc_data_structures::indexed_vec::Idx;
225 DEBUG_FORMAT = "NodeId({})"
230 pub use self::node_id_inner::NodeId;
233 pub fn placeholder_from_mark(mark: Mark) -> Self {
234 NodeId::from_u32(mark.as_u32())
237 pub fn placeholder_to_mark(self) -> Mark {
238 Mark::from_u32(self.as_u32())
242 impl fmt::Display for NodeId {
243 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
244 fmt::Display::fmt(&self.as_u32(), f)
248 impl serialize::UseSpecializedEncodable for NodeId {
249 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
250 s.emit_u32(self.as_u32())
254 impl serialize::UseSpecializedDecodable for NodeId {
255 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
256 d.read_u32().map(NodeId::from_u32)
260 /// Node id used to represent the root of the crate.
261 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
263 /// When parsing and doing expansions, we initially give all AST nodes this AST
264 /// node value. Then later, in the renumber pass, we renumber them to have
265 /// small, positive ids.
266 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
268 /// A modifier on a bound, currently this is only used for `?Sized`, where the
269 /// modifier is `Maybe`. Negative bounds should also be handled here.
270 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
271 pub enum TraitBoundModifier {
276 /// The AST represents all type param bounds as types.
277 /// `typeck::collect::compute_bounds` matches these against
278 /// the "special" built-in traits (see `middle::lang_items`) and
279 /// detects `Copy`, `Send` and `Sync`.
280 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
281 pub enum GenericBound {
282 Trait(PolyTraitRef, TraitBoundModifier),
287 pub fn span(&self) -> Span {
289 &GenericBound::Trait(ref t, ..) => t.span,
290 &GenericBound::Outlives(ref l) => l.ident.span,
295 pub type GenericBounds = Vec<GenericBound>;
297 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
298 pub enum GenericParamKind {
299 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
302 default: Option<P<Ty>>,
306 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
307 pub struct GenericParam {
310 pub attrs: ThinVec<Attribute>,
311 pub bounds: GenericBounds,
313 pub kind: GenericParamKind,
316 /// Represents lifetime, type and const parameters attached to a declaration of
317 /// a function, enum, trait, etc.
318 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
319 pub struct Generics {
320 pub params: Vec<GenericParam>,
321 pub where_clause: WhereClause,
325 impl Default for Generics {
326 /// Creates an instance of `Generics`.
327 fn default() -> Generics {
330 where_clause: WhereClause {
332 predicates: Vec::new(),
340 /// A `where` clause in a definition
341 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
342 pub struct WhereClause {
344 pub predicates: Vec<WherePredicate>,
348 /// A single predicate in a `where` clause
349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
350 pub enum WherePredicate {
351 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
352 BoundPredicate(WhereBoundPredicate),
353 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
354 RegionPredicate(WhereRegionPredicate),
355 /// An equality predicate (unsupported).
356 EqPredicate(WhereEqPredicate),
359 impl WherePredicate {
360 pub fn span(&self) -> Span {
362 &WherePredicate::BoundPredicate(ref p) => p.span,
363 &WherePredicate::RegionPredicate(ref p) => p.span,
364 &WherePredicate::EqPredicate(ref p) => p.span,
371 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
372 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
373 pub struct WhereBoundPredicate {
375 /// Any generics from a `for` binding
376 pub bound_generic_params: Vec<GenericParam>,
377 /// The type being bounded
378 pub bounded_ty: P<Ty>,
379 /// Trait and lifetime bounds (`Clone+Send+'static`)
380 pub bounds: GenericBounds,
383 /// A lifetime predicate.
385 /// E.g., `'a: 'b + 'c`.
386 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
387 pub struct WhereRegionPredicate {
389 pub lifetime: Lifetime,
390 pub bounds: GenericBounds,
393 /// An equality predicate (unsupported).
396 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
397 pub struct WhereEqPredicate {
404 /// The set of `MetaItem`s that define the compilation environment of the crate,
405 /// used to drive conditional compilation.
406 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
408 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
411 pub attrs: Vec<Attribute>,
415 /// A spanned compile-time attribute list item.
416 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
418 /// Possible values inside of compile-time attribute lists.
420 /// E.g., the '..' in `#[name(..)]`.
421 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
422 pub enum NestedMetaItemKind {
423 /// A full MetaItem, for recursive meta items.
427 /// E.g., `"foo"`, `64`, `true`.
431 /// A spanned compile-time attribute item.
433 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
434 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
435 pub struct MetaItem {
437 pub node: MetaItemKind,
441 /// A compile-time attribute item.
443 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
444 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
445 pub enum MetaItemKind {
448 /// E.g., `test` as in `#[test]`.
452 /// E.g., `derive(..)` as in `#[derive(..)]`.
453 List(Vec<NestedMetaItem>),
454 /// Name value meta item.
456 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
460 /// A Block (`{ .. }`).
462 /// E.g., `{ .. }` as in `fn foo() { .. }`.
463 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
465 /// Statements in a block
466 pub stmts: Vec<Stmt>,
468 /// Distinguishes between `unsafe { ... }` and `{ ... }`
469 pub rules: BlockCheckMode,
473 #[derive(Clone, RustcEncodable, RustcDecodable)]
480 impl fmt::Debug for Pat {
481 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
482 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
487 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
488 let node = match &self.node {
489 PatKind::Wild => TyKind::Infer,
490 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
491 TyKind::Path(None, Path::from_ident(*ident))
493 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
494 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
495 PatKind::Ref(pat, mutbl) => pat
497 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
498 PatKind::Slice(pats, None, _) if pats.len() == 1 => {
499 pats[0].to_ty().map(TyKind::Slice)?
501 PatKind::Tuple(pats, None) => {
502 let mut tys = Vec::with_capacity(pats.len());
503 // FIXME(#48994) - could just be collected into an Option<Vec>
505 tys.push(pat.to_ty()?);
519 pub fn walk<F>(&self, it: &mut F) -> bool
521 F: FnMut(&Pat) -> bool,
528 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
529 PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
530 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
531 s.iter().all(|p| p.walk(it))
533 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
534 PatKind::Slice(ref before, ref slice, ref after) => {
535 before.iter().all(|p| p.walk(it))
536 && slice.iter().all(|p| p.walk(it))
537 && after.iter().all(|p| p.walk(it))
544 | PatKind::Mac(_) => true,
549 /// A single field in a struct pattern
551 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
552 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
553 /// except is_shorthand is true
554 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
555 pub struct FieldPat {
556 /// The identifier for the field
558 /// The pattern the field is destructured to
560 pub is_shorthand: bool,
561 pub attrs: ThinVec<Attribute>,
564 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
565 pub enum BindingMode {
570 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
572 Included(RangeSyntax),
576 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
577 pub enum RangeSyntax {
582 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
584 /// Represents a wildcard pattern (`_`).
587 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
588 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
589 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
590 /// during name resolution.
591 Ident(BindingMode, Ident, Option<P<Pat>>),
593 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
594 /// The `bool` is `true` in the presence of a `..`.
595 Struct(Path, Vec<Spanned<FieldPat>>, bool),
597 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
598 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
599 /// `0 <= position <= subpats.len()`.
600 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
602 /// A possibly qualified path pattern.
603 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
604 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
605 /// only legally refer to associated constants.
606 Path(Option<QSelf>, Path),
608 /// A tuple pattern (`(a, b)`).
609 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
610 /// `0 <= position <= subpats.len()`.
611 Tuple(Vec<P<Pat>>, Option<usize>),
614 /// A reference pattern (e.g., `&mut (a, b)`).
615 Ref(P<Pat>, Mutability),
618 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
619 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
620 /// `[a, b, ..i, y, z]` is represented as:
621 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
622 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
623 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
625 /// A macro pattern; pre-expansion.
630 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
632 pub enum Mutability {
637 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
639 /// The `+` operator (addition)
641 /// The `-` operator (subtraction)
643 /// The `*` operator (multiplication)
645 /// The `/` operator (division)
647 /// The `%` operator (modulus)
649 /// The `&&` operator (logical and)
651 /// The `||` operator (logical or)
653 /// The `^` operator (bitwise xor)
655 /// The `&` operator (bitwise and)
657 /// The `|` operator (bitwise or)
659 /// The `<<` operator (shift left)
661 /// The `>>` operator (shift right)
663 /// The `==` operator (equality)
665 /// The `<` operator (less than)
667 /// The `<=` operator (less than or equal to)
669 /// The `!=` operator (not equal to)
671 /// The `>=` operator (greater than or equal to)
673 /// The `>` operator (greater than)
678 pub fn to_string(&self) -> &'static str {
679 use self::BinOpKind::*;
701 pub fn lazy(&self) -> bool {
703 BinOpKind::And | BinOpKind::Or => true,
708 pub fn is_shift(&self) -> bool {
710 BinOpKind::Shl | BinOpKind::Shr => true,
715 pub fn is_comparison(&self) -> bool {
716 use self::BinOpKind::*;
718 Eq | Lt | Le | Ne | Gt | Ge => true,
719 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
723 /// Returns `true` if the binary operator takes its arguments by value
724 pub fn is_by_value(&self) -> bool {
725 !self.is_comparison()
729 pub type BinOp = Spanned<BinOpKind>;
731 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
733 /// The `*` operator for dereferencing
735 /// The `!` operator for logical inversion
737 /// The `-` operator for negation
742 /// Returns `true` if the unary operator takes its argument by value
743 pub fn is_by_value(u: UnOp) -> bool {
745 UnOp::Neg | UnOp::Not => true,
750 pub fn to_string(op: UnOp) -> &'static str {
760 #[derive(Clone, RustcEncodable, RustcDecodable)]
768 pub fn add_trailing_semicolon(mut self) -> Self {
769 self.node = match self.node {
770 StmtKind::Expr(expr) => StmtKind::Semi(expr),
771 StmtKind::Mac(mac) => {
772 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
779 pub fn is_item(&self) -> bool {
781 StmtKind::Item(_) => true,
786 pub fn is_expr(&self) -> bool {
788 StmtKind::Expr(_) => true,
794 impl fmt::Debug for Stmt {
795 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
800 pprust::stmt_to_string(self)
805 #[derive(Clone, RustcEncodable, RustcDecodable)]
807 /// A local (let) binding.
810 /// An item definition.
813 /// Expr without trailing semi-colon.
815 /// Expr with a trailing semi-colon.
818 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
821 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
822 pub enum MacStmtStyle {
823 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
824 /// `foo!(...);`, `foo![...];`).
826 /// The macro statement had braces (e.g., `foo! { ... }`).
828 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
829 /// `foo!(...)`). All of these will end up being converted into macro
834 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
835 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
838 pub ty: Option<P<Ty>>,
839 /// Initializer expression to set the value, if any.
840 pub init: Option<P<Expr>>,
843 pub attrs: ThinVec<Attribute>,
846 /// An arm of a 'match'.
848 /// E.g., `0..=10 => { println!("match!") }` as in
852 /// 0..=10 => { println!("match!") },
853 /// _ => { println!("no match!") },
856 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
858 pub attrs: Vec<Attribute>,
859 pub pats: Vec<P<Pat>>,
860 pub guard: Option<Guard>,
864 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
869 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
874 pub is_shorthand: bool,
875 pub attrs: ThinVec<Attribute>,
878 pub type SpannedIdent = Spanned<Ident>;
880 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
881 pub enum BlockCheckMode {
883 Unsafe(UnsafeSource),
886 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
887 pub enum UnsafeSource {
892 /// A constant (expression) that's not an item or associated item,
893 /// but needs its own `DefId` for type-checking, const-eval, etc.
894 /// These are usually found nested inside types (e.g., array lengths)
895 /// or expressions (e.g., repeat counts), and also used to define
896 /// explicit discriminant values for enum variants.
897 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
898 pub struct AnonConst {
904 #[derive(Clone, RustcEncodable, RustcDecodable)]
909 pub attrs: ThinVec<Attribute>,
912 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
913 #[cfg(target_arch = "x86_64")]
914 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 88);
917 /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
919 pub fn returns(&self) -> bool {
920 if let ExprKind::Block(ref block, _) = self.node {
921 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
923 Some(&StmtKind::Expr(_)) => true,
924 Some(&StmtKind::Semi(ref expr)) => {
925 if let ExprKind::Ret(_) = expr.node {
926 // last statement is explicit return
932 // This is a block that doesn't end in either an implicit or explicit return
936 // This is not a block, it is a value
941 fn to_bound(&self) -> Option<GenericBound> {
943 ExprKind::Path(None, path) => Some(GenericBound::Trait(
944 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
945 TraitBoundModifier::None,
951 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
952 let node = match &self.node {
953 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
954 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
955 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
956 ExprKind::AddrOf(mutbl, expr) => expr
958 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
959 ExprKind::Repeat(expr, expr_len) => {
960 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
962 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
963 ExprKind::Tup(exprs) => {
966 .map(|expr| expr.to_ty())
967 .collect::<Option<Vec<_>>>()?;
970 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
971 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
972 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
987 pub fn precedence(&self) -> ExprPrecedence {
989 ExprKind::Box(_) => ExprPrecedence::Box,
990 ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
991 ExprKind::Array(_) => ExprPrecedence::Array,
992 ExprKind::Call(..) => ExprPrecedence::Call,
993 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
994 ExprKind::Tup(_) => ExprPrecedence::Tup,
995 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
996 ExprKind::Unary(..) => ExprPrecedence::Unary,
997 ExprKind::Lit(_) => ExprPrecedence::Lit,
998 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
999 ExprKind::If(..) => ExprPrecedence::If,
1000 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
1001 ExprKind::While(..) => ExprPrecedence::While,
1002 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
1003 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1004 ExprKind::Loop(..) => ExprPrecedence::Loop,
1005 ExprKind::Match(..) => ExprPrecedence::Match,
1006 ExprKind::Closure(..) => ExprPrecedence::Closure,
1007 ExprKind::Block(..) => ExprPrecedence::Block,
1008 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1009 ExprKind::Async(..) => ExprPrecedence::Async,
1010 ExprKind::Assign(..) => ExprPrecedence::Assign,
1011 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1012 ExprKind::Field(..) => ExprPrecedence::Field,
1013 ExprKind::Index(..) => ExprPrecedence::Index,
1014 ExprKind::Range(..) => ExprPrecedence::Range,
1015 ExprKind::Path(..) => ExprPrecedence::Path,
1016 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1017 ExprKind::Break(..) => ExprPrecedence::Break,
1018 ExprKind::Continue(..) => ExprPrecedence::Continue,
1019 ExprKind::Ret(..) => ExprPrecedence::Ret,
1020 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1021 ExprKind::Mac(..) => ExprPrecedence::Mac,
1022 ExprKind::Struct(..) => ExprPrecedence::Struct,
1023 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1024 ExprKind::Paren(..) => ExprPrecedence::Paren,
1025 ExprKind::Try(..) => ExprPrecedence::Try,
1026 ExprKind::Yield(..) => ExprPrecedence::Yield,
1027 ExprKind::Err => ExprPrecedence::Err,
1032 impl fmt::Debug for Expr {
1033 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1034 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1038 /// Limit types of a range (inclusive or exclusive)
1039 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1040 pub enum RangeLimits {
1041 /// Inclusive at the beginning, exclusive at the end
1043 /// Inclusive at the beginning and end
1047 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1049 /// A `box x` expression.
1051 /// First expr is the place; second expr is the value.
1052 ObsoleteInPlace(P<Expr>, P<Expr>),
1053 /// An array (`[a, b, c, d]`)
1054 Array(Vec<P<Expr>>),
1057 /// The first field resolves to the function itself,
1058 /// and the second field is the list of arguments.
1059 /// This also represents calling the constructor of
1060 /// tuple-like ADTs such as tuple structs and enum variants.
1061 Call(P<Expr>, Vec<P<Expr>>),
1062 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1064 /// The `PathSegment` represents the method name and its generic arguments
1065 /// (within the angle brackets).
1066 /// The first element of the vector of an `Expr` is the expression that evaluates
1067 /// to the object on which the method is being called on (the receiver),
1068 /// and the remaining elements are the rest of the arguments.
1069 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1070 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1071 MethodCall(PathSegment, Vec<P<Expr>>),
1072 /// A tuple (e.g., `(a, b, c, d)`).
1074 /// A binary operation (e.g., `a + b`, `a * b`).
1075 Binary(BinOp, P<Expr>, P<Expr>),
1076 /// A unary operation (e.g., `!x`, `*x`).
1077 Unary(UnOp, P<Expr>),
1078 /// A literal (e.g., `1`, `"foo"`).
1080 /// A cast (e.g., `foo as f64`).
1081 Cast(P<Expr>, P<Ty>),
1082 Type(P<Expr>, P<Ty>),
1083 /// An `if` block, with an optional `else` block.
1085 /// `if expr { block } else { expr }`
1086 If(P<Expr>, P<Block>, Option<P<Expr>>),
1087 /// An `if let` expression with an optional else block
1089 /// `if let pat = expr { block } else { expr }`
1091 /// This is desugared to a `match` expression.
1092 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1093 /// A while loop, with an optional label
1095 /// `'label: while expr { block }`
1096 While(P<Expr>, P<Block>, Option<Label>),
1097 /// A `while let` loop, with an optional label.
1099 /// `'label: while let pat = expr { block }`
1101 /// This is desugared to a combination of `loop` and `match` expressions.
1102 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1103 /// A `for` loop, with an optional label.
1105 /// `'label: for pat in expr { block }`
1107 /// This is desugared to a combination of `loop` and `match` expressions.
1108 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1109 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1111 /// `'label: loop { block }`
1112 Loop(P<Block>, Option<Label>),
1113 /// A `match` block.
1114 Match(P<Expr>, Vec<Arm>),
1115 /// A closure (e.g., `move |a, b, c| a + b + c`).
1117 /// The final span is the span of the argument block `|...|`.
1118 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1119 /// A block (`'label: { ... }`).
1120 Block(P<Block>, Option<Label>),
1121 /// An async block (`async move { ... }`).
1123 /// The `NodeId` is the `NodeId` for the closure that results from
1124 /// desugaring an async block, just like the NodeId field in the
1125 /// `IsAsync` enum. This is necessary in order to create a def for the
1126 /// closure which can be used as a parent of any child defs. Defs
1127 /// created during lowering cannot be made the parent of any other
1128 /// preexisting defs.
1129 Async(CaptureBy, NodeId, P<Block>),
1130 /// A try block (`try { ... }`).
1133 /// An assignment (`a = foo()`).
1134 Assign(P<Expr>, P<Expr>),
1135 /// An assignment with an operator.
1138 AssignOp(BinOp, P<Expr>, P<Expr>),
1139 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1140 Field(P<Expr>, Ident),
1141 /// An indexing operation (e.g., `foo[2]`).
1142 Index(P<Expr>, P<Expr>),
1143 /// A range (e.g., `1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`).
1144 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1146 /// Variable reference, possibly containing `::` and/or type
1147 /// parameters (e.g., `foo::bar::<baz>`).
1149 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1150 Path(Option<QSelf>, Path),
1152 /// A referencing operation (`&a` or `&mut a`).
1153 AddrOf(Mutability, P<Expr>),
1154 /// A `break`, with an optional label to break, and an optional expression.
1155 Break(Option<Label>, Option<P<Expr>>),
1156 /// A `continue`, with an optional label.
1157 Continue(Option<Label>),
1158 /// A `return`, with an optional value to be returned.
1159 Ret(Option<P<Expr>>),
1161 /// Output of the `asm!()` macro.
1162 InlineAsm(P<InlineAsm>),
1164 /// A macro invocation; pre-expansion.
1167 /// A struct literal expression.
1169 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1170 /// where `base` is the `Option<Expr>`.
1171 Struct(Path, Vec<Field>, Option<P<Expr>>),
1173 /// An array literal constructed from one repeated element.
1175 /// E.g., `[1; 5]`. The expression is the element to be
1176 /// repeated; the constant is the number of times to repeat it.
1177 Repeat(P<Expr>, AnonConst),
1179 /// No-op: used solely so we can pretty-print faithfully.
1182 /// A try expression (`expr?`).
1185 /// A `yield`, with an optional value to be yielded.
1186 Yield(Option<P<Expr>>),
1188 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1192 /// The explicit `Self` type in a "qualified path". The actual
1193 /// path, including the trait and the associated item, is stored
1194 /// separately. `position` represents the index of the associated
1195 /// item qualified with this `Self` type.
1197 /// ```ignore (only-for-syntax-highlight)
1198 /// <Vec<T> as a::b::Trait>::AssociatedItem
1199 /// ^~~~~ ~~~~~~~~~~~~~~^
1202 /// <Vec<T>>::AssociatedItem
1206 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1210 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1211 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1212 /// 0`, this is an empty span.
1213 pub path_span: Span,
1214 pub position: usize,
1217 /// A capture clause.
1218 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1219 pub enum CaptureBy {
1224 /// The movability of a generator / closure literal.
1225 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1226 pub enum Movability {
1231 pub type Mac = Spanned<Mac_>;
1233 /// Represents a macro invocation. The `Path` indicates which macro
1234 /// is being invoked, and the vector of token-trees contains the source
1235 /// of the macro invocation.
1237 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1238 /// stored in the enclosing item.
1239 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1242 pub delim: MacDelimiter,
1243 pub tts: TokenStream,
1246 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1247 pub enum MacDelimiter {
1254 pub fn stream(&self) -> TokenStream {
1259 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1260 pub struct MacroDef {
1261 pub tokens: TokenStream,
1266 pub fn stream(&self) -> TokenStream {
1267 self.tokens.clone().into()
1271 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1273 /// A regular string, like `"foo"`.
1275 /// A raw string, like `r##"foo"##`.
1277 /// The value is the number of `#` symbols used.
1282 pub type Lit = Spanned<LitKind>;
1284 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1285 pub enum LitIntType {
1293 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1294 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1296 /// A string literal (`"foo"`).
1297 Str(Symbol, StrStyle),
1298 /// A byte string (`b"foo"`).
1299 ByteStr(Lrc<Vec<u8>>),
1300 /// A byte char (`b'f'`).
1302 /// A character literal (`'a'`).
1304 /// An integer literal (`1`).
1305 Int(u128, LitIntType),
1306 /// A float literal (`1f64` or `1E10f64`).
1307 Float(Symbol, FloatTy),
1308 /// A float literal without a suffix (`1.0 or 1.0E10`).
1309 FloatUnsuffixed(Symbol),
1310 /// A boolean literal.
1312 /// A recovered character literal that contains mutliple `char`s, most likely a typo.
1317 /// Returns `true` if this literal is a string.
1318 pub fn is_str(&self) -> bool {
1320 LitKind::Str(..) => true,
1325 /// Returns `true` if this literal is byte literal string.
1326 pub fn is_bytestr(&self) -> bool {
1328 LitKind::ByteStr(_) => true,
1333 /// Returns `true` if this is a numeric literal.
1334 pub fn is_numeric(&self) -> bool {
1336 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1341 /// Returns `true` if this literal has no suffix.
1342 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1343 pub fn is_unsuffixed(&self) -> bool {
1345 // unsuffixed variants
1347 | LitKind::ByteStr(..)
1351 | LitKind::Int(_, LitIntType::Unsuffixed)
1352 | LitKind::FloatUnsuffixed(..)
1353 | LitKind::Bool(..) => true,
1354 // suffixed variants
1355 LitKind::Int(_, LitIntType::Signed(..))
1356 | LitKind::Int(_, LitIntType::Unsigned(..))
1357 | LitKind::Float(..) => false,
1361 /// Returns `true` if this literal has a suffix.
1362 pub fn is_suffixed(&self) -> bool {
1363 !self.is_unsuffixed()
1367 // N.B., If you change this, you'll probably want to change the corresponding
1368 // type structure in `middle/ty.rs` as well.
1369 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1372 pub mutbl: Mutability,
1375 /// Represents a method's signature in a trait declaration,
1376 /// or in an implementation.
1377 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1378 pub struct MethodSig {
1379 pub header: FnHeader,
1380 pub decl: P<FnDecl>,
1383 /// Represents an item declaration within a trait declaration,
1384 /// possibly including a default implementation. A trait item is
1385 /// either required (meaning it doesn't have an implementation, just a
1386 /// signature) or provided (meaning it has a default implementation).
1387 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1388 pub struct TraitItem {
1391 pub attrs: Vec<Attribute>,
1392 pub generics: Generics,
1393 pub node: TraitItemKind,
1395 /// See `Item::tokens` for what this is.
1396 pub tokens: Option<TokenStream>,
1399 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1400 pub enum TraitItemKind {
1401 Const(P<Ty>, Option<P<Expr>>),
1402 Method(MethodSig, Option<P<Block>>),
1403 Type(GenericBounds, Option<P<Ty>>),
1407 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1408 pub struct ImplItem {
1411 pub vis: Visibility,
1412 pub defaultness: Defaultness,
1413 pub attrs: Vec<Attribute>,
1414 pub generics: Generics,
1415 pub node: ImplItemKind,
1417 /// See `Item::tokens` for what this is.
1418 pub tokens: Option<TokenStream>,
1421 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1422 pub enum ImplItemKind {
1423 Const(P<Ty>, P<Expr>),
1424 Method(MethodSig, P<Block>),
1426 Existential(GenericBounds),
1430 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1440 impl fmt::Debug for IntTy {
1441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1442 fmt::Display::fmt(self, f)
1446 impl fmt::Display for IntTy {
1447 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1448 write!(f, "{}", self.ty_to_string())
1453 pub fn ty_to_string(&self) -> &'static str {
1455 IntTy::Isize => "isize",
1457 IntTy::I16 => "i16",
1458 IntTy::I32 => "i32",
1459 IntTy::I64 => "i64",
1460 IntTy::I128 => "i128",
1464 pub fn val_to_string(&self, val: i128) -> String {
1465 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1466 // are parsed as `u128`, so we wouldn't want to print an extra negative
1468 format!("{}{}", val as u128, self.ty_to_string())
1471 pub fn bit_width(&self) -> Option<usize> {
1473 IntTy::Isize => return None,
1483 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1494 pub fn ty_to_string(&self) -> &'static str {
1496 UintTy::Usize => "usize",
1498 UintTy::U16 => "u16",
1499 UintTy::U32 => "u32",
1500 UintTy::U64 => "u64",
1501 UintTy::U128 => "u128",
1505 pub fn val_to_string(&self, val: u128) -> String {
1506 format!("{}{}", val, self.ty_to_string())
1509 pub fn bit_width(&self) -> Option<usize> {
1511 UintTy::Usize => return None,
1516 UintTy::U128 => 128,
1521 impl fmt::Debug for UintTy {
1522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1523 fmt::Display::fmt(self, f)
1527 impl fmt::Display for UintTy {
1528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1529 write!(f, "{}", self.ty_to_string())
1533 // Bind a type to an associated type: `A = Foo`.
1534 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1535 pub struct TypeBinding {
1542 #[derive(Clone, RustcEncodable, RustcDecodable)]
1549 impl fmt::Debug for Ty {
1550 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1551 write!(f, "type({})", pprust::ty_to_string(self))
1555 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1556 pub struct BareFnTy {
1557 pub unsafety: Unsafety,
1559 pub generic_params: Vec<GenericParam>,
1560 pub decl: P<FnDecl>,
1563 /// The different kinds of types recognized by the compiler.
1564 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1566 /// A variable-length slice (`[T]`).
1568 /// A fixed length array (`[T; n]`).
1569 Array(P<Ty>, AnonConst),
1570 /// A raw pointer (`*const T` or `*mut T`).
1572 /// A reference (`&'a T` or `&'a mut T`).
1573 Rptr(Option<Lifetime>, MutTy),
1574 /// A bare function (e.g., `fn(usize) -> bool`).
1575 BareFn(P<BareFnTy>),
1576 /// The never type (`!`).
1578 /// A tuple (`(A, B, C, D,...)`).
1580 /// A path (`module::module::...::Type`), optionally
1581 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1583 /// Type parameters are stored in the `Path` itself.
1584 Path(Option<QSelf>, Path),
1585 /// A trait object type `Bound1 + Bound2 + Bound3`
1586 /// where `Bound` is a trait or a lifetime.
1587 TraitObject(GenericBounds, TraitObjectSyntax),
1588 /// An `impl Bound1 + Bound2 + Bound3` type
1589 /// where `Bound` is a trait or a lifetime.
1591 /// The `NodeId` exists to prevent lowering from having to
1592 /// generate `NodeId`s on the fly, which would complicate
1593 /// the generation of `existential type` items significantly.
1594 ImplTrait(NodeId, GenericBounds),
1595 /// No-op; kept solely so that we can pretty-print faithfully.
1599 /// This means the type should be inferred instead of it having been
1600 /// specified. This can appear anywhere in a type.
1602 /// Inferred type of a `self` or `&self` argument in a method.
1604 /// A macro in the type position.
1606 /// Placeholder for a kind that has failed to be defined.
1611 pub fn is_implicit_self(&self) -> bool {
1612 if let TyKind::ImplicitSelf = *self {
1619 pub fn is_unit(&self) -> bool {
1620 if let TyKind::Tup(ref tys) = *self {
1628 /// Syntax used to declare a trait object.
1629 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1630 pub enum TraitObjectSyntax {
1635 /// Inline assembly dialect.
1637 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1638 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1639 pub enum AsmDialect {
1644 /// Inline assembly.
1646 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1647 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1648 pub struct InlineAsmOutput {
1649 pub constraint: Symbol,
1652 pub is_indirect: bool,
1655 /// Inline assembly.
1657 /// E.g., `asm!("NOP");`.
1658 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1659 pub struct InlineAsm {
1661 pub asm_str_style: StrStyle,
1662 pub outputs: Vec<InlineAsmOutput>,
1663 pub inputs: Vec<(Symbol, P<Expr>)>,
1664 pub clobbers: Vec<Symbol>,
1666 pub alignstack: bool,
1667 pub dialect: AsmDialect,
1668 pub ctxt: SyntaxContext,
1671 /// An argument in a function header.
1673 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1674 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1681 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1683 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1684 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1686 /// `self`, `mut self`
1688 /// `&'lt self`, `&'lt mut self`
1689 Region(Option<Lifetime>, Mutability),
1690 /// `self: TYPE`, `mut self: TYPE`
1691 Explicit(P<Ty>, Mutability),
1694 pub type ExplicitSelf = Spanned<SelfKind>;
1697 pub fn to_self(&self) -> Option<ExplicitSelf> {
1698 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1699 if ident.name == keywords::SelfLower.name() {
1700 return match self.ty.node {
1701 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1702 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1703 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1706 self.pat.span.to(self.ty.span),
1707 SelfKind::Explicit(self.ty.clone(), mutbl),
1715 pub fn is_self(&self) -> bool {
1716 if let PatKind::Ident(_, ident, _) = self.pat.node {
1717 ident.name == keywords::SelfLower.name()
1723 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1724 let span = eself.span.to(eself_ident.span);
1725 let infer_ty = P(Ty {
1727 node: TyKind::ImplicitSelf,
1730 let arg = |mutbl, ty| Arg {
1733 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1740 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1741 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1742 SelfKind::Region(lt, mutbl) => arg(
1743 Mutability::Immutable,
1760 /// Header (not the body) of a function declaration.
1762 /// E.g., `fn foo(bar: baz)`.
1763 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1765 pub inputs: Vec<Arg>,
1766 pub output: FunctionRetTy,
1771 pub fn get_self(&self) -> Option<ExplicitSelf> {
1772 self.inputs.get(0).and_then(Arg::to_self)
1774 pub fn has_self(&self) -> bool {
1775 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1779 /// Is the trait definition an auto trait?
1780 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1786 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1792 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1796 return_impl_trait_id: NodeId,
1802 pub fn is_async(self) -> bool {
1803 if let IsAsync::Async { .. } = self {
1810 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1811 pub fn opt_return_id(self) -> Option<NodeId> {
1814 return_impl_trait_id,
1816 } => Some(return_impl_trait_id),
1817 IsAsync::NotAsync => None,
1822 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1823 pub enum Constness {
1828 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1829 pub enum Defaultness {
1834 impl fmt::Display for Unsafety {
1835 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1838 Unsafety::Normal => "normal",
1839 Unsafety::Unsafe => "unsafe",
1846 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1847 pub enum ImplPolarity {
1848 /// `impl Trait for Type`
1850 /// `impl !Trait for Type`
1854 impl fmt::Debug for ImplPolarity {
1855 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1857 ImplPolarity::Positive => "positive".fmt(f),
1858 ImplPolarity::Negative => "negative".fmt(f),
1863 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1864 pub enum FunctionRetTy {
1865 /// Return type is not specified.
1867 /// Functions default to `()` and closures default to inference.
1868 /// Span points to where return type would be inserted.
1870 /// Everything else.
1874 impl FunctionRetTy {
1875 pub fn span(&self) -> Span {
1877 FunctionRetTy::Default(span) => span,
1878 FunctionRetTy::Ty(ref ty) => ty.span,
1883 /// Module declaration.
1885 /// E.g., `mod foo;` or `mod foo { .. }`.
1886 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1888 /// A span from the first token past `{` to the last token until `}`.
1889 /// For `mod foo;`, the inner span ranges from the first token
1890 /// to the last token in the external file.
1892 pub items: Vec<P<Item>>,
1893 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
1897 /// Foreign module declaration.
1899 /// E.g., `extern { .. }` or `extern C { .. }`.
1900 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1901 pub struct ForeignMod {
1903 pub items: Vec<ForeignItem>,
1906 /// Global inline assembly.
1908 /// Also known as "module-level assembly" or "file-scoped assembly".
1909 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1910 pub struct GlobalAsm {
1912 pub ctxt: SyntaxContext,
1915 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1916 pub struct EnumDef {
1917 pub variants: Vec<Variant>,
1920 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1921 pub struct Variant_ {
1923 pub attrs: Vec<Attribute>,
1924 pub data: VariantData,
1925 /// Explicit discriminant, e.g., `Foo = 1`.
1926 pub disr_expr: Option<AnonConst>,
1929 pub type Variant = Spanned<Variant_>;
1931 /// Part of `use` item to the right of its prefix.
1932 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1933 pub enum UseTreeKind {
1934 /// `use prefix` or `use prefix as rename`
1936 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1938 Simple(Option<Ident>, NodeId, NodeId),
1939 /// `use prefix::{...}`
1940 Nested(Vec<(UseTree, NodeId)>),
1945 /// A tree of paths sharing common prefixes.
1946 /// Used in `use` items both at top-level and inside of braces in import groups.
1947 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1948 pub struct UseTree {
1950 pub kind: UseTreeKind,
1955 pub fn ident(&self) -> Ident {
1957 UseTreeKind::Simple(Some(rename), ..) => rename,
1958 UseTreeKind::Simple(None, ..) => {
1962 .expect("empty prefix in a simple import")
1965 _ => panic!("`UseTree::ident` can only be used on a simple import"),
1970 /// Distinguishes between `Attribute`s that decorate items and Attributes that
1971 /// are contained as statements within items. These two cases need to be
1972 /// distinguished for pretty-printing.
1973 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1974 pub enum AttrStyle {
1980 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
1982 pub struct AttrId(pub usize);
1984 impl Idx for AttrId {
1985 fn new(idx: usize) -> Self {
1988 fn index(self) -> usize {
1993 /// Metadata associated with an item.
1994 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
1995 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1996 pub struct Attribute {
1998 pub style: AttrStyle,
2000 pub tokens: TokenStream,
2001 pub is_sugared_doc: bool,
2005 /// `TraitRef`s appear in impls.
2007 /// Resolve maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2008 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2009 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2010 /// same as the impl's node-id).
2011 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2012 pub struct TraitRef {
2017 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2018 pub struct PolyTraitRef {
2019 /// The `'a` in `<'a> Foo<&'a T>`
2020 pub bound_generic_params: Vec<GenericParam>,
2022 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2023 pub trait_ref: TraitRef,
2029 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2031 bound_generic_params: generic_params,
2032 trait_ref: TraitRef {
2034 ref_id: DUMMY_NODE_ID,
2041 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2042 pub enum CrateSugar {
2043 /// Source is `pub(crate)`.
2046 /// Source is (just) `crate`.
2050 pub type Visibility = Spanned<VisibilityKind>;
2052 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2053 pub enum VisibilityKind {
2056 Restricted { path: P<Path>, id: NodeId },
2060 impl VisibilityKind {
2061 pub fn is_pub(&self) -> bool {
2062 if let VisibilityKind::Public = *self {
2070 /// Field of a struct.
2072 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2073 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2074 pub struct StructField {
2076 pub ident: Option<Ident>,
2077 pub vis: Visibility,
2080 pub attrs: Vec<Attribute>,
2083 /// Fields and Ids of enum variants and structs
2085 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2086 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2087 /// One shared Id can be successfully used for these two purposes.
2088 /// Id of the whole enum lives in `Item`.
2090 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2091 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2092 /// the variant itself" from enum variants.
2093 /// Id of the whole struct lives in `Item`.
2094 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2095 pub enum VariantData {
2098 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2099 Struct(Vec<StructField>, NodeId),
2102 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2103 Tuple(Vec<StructField>, NodeId),
2106 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2111 pub fn fields(&self) -> &[StructField] {
2113 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2117 pub fn id(&self) -> NodeId {
2119 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2122 pub fn is_struct(&self) -> bool {
2123 if let VariantData::Struct(..) = *self {
2129 pub fn is_tuple(&self) -> bool {
2130 if let VariantData::Tuple(..) = *self {
2136 pub fn is_unit(&self) -> bool {
2137 if let VariantData::Unit(..) = *self {
2147 /// The name might be a dummy name in case of anonymous items.
2148 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2151 pub attrs: Vec<Attribute>,
2154 pub vis: Visibility,
2157 /// Original tokens this item was parsed from. This isn't necessarily
2158 /// available for all items, although over time more and more items should
2159 /// have this be `Some`. Right now this is primarily used for procedural
2160 /// macros, notably custom attributes.
2162 /// Note that the tokens here do not include the outer attributes, but will
2163 /// include inner attributes.
2164 pub tokens: Option<TokenStream>,
2168 /// Return the span that encompasses the attributes.
2169 pub fn span_with_attributes(&self) -> Span {
2170 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span()))
2174 /// A function header.
2176 /// All the information between the visibility and the name of the function is
2177 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2178 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2179 pub struct FnHeader {
2180 pub unsafety: Unsafety,
2181 pub asyncness: IsAsync,
2182 pub constness: Spanned<Constness>,
2186 impl Default for FnHeader {
2187 fn default() -> FnHeader {
2189 unsafety: Unsafety::Normal,
2190 asyncness: IsAsync::NotAsync,
2191 constness: dummy_spanned(Constness::NotConst),
2197 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2199 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2201 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2202 ExternCrate(Option<Name>),
2203 /// A use declaration (`use` or `pub use`) item.
2205 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2207 /// A static item (`static` or `pub static`).
2209 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2210 Static(P<Ty>, Mutability, P<Expr>),
2211 /// A constant item (`const` or `pub const`).
2213 /// E.g., `const FOO: i32 = 42;`.
2214 Const(P<Ty>, P<Expr>),
2215 /// A function declaration (`fn` or `pub fn`).
2217 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2218 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2219 /// A module declaration (`mod` or `pub mod`).
2221 /// E.g., `mod foo;` or `mod foo { .. }`.
2223 /// An external module (`extern` or `pub extern`).
2225 /// E.g., `extern {}` or `extern "C" {}`.
2226 ForeignMod(ForeignMod),
2227 /// Module-level inline assembly (from `global_asm!()`).
2228 GlobalAsm(P<GlobalAsm>),
2229 /// A type alias (`type` or `pub type`).
2231 /// E.g., `type Foo = Bar<u8>;`.
2232 Ty(P<Ty>, Generics),
2233 /// An existential type declaration (`existential type`).
2235 /// E.g., `existential type Foo: Bar + Boo;`.
2236 Existential(GenericBounds, Generics),
2237 /// An enum definition (`enum` or `pub enum`).
2239 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2240 Enum(EnumDef, Generics),
2241 /// A struct definition (`struct` or `pub struct`).
2243 /// E.g., `struct Foo<A> { x: A }`.
2244 Struct(VariantData, Generics),
2245 /// A union definition (`union` or `pub union`).
2247 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2248 Union(VariantData, Generics),
2249 /// A Trait declaration (`trait` or `pub trait`).
2251 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2252 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2255 /// E.g., `trait Foo = Bar + Quux;`.
2256 TraitAlias(Generics, GenericBounds),
2257 /// An implementation.
2259 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2265 Option<TraitRef>, // (optional) trait this impl implements
2269 /// A macro invocation.
2271 /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2274 /// A macro definition.
2279 pub fn descriptive_variant(&self) -> &str {
2281 ItemKind::ExternCrate(..) => "extern crate",
2282 ItemKind::Use(..) => "use",
2283 ItemKind::Static(..) => "static item",
2284 ItemKind::Const(..) => "constant item",
2285 ItemKind::Fn(..) => "function",
2286 ItemKind::Mod(..) => "module",
2287 ItemKind::ForeignMod(..) => "foreign module",
2288 ItemKind::GlobalAsm(..) => "global asm",
2289 ItemKind::Ty(..) => "type alias",
2290 ItemKind::Existential(..) => "existential type",
2291 ItemKind::Enum(..) => "enum",
2292 ItemKind::Struct(..) => "struct",
2293 ItemKind::Union(..) => "union",
2294 ItemKind::Trait(..) => "trait",
2295 ItemKind::TraitAlias(..) => "trait alias",
2296 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2301 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2302 pub struct ForeignItem {
2304 pub attrs: Vec<Attribute>,
2305 pub node: ForeignItemKind,
2308 pub vis: Visibility,
2311 /// An item within an `extern` block.
2312 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2313 pub enum ForeignItemKind {
2314 /// A foreign function.
2315 Fn(P<FnDecl>, Generics),
2316 /// A foreign static item (`static ext: u8`), with optional mutability.
2317 /// (The boolean is `true` for mutable items).
2318 Static(P<Ty>, bool),
2321 /// A macro invocation.
2325 impl ForeignItemKind {
2326 pub fn descriptive_variant(&self) -> &str {
2328 ForeignItemKind::Fn(..) => "foreign function",
2329 ForeignItemKind::Static(..) => "foreign static item",
2330 ForeignItemKind::Ty => "foreign type",
2331 ForeignItemKind::Macro(..) => "macro in foreign module",
2341 // Are ASTs encodable?
2343 fn check_asts_encodable() {
2344 fn assert_encodable<T: serialize::Encodable>() {}
2345 assert_encodable::<Crate>();