1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // The Rust abstract syntax tree.
13 pub use self::GenericArgs::*;
14 pub use self::UnsafeSource::*;
15 pub use symbol::{Ident, Symbol as Name};
16 pub use util::parser::ExprPrecedence;
18 use ext::hygiene::{Mark, SyntaxContext};
21 use rustc_data_structures::indexed_vec::Idx;
22 #[cfg(target_arch = "x86_64")]
23 use rustc_data_structures::static_assert;
24 use rustc_target::spec::abi::Abi;
25 use source_map::{dummy_spanned, respan, Spanned};
26 use symbol::{keywords, Symbol};
27 use syntax_pos::{Span, DUMMY_SP};
28 use tokenstream::{ThinTokenStream, TokenStream};
31 use rustc_data_structures::fx::FxHashSet;
32 use rustc_data_structures::sync::Lrc;
33 use serialize::{self, Decoder, Encoder};
36 pub use rustc_target::abi::FloatTy;
38 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
43 impl fmt::Debug for Label {
44 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45 write!(f, "label({:?})", self.ident)
49 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
55 impl fmt::Debug for Lifetime {
56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 pprust::lifetime_to_string(self)
66 /// A "Path" is essentially Rust's notion of a name.
68 /// It's represented as a sequence of identifiers,
69 /// along with a bunch of supporting information.
71 /// E.g., `std::cmp::PartialEq`.
72 #[derive(Clone, RustcEncodable, RustcDecodable)]
75 /// The segments in the path: the things separated by `::`.
76 /// Global paths begin with `keywords::PathRoot`.
77 pub segments: Vec<PathSegment>,
80 impl<'a> PartialEq<&'a str> for Path {
81 fn eq(&self, string: &&'a str) -> bool {
82 self.segments.len() == 1 && self.segments[0].ident.name == *string
86 impl fmt::Debug for Path {
87 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
88 write!(f, "path({})", pprust::path_to_string(self))
92 impl fmt::Display for Path {
93 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94 write!(f, "{}", pprust::path_to_string(self))
99 // Convert a span and an identifier to the corresponding
101 pub fn from_ident(ident: Ident) -> Path {
103 segments: vec![PathSegment::from_ident(ident)],
108 pub fn is_global(&self) -> bool {
109 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
113 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
115 /// E.g., `std`, `String` or `Box<T>`.
116 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
117 pub struct PathSegment {
118 /// The identifier portion of this path segment.
123 /// Type/lifetime parameters attached to this path. They come in
124 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
125 /// `None` means that no parameter list is supplied (`Path`),
126 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
127 /// but it can be empty (`Path<>`).
128 /// `P` is used as a size optimization for the common case with no parameters.
129 pub args: Option<P<GenericArgs>>,
133 pub fn from_ident(ident: Ident) -> Self {
134 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
136 pub fn path_root(span: Span) -> Self {
137 PathSegment::from_ident(Ident::new(keywords::PathRoot.name(), span))
141 /// Arguments of a path segment.
143 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
144 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
145 pub enum GenericArgs {
146 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
147 AngleBracketed(AngleBracketedArgs),
148 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
149 Parenthesized(ParenthesisedArgs),
153 pub fn span(&self) -> Span {
155 AngleBracketed(ref data) => data.span,
156 Parenthesized(ref data) => data.span,
161 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
162 pub enum GenericArg {
167 /// A path like `Foo<'a, T>`
168 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
169 pub struct AngleBracketedArgs {
172 /// The arguments for this path segment.
173 pub args: Vec<GenericArg>,
174 /// Bindings (equality constraints) on associated types, if present.
176 /// E.g., `Foo<A=Bar>`.
177 pub bindings: Vec<TypeBinding>,
180 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
181 fn into(self) -> Option<P<GenericArgs>> {
182 Some(P(GenericArgs::AngleBracketed(self)))
186 impl Into<Option<P<GenericArgs>>> for ParenthesisedArgs {
187 fn into(self) -> Option<P<GenericArgs>> {
188 Some(P(GenericArgs::Parenthesized(self)))
192 /// A path like `Foo(A,B) -> C`
193 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
194 pub struct ParenthesisedArgs {
199 pub inputs: Vec<P<Ty>>,
202 pub output: Option<P<Ty>>,
205 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
207 use rustc_data_structures::indexed_vec::Idx;
211 DEBUG_FORMAT = "NodeId({})"
216 pub use self::node_id_inner::NodeId;
219 pub fn placeholder_from_mark(mark: Mark) -> Self {
220 NodeId::from_u32(mark.as_u32())
223 pub fn placeholder_to_mark(self) -> Mark {
224 Mark::from_u32(self.as_u32())
228 impl fmt::Display for NodeId {
229 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
230 fmt::Display::fmt(&self.as_u32(), f)
234 impl serialize::UseSpecializedEncodable for NodeId {
235 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
236 s.emit_u32(self.as_u32())
240 impl serialize::UseSpecializedDecodable for NodeId {
241 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
242 d.read_u32().map(NodeId::from_u32)
246 /// Node id used to represent the root of the crate.
247 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
249 /// When parsing and doing expansions, we initially give all AST nodes this AST
250 /// node value. Then later, in the renumber pass, we renumber them to have
251 /// small, positive ids.
252 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
254 /// A modifier on a bound, currently this is only used for `?Sized`, where the
255 /// modifier is `Maybe`. Negative bounds should also be handled here.
256 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
257 pub enum TraitBoundModifier {
262 /// The AST represents all type param bounds as types.
263 /// `typeck::collect::compute_bounds` matches these against
264 /// the "special" built-in traits (see `middle::lang_items`) and
265 /// detects `Copy`, `Send` and `Sync`.
266 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
267 pub enum GenericBound {
268 Trait(PolyTraitRef, TraitBoundModifier),
273 pub fn span(&self) -> Span {
275 &GenericBound::Trait(ref t, ..) => t.span,
276 &GenericBound::Outlives(ref l) => l.ident.span,
281 pub type GenericBounds = Vec<GenericBound>;
283 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
284 pub enum GenericParamKind {
285 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
288 default: Option<P<Ty>>,
292 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
293 pub struct GenericParam {
296 pub attrs: ThinVec<Attribute>,
297 pub bounds: GenericBounds,
299 pub kind: GenericParamKind,
302 /// Represents lifetime, type and const parameters attached to a declaration of
303 /// a function, enum, trait, etc.
304 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
305 pub struct Generics {
306 pub params: Vec<GenericParam>,
307 pub where_clause: WhereClause,
311 impl Default for Generics {
312 /// Creates an instance of `Generics`.
313 fn default() -> Generics {
316 where_clause: WhereClause {
318 predicates: Vec::new(),
326 /// A `where` clause in a definition
327 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
328 pub struct WhereClause {
330 pub predicates: Vec<WherePredicate>,
334 /// A single predicate in a `where` clause
335 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
336 pub enum WherePredicate {
337 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
338 BoundPredicate(WhereBoundPredicate),
339 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
340 RegionPredicate(WhereRegionPredicate),
341 /// An equality predicate (unsupported).
342 EqPredicate(WhereEqPredicate),
345 impl WherePredicate {
346 pub fn span(&self) -> Span {
348 &WherePredicate::BoundPredicate(ref p) => p.span,
349 &WherePredicate::RegionPredicate(ref p) => p.span,
350 &WherePredicate::EqPredicate(ref p) => p.span,
357 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
358 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
359 pub struct WhereBoundPredicate {
361 /// Any generics from a `for` binding
362 pub bound_generic_params: Vec<GenericParam>,
363 /// The type being bounded
364 pub bounded_ty: P<Ty>,
365 /// Trait and lifetime bounds (`Clone+Send+'static`)
366 pub bounds: GenericBounds,
369 /// A lifetime predicate.
371 /// E.g., `'a: 'b + 'c`.
372 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
373 pub struct WhereRegionPredicate {
375 pub lifetime: Lifetime,
376 pub bounds: GenericBounds,
379 /// An equality predicate (unsupported).
382 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
383 pub struct WhereEqPredicate {
390 /// The set of `MetaItem`s that define the compilation environment of the crate,
391 /// used to drive conditional compilation.
392 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
394 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
397 pub attrs: Vec<Attribute>,
401 /// A spanned compile-time attribute list item.
402 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
404 /// Possible values inside of compile-time attribute lists.
406 /// E.g., the '..' in `#[name(..)]`.
407 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
408 pub enum NestedMetaItemKind {
409 /// A full MetaItem, for recursive meta items.
413 /// E.g., `"foo"`, `64`, `true`.
417 /// A spanned compile-time attribute item.
419 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
420 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
421 pub struct MetaItem {
423 pub node: MetaItemKind,
427 /// A compile-time attribute item.
429 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
430 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
431 pub enum MetaItemKind {
434 /// E.g., `test` as in `#[test]`.
438 /// E.g., `derive(..)` as in `#[derive(..)]`.
439 List(Vec<NestedMetaItem>),
440 /// Name value meta item.
442 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
446 /// A Block (`{ .. }`).
448 /// E.g., `{ .. }` as in `fn foo() { .. }`.
449 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
451 /// Statements in a block
452 pub stmts: Vec<Stmt>,
454 /// Distinguishes between `unsafe { ... }` and `{ ... }`
455 pub rules: BlockCheckMode,
460 #[derive(Clone, RustcEncodable, RustcDecodable)]
467 impl fmt::Debug for Pat {
468 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
469 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
474 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
475 let node = match &self.node {
476 PatKind::Wild => TyKind::Infer,
477 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
478 TyKind::Path(None, Path::from_ident(*ident))
480 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
481 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
482 PatKind::Ref(pat, mutbl) => pat
484 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
485 PatKind::Slice(pats, None, _) if pats.len() == 1 => {
486 pats[0].to_ty().map(TyKind::Slice)?
488 PatKind::Tuple(pats, None) => {
489 let mut tys = Vec::with_capacity(pats.len());
490 // FIXME(#48994) - could just be collected into an Option<Vec>
492 tys.push(pat.to_ty()?);
506 pub fn walk<F>(&self, it: &mut F) -> bool
508 F: FnMut(&Pat) -> bool,
515 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
516 PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
517 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
518 s.iter().all(|p| p.walk(it))
520 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
521 PatKind::Slice(ref before, ref slice, ref after) => {
522 before.iter().all(|p| p.walk(it))
523 && slice.iter().all(|p| p.walk(it))
524 && after.iter().all(|p| p.walk(it))
531 | PatKind::Mac(_) => true,
536 /// A single field in a struct pattern
538 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
539 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
540 /// except is_shorthand is true
541 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
542 pub struct FieldPat {
543 /// The identifier for the field
545 /// The pattern the field is destructured to
547 pub is_shorthand: bool,
548 pub attrs: ThinVec<Attribute>,
551 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
552 pub enum BindingMode {
557 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
559 Included(RangeSyntax),
563 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
564 pub enum RangeSyntax {
569 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
571 /// Represents a wildcard pattern (`_`).
574 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
575 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
576 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
577 /// during name resolution.
578 Ident(BindingMode, Ident, Option<P<Pat>>),
580 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
581 /// The `bool` is `true` in the presence of a `..`.
582 Struct(Path, Vec<Spanned<FieldPat>>, bool),
584 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
585 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
586 /// `0 <= position <= subpats.len()`.
587 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
589 /// A possibly qualified path pattern.
590 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
591 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
592 /// only legally refer to associated constants.
593 Path(Option<QSelf>, Path),
595 /// A tuple pattern (`(a, b)`).
596 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
597 /// `0 <= position <= subpats.len()`.
598 Tuple(Vec<P<Pat>>, Option<usize>),
601 /// A reference pattern (e.g., `&mut (a, b)`).
602 Ref(P<Pat>, Mutability),
605 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
606 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
607 /// `[a, b, ..i, y, z]` is represented as:
608 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
609 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
610 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
612 /// A macro pattern; pre-expansion.
617 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
619 pub enum Mutability {
624 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
626 /// The `+` operator (addition)
628 /// The `-` operator (subtraction)
630 /// The `*` operator (multiplication)
632 /// The `/` operator (division)
634 /// The `%` operator (modulus)
636 /// The `&&` operator (logical and)
638 /// The `||` operator (logical or)
640 /// The `^` operator (bitwise xor)
642 /// The `&` operator (bitwise and)
644 /// The `|` operator (bitwise or)
646 /// The `<<` operator (shift left)
648 /// The `>>` operator (shift right)
650 /// The `==` operator (equality)
652 /// The `<` operator (less than)
654 /// The `<=` operator (less than or equal to)
656 /// The `!=` operator (not equal to)
658 /// The `>=` operator (greater than or equal to)
660 /// The `>` operator (greater than)
665 pub fn to_string(&self) -> &'static str {
666 use self::BinOpKind::*;
688 pub fn lazy(&self) -> bool {
690 BinOpKind::And | BinOpKind::Or => true,
695 pub fn is_shift(&self) -> bool {
697 BinOpKind::Shl | BinOpKind::Shr => true,
702 pub fn is_comparison(&self) -> bool {
703 use self::BinOpKind::*;
705 Eq | Lt | Le | Ne | Gt | Ge => true,
706 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
710 /// Returns `true` if the binary operator takes its arguments by value
711 pub fn is_by_value(&self) -> bool {
712 !self.is_comparison()
716 pub type BinOp = Spanned<BinOpKind>;
718 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
720 /// The `*` operator for dereferencing
722 /// The `!` operator for logical inversion
724 /// The `-` operator for negation
729 /// Returns `true` if the unary operator takes its argument by value
730 pub fn is_by_value(u: UnOp) -> bool {
732 UnOp::Neg | UnOp::Not => true,
737 pub fn to_string(op: UnOp) -> &'static str {
747 #[derive(Clone, RustcEncodable, RustcDecodable)]
755 pub fn add_trailing_semicolon(mut self) -> Self {
756 self.node = match self.node {
757 StmtKind::Expr(expr) => StmtKind::Semi(expr),
758 StmtKind::Mac(mac) => {
759 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
766 pub fn is_item(&self) -> bool {
768 StmtKind::Item(_) => true,
773 pub fn is_expr(&self) -> bool {
775 StmtKind::Expr(_) => true,
781 impl fmt::Debug for Stmt {
782 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
787 pprust::stmt_to_string(self)
792 #[derive(Clone, RustcEncodable, RustcDecodable)]
794 /// A local (let) binding.
797 /// An item definition.
800 /// Expr without trailing semi-colon.
802 /// Expr with a trailing semi-colon.
805 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
808 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
809 pub enum MacStmtStyle {
810 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
811 /// `foo!(...);`, `foo![...];`).
813 /// The macro statement had braces (e.g., `foo! { ... }`).
815 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
816 /// `foo!(...)`). All of these will end up being converted into macro
821 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
822 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
825 pub ty: Option<P<Ty>>,
826 /// Initializer expression to set the value, if any.
827 pub init: Option<P<Expr>>,
830 pub attrs: ThinVec<Attribute>,
833 /// An arm of a 'match'.
835 /// E.g., `0..=10 => { println!("match!") }` as in
839 /// 0..=10 => { println!("match!") },
840 /// _ => { println!("no match!") },
843 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
845 pub attrs: Vec<Attribute>,
846 pub pats: Vec<P<Pat>>,
847 pub guard: Option<Guard>,
851 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
856 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
861 pub is_shorthand: bool,
862 pub attrs: ThinVec<Attribute>,
865 pub type SpannedIdent = Spanned<Ident>;
867 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
868 pub enum BlockCheckMode {
870 Unsafe(UnsafeSource),
873 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
874 pub enum UnsafeSource {
879 /// A constant (expression) that's not an item or associated item,
880 /// but needs its own `DefId` for type-checking, const-eval, etc.
881 /// These are usually found nested inside types (e.g., array lengths)
882 /// or expressions (e.g., repeat counts), and also used to define
883 /// explicit discriminant values for enum variants.
884 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
885 pub struct AnonConst {
891 #[derive(Clone, RustcEncodable, RustcDecodable)]
896 pub attrs: ThinVec<Attribute>,
899 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
900 #[cfg(target_arch = "x86_64")]
901 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 88);
904 /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
906 pub fn returns(&self) -> bool {
907 if let ExprKind::Block(ref block, _) = self.node {
908 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
910 Some(&StmtKind::Expr(_)) => true,
911 Some(&StmtKind::Semi(ref expr)) => {
912 if let ExprKind::Ret(_) = expr.node {
913 // last statement is explicit return
919 // This is a block that doesn't end in either an implicit or explicit return
923 // This is not a block, it is a value
928 fn to_bound(&self) -> Option<GenericBound> {
930 ExprKind::Path(None, path) => Some(GenericBound::Trait(
931 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
932 TraitBoundModifier::None,
938 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
939 let node = match &self.node {
940 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
941 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
942 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
943 ExprKind::AddrOf(mutbl, expr) => expr
945 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
946 ExprKind::Repeat(expr, expr_len) => {
947 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
949 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
950 ExprKind::Tup(exprs) => {
953 .map(|expr| expr.to_ty())
954 .collect::<Option<Vec<_>>>()?;
957 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
958 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
959 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
974 pub fn precedence(&self) -> ExprPrecedence {
976 ExprKind::Box(_) => ExprPrecedence::Box,
977 ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
978 ExprKind::Array(_) => ExprPrecedence::Array,
979 ExprKind::Call(..) => ExprPrecedence::Call,
980 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
981 ExprKind::Tup(_) => ExprPrecedence::Tup,
982 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
983 ExprKind::Unary(..) => ExprPrecedence::Unary,
984 ExprKind::Lit(_) => ExprPrecedence::Lit,
985 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
986 ExprKind::If(..) => ExprPrecedence::If,
987 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
988 ExprKind::While(..) => ExprPrecedence::While,
989 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
990 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
991 ExprKind::Loop(..) => ExprPrecedence::Loop,
992 ExprKind::Match(..) => ExprPrecedence::Match,
993 ExprKind::Closure(..) => ExprPrecedence::Closure,
994 ExprKind::Block(..) => ExprPrecedence::Block,
995 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
996 ExprKind::Async(..) => ExprPrecedence::Async,
997 ExprKind::Assign(..) => ExprPrecedence::Assign,
998 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
999 ExprKind::Field(..) => ExprPrecedence::Field,
1000 ExprKind::Index(..) => ExprPrecedence::Index,
1001 ExprKind::Range(..) => ExprPrecedence::Range,
1002 ExprKind::Path(..) => ExprPrecedence::Path,
1003 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1004 ExprKind::Break(..) => ExprPrecedence::Break,
1005 ExprKind::Continue(..) => ExprPrecedence::Continue,
1006 ExprKind::Ret(..) => ExprPrecedence::Ret,
1007 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1008 ExprKind::Mac(..) => ExprPrecedence::Mac,
1009 ExprKind::Struct(..) => ExprPrecedence::Struct,
1010 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1011 ExprKind::Paren(..) => ExprPrecedence::Paren,
1012 ExprKind::Try(..) => ExprPrecedence::Try,
1013 ExprKind::Yield(..) => ExprPrecedence::Yield,
1018 impl fmt::Debug for Expr {
1019 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1020 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1024 /// Limit types of a range (inclusive or exclusive)
1025 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1026 pub enum RangeLimits {
1027 /// Inclusive at the beginning, exclusive at the end
1029 /// Inclusive at the beginning and end
1033 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1035 /// A `box x` expression.
1037 /// First expr is the place; second expr is the value.
1038 ObsoleteInPlace(P<Expr>, P<Expr>),
1039 /// An array (`[a, b, c, d]`)
1040 Array(Vec<P<Expr>>),
1043 /// The first field resolves to the function itself,
1044 /// and the second field is the list of arguments.
1045 /// This also represents calling the constructor of
1046 /// tuple-like ADTs such as tuple structs and enum variants.
1047 Call(P<Expr>, Vec<P<Expr>>),
1048 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1050 /// The `PathSegment` represents the method name and its generic arguments
1051 /// (within the angle brackets).
1052 /// The first element of the vector of an `Expr` is the expression that evaluates
1053 /// to the object on which the method is being called on (the receiver),
1054 /// and the remaining elements are the rest of the arguments.
1055 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1056 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1057 MethodCall(PathSegment, Vec<P<Expr>>),
1058 /// A tuple (e.g., `(a, b, c, d)`).
1060 /// A binary operation (e.g., `a + b`, `a * b`).
1061 Binary(BinOp, P<Expr>, P<Expr>),
1062 /// A unary operation (e.g., `!x`, `*x`).
1063 Unary(UnOp, P<Expr>),
1064 /// A literal (e.g., `1`, `"foo"`).
1066 /// A cast (e.g., `foo as f64`).
1067 Cast(P<Expr>, P<Ty>),
1068 Type(P<Expr>, P<Ty>),
1069 /// An `if` block, with an optional `else` block.
1071 /// `if expr { block } else { expr }`
1072 If(P<Expr>, P<Block>, Option<P<Expr>>),
1073 /// An `if let` expression with an optional else block
1075 /// `if let pat = expr { block } else { expr }`
1077 /// This is desugared to a `match` expression.
1078 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1079 /// A while loop, with an optional label
1081 /// `'label: while expr { block }`
1082 While(P<Expr>, P<Block>, Option<Label>),
1083 /// A `while let` loop, with an optional label.
1085 /// `'label: while let pat = expr { block }`
1087 /// This is desugared to a combination of `loop` and `match` expressions.
1088 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1089 /// A `for` loop, with an optional label.
1091 /// `'label: for pat in expr { block }`
1093 /// This is desugared to a combination of `loop` and `match` expressions.
1094 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1095 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1097 /// `'label: loop { block }`
1098 Loop(P<Block>, Option<Label>),
1099 /// A `match` block.
1100 Match(P<Expr>, Vec<Arm>),
1101 /// A closure (e.g., `move |a, b, c| a + b + c`).
1103 /// The final span is the span of the argument block `|...|`.
1104 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1105 /// A block (`'label: { ... }`).
1106 Block(P<Block>, Option<Label>),
1107 /// An async block (`async move { ... }`).
1109 /// The `NodeId` is the `NodeId` for the closure that results from
1110 /// desugaring an async block, just like the NodeId field in the
1111 /// `IsAsync` enum. This is necessary in order to create a def for the
1112 /// closure which can be used as a parent of any child defs. Defs
1113 /// created during lowering cannot be made the parent of any other
1114 /// preexisting defs.
1115 Async(CaptureBy, NodeId, P<Block>),
1116 /// A try block (`try { ... }`).
1119 /// An assignment (`a = foo()`).
1120 Assign(P<Expr>, P<Expr>),
1121 /// An assignment with an operator.
1124 AssignOp(BinOp, P<Expr>, P<Expr>),
1125 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1126 Field(P<Expr>, Ident),
1127 /// An indexing operation (e.g., `foo[2]`).
1128 Index(P<Expr>, P<Expr>),
1129 /// A range (e.g., `1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`).
1130 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1132 /// Variable reference, possibly containing `::` and/or type
1133 /// parameters (e.g., `foo::bar::<baz>`).
1135 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1136 Path(Option<QSelf>, Path),
1138 /// A referencing operation (`&a` or `&mut a`).
1139 AddrOf(Mutability, P<Expr>),
1140 /// A `break`, with an optional label to break, and an optional expression.
1141 Break(Option<Label>, Option<P<Expr>>),
1142 /// A `continue`, with an optional label.
1143 Continue(Option<Label>),
1144 /// A `return`, with an optional value to be returned.
1145 Ret(Option<P<Expr>>),
1147 /// Output of the `asm!()` macro.
1148 InlineAsm(P<InlineAsm>),
1150 /// A macro invocation; pre-expansion.
1153 /// A struct literal expression.
1155 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1156 /// where `base` is the `Option<Expr>`.
1157 Struct(Path, Vec<Field>, Option<P<Expr>>),
1159 /// An array literal constructed from one repeated element.
1161 /// E.g., `[1; 5]`. The expression is the element to be
1162 /// repeated; the constant is the number of times to repeat it.
1163 Repeat(P<Expr>, AnonConst),
1165 /// No-op: used solely so we can pretty-print faithfully.
1168 /// A try expression (`expr?`).
1171 /// A `yield`, with an optional value to be yielded.
1172 Yield(Option<P<Expr>>),
1175 /// The explicit `Self` type in a "qualified path". The actual
1176 /// path, including the trait and the associated item, is stored
1177 /// separately. `position` represents the index of the associated
1178 /// item qualified with this `Self` type.
1180 /// ```ignore (only-for-syntax-highlight)
1181 /// <Vec<T> as a::b::Trait>::AssociatedItem
1182 /// ^~~~~ ~~~~~~~~~~~~~~^
1185 /// <Vec<T>>::AssociatedItem
1189 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1193 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1194 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1195 /// 0`, this is an empty span.
1196 pub path_span: Span,
1197 pub position: usize,
1200 /// A capture clause.
1201 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1202 pub enum CaptureBy {
1207 /// The movability of a generator / closure literal.
1208 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1209 pub enum Movability {
1214 pub type Mac = Spanned<Mac_>;
1216 /// Represents a macro invocation. The `Path` indicates which macro
1217 /// is being invoked, and the vector of token-trees contains the source
1218 /// of the macro invocation.
1220 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1221 /// stored in the enclosing item.
1222 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1225 pub delim: MacDelimiter,
1226 pub tts: ThinTokenStream,
1229 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1230 pub enum MacDelimiter {
1237 pub fn stream(&self) -> TokenStream {
1238 self.tts.clone().into()
1242 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1243 pub struct MacroDef {
1244 pub tokens: ThinTokenStream,
1249 pub fn stream(&self) -> TokenStream {
1250 self.tokens.clone().into()
1254 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1256 /// A regular string, like `"foo"`.
1258 /// A raw string, like `r##"foo"##`.
1260 /// The value is the number of `#` symbols used.
1265 pub type Lit = Spanned<LitKind>;
1267 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1268 pub enum LitIntType {
1276 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1277 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1279 /// A string literal (`"foo"`).
1280 Str(Symbol, StrStyle),
1281 /// A byte string (`b"foo"`).
1282 ByteStr(Lrc<Vec<u8>>),
1283 /// A byte char (`b'f'`).
1285 /// A character literal (`'a'`).
1287 /// An integer literal (`1`).
1288 Int(u128, LitIntType),
1289 /// A float literal (`1f64` or `1E10f64`).
1290 Float(Symbol, FloatTy),
1291 /// A float literal without a suffix (`1.0 or 1.0E10`).
1292 FloatUnsuffixed(Symbol),
1293 /// A boolean literal.
1298 /// Returns `true` if this literal is a string.
1299 pub fn is_str(&self) -> bool {
1301 LitKind::Str(..) => true,
1306 /// Returns `true` if this literal is byte literal string.
1307 pub fn is_bytestr(&self) -> bool {
1309 LitKind::ByteStr(_) => true,
1314 /// Returns `true` if this is a numeric literal.
1315 pub fn is_numeric(&self) -> bool {
1317 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1322 /// Returns `true` if this literal has no suffix.
1323 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1324 pub fn is_unsuffixed(&self) -> bool {
1326 // unsuffixed variants
1328 | LitKind::ByteStr(..)
1331 | LitKind::Int(_, LitIntType::Unsuffixed)
1332 | LitKind::FloatUnsuffixed(..)
1333 | LitKind::Bool(..) => true,
1334 // suffixed variants
1335 LitKind::Int(_, LitIntType::Signed(..))
1336 | LitKind::Int(_, LitIntType::Unsigned(..))
1337 | LitKind::Float(..) => false,
1341 /// Returns `true` if this literal has a suffix.
1342 pub fn is_suffixed(&self) -> bool {
1343 !self.is_unsuffixed()
1347 // N.B., If you change this, you'll probably want to change the corresponding
1348 // type structure in `middle/ty.rs` as well.
1349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1352 pub mutbl: Mutability,
1355 /// Represents a method's signature in a trait declaration,
1356 /// or in an implementation.
1357 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1358 pub struct MethodSig {
1359 pub header: FnHeader,
1360 pub decl: P<FnDecl>,
1363 /// Represents an item declaration within a trait declaration,
1364 /// possibly including a default implementation. A trait item is
1365 /// either required (meaning it doesn't have an implementation, just a
1366 /// signature) or provided (meaning it has a default implementation).
1367 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1368 pub struct TraitItem {
1371 pub attrs: Vec<Attribute>,
1372 pub generics: Generics,
1373 pub node: TraitItemKind,
1375 /// See `Item::tokens` for what this is.
1376 pub tokens: Option<TokenStream>,
1379 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1380 pub enum TraitItemKind {
1381 Const(P<Ty>, Option<P<Expr>>),
1382 Method(MethodSig, Option<P<Block>>),
1383 Type(GenericBounds, Option<P<Ty>>),
1387 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1388 pub struct ImplItem {
1391 pub vis: Visibility,
1392 pub defaultness: Defaultness,
1393 pub attrs: Vec<Attribute>,
1394 pub generics: Generics,
1395 pub node: ImplItemKind,
1397 /// See `Item::tokens` for what this is.
1398 pub tokens: Option<TokenStream>,
1401 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1402 pub enum ImplItemKind {
1403 Const(P<Ty>, P<Expr>),
1404 Method(MethodSig, P<Block>),
1406 Existential(GenericBounds),
1410 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1420 impl fmt::Debug for IntTy {
1421 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1422 fmt::Display::fmt(self, f)
1426 impl fmt::Display for IntTy {
1427 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1428 write!(f, "{}", self.ty_to_string())
1433 pub fn ty_to_string(&self) -> &'static str {
1435 IntTy::Isize => "isize",
1437 IntTy::I16 => "i16",
1438 IntTy::I32 => "i32",
1439 IntTy::I64 => "i64",
1440 IntTy::I128 => "i128",
1444 pub fn val_to_string(&self, val: i128) -> String {
1445 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1446 // are parsed as `u128`, so we wouldn't want to print an extra negative
1448 format!("{}{}", val as u128, self.ty_to_string())
1451 pub fn bit_width(&self) -> Option<usize> {
1453 IntTy::Isize => return None,
1463 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1474 pub fn ty_to_string(&self) -> &'static str {
1476 UintTy::Usize => "usize",
1478 UintTy::U16 => "u16",
1479 UintTy::U32 => "u32",
1480 UintTy::U64 => "u64",
1481 UintTy::U128 => "u128",
1485 pub fn val_to_string(&self, val: u128) -> String {
1486 format!("{}{}", val, self.ty_to_string())
1489 pub fn bit_width(&self) -> Option<usize> {
1491 UintTy::Usize => return None,
1496 UintTy::U128 => 128,
1501 impl fmt::Debug for UintTy {
1502 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1503 fmt::Display::fmt(self, f)
1507 impl fmt::Display for UintTy {
1508 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1509 write!(f, "{}", self.ty_to_string())
1513 // Bind a type to an associated type: `A = Foo`.
1514 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1515 pub struct TypeBinding {
1522 #[derive(Clone, RustcEncodable, RustcDecodable)]
1529 impl fmt::Debug for Ty {
1530 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1531 write!(f, "type({})", pprust::ty_to_string(self))
1535 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1536 pub struct BareFnTy {
1537 pub unsafety: Unsafety,
1539 pub generic_params: Vec<GenericParam>,
1540 pub decl: P<FnDecl>,
1543 /// The different kinds of types recognized by the compiler.
1544 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1546 /// A variable-length slice (`[T]`).
1548 /// A fixed length array (`[T; n]`).
1549 Array(P<Ty>, AnonConst),
1550 /// A raw pointer (`*const T` or `*mut T`).
1552 /// A reference (`&'a T` or `&'a mut T`).
1553 Rptr(Option<Lifetime>, MutTy),
1554 /// A bare function (e.g., `fn(usize) -> bool`).
1555 BareFn(P<BareFnTy>),
1556 /// The never type (`!`).
1558 /// A tuple (`(A, B, C, D,...)`).
1560 /// A path (`module::module::...::Type`), optionally
1561 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1563 /// Type parameters are stored in the `Path` itself.
1564 Path(Option<QSelf>, Path),
1565 /// A trait object type `Bound1 + Bound2 + Bound3`
1566 /// where `Bound` is a trait or a lifetime.
1567 TraitObject(GenericBounds, TraitObjectSyntax),
1568 /// An `impl Bound1 + Bound2 + Bound3` type
1569 /// where `Bound` is a trait or a lifetime.
1571 /// The `NodeId` exists to prevent lowering from having to
1572 /// generate `NodeId`s on the fly, which would complicate
1573 /// the generation of `existential type` items significantly.
1574 ImplTrait(NodeId, GenericBounds),
1575 /// No-op; kept solely so that we can pretty-print faithfully.
1579 /// This means the type should be inferred instead of it having been
1580 /// specified. This can appear anywhere in a type.
1582 /// Inferred type of a `self` or `&self` argument in a method.
1584 /// A macro in the type position.
1586 /// Placeholder for a kind that has failed to be defined.
1591 pub fn is_implicit_self(&self) -> bool {
1592 if let TyKind::ImplicitSelf = *self {
1599 pub fn is_unit(&self) -> bool {
1600 if let TyKind::Tup(ref tys) = *self {
1608 /// Syntax used to declare a trait object.
1609 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1610 pub enum TraitObjectSyntax {
1615 /// Inline assembly dialect.
1617 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1618 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1619 pub enum AsmDialect {
1624 /// Inline assembly.
1626 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1627 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1628 pub struct InlineAsmOutput {
1629 pub constraint: Symbol,
1632 pub is_indirect: bool,
1635 /// Inline assembly.
1637 /// E.g., `asm!("NOP");`.
1638 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1639 pub struct InlineAsm {
1641 pub asm_str_style: StrStyle,
1642 pub outputs: Vec<InlineAsmOutput>,
1643 pub inputs: Vec<(Symbol, P<Expr>)>,
1644 pub clobbers: Vec<Symbol>,
1646 pub alignstack: bool,
1647 pub dialect: AsmDialect,
1648 pub ctxt: SyntaxContext,
1651 /// An argument in a function header.
1653 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1654 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1661 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1663 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1664 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1666 /// `self`, `mut self`
1668 /// `&'lt self`, `&'lt mut self`
1669 Region(Option<Lifetime>, Mutability),
1670 /// `self: TYPE`, `mut self: TYPE`
1671 Explicit(P<Ty>, Mutability),
1674 pub type ExplicitSelf = Spanned<SelfKind>;
1677 pub fn to_self(&self) -> Option<ExplicitSelf> {
1678 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1679 if ident.name == keywords::SelfLower.name() {
1680 return match self.ty.node {
1681 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1682 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1683 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1686 self.pat.span.to(self.ty.span),
1687 SelfKind::Explicit(self.ty.clone(), mutbl),
1695 pub fn is_self(&self) -> bool {
1696 if let PatKind::Ident(_, ident, _) = self.pat.node {
1697 ident.name == keywords::SelfLower.name()
1703 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1704 let span = eself.span.to(eself_ident.span);
1705 let infer_ty = P(Ty {
1707 node: TyKind::ImplicitSelf,
1710 let arg = |mutbl, ty| Arg {
1713 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1720 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1721 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1722 SelfKind::Region(lt, mutbl) => arg(
1723 Mutability::Immutable,
1740 /// Header (not the body) of a function declaration.
1742 /// E.g., `fn foo(bar: baz)`.
1743 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1745 pub inputs: Vec<Arg>,
1746 pub output: FunctionRetTy,
1751 pub fn get_self(&self) -> Option<ExplicitSelf> {
1752 self.inputs.get(0).and_then(Arg::to_self)
1754 pub fn has_self(&self) -> bool {
1755 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1759 /// Is the trait definition an auto trait?
1760 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1766 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1772 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1776 return_impl_trait_id: NodeId,
1782 pub fn is_async(self) -> bool {
1783 if let IsAsync::Async { .. } = self {
1790 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1791 pub fn opt_return_id(self) -> Option<NodeId> {
1794 return_impl_trait_id,
1796 } => Some(return_impl_trait_id),
1797 IsAsync::NotAsync => None,
1802 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1803 pub enum Constness {
1808 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1809 pub enum Defaultness {
1814 impl fmt::Display for Unsafety {
1815 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1818 Unsafety::Normal => "normal",
1819 Unsafety::Unsafe => "unsafe",
1826 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1827 pub enum ImplPolarity {
1828 /// `impl Trait for Type`
1830 /// `impl !Trait for Type`
1834 impl fmt::Debug for ImplPolarity {
1835 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1837 ImplPolarity::Positive => "positive".fmt(f),
1838 ImplPolarity::Negative => "negative".fmt(f),
1843 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1844 pub enum FunctionRetTy {
1845 /// Return type is not specified.
1847 /// Functions default to `()` and closures default to inference.
1848 /// Span points to where return type would be inserted.
1850 /// Everything else.
1854 impl FunctionRetTy {
1855 pub fn span(&self) -> Span {
1857 FunctionRetTy::Default(span) => span,
1858 FunctionRetTy::Ty(ref ty) => ty.span,
1863 /// Module declaration.
1865 /// E.g., `mod foo;` or `mod foo { .. }`.
1866 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1868 /// A span from the first token past `{` to the last token until `}`.
1869 /// For `mod foo;`, the inner span ranges from the first token
1870 /// to the last token in the external file.
1872 pub items: Vec<P<Item>>,
1873 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
1877 /// Foreign module declaration.
1879 /// E.g., `extern { .. }` or `extern C { .. }`.
1880 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1881 pub struct ForeignMod {
1883 pub items: Vec<ForeignItem>,
1886 /// Global inline assembly.
1888 /// Also known as "module-level assembly" or "file-scoped assembly".
1889 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1890 pub struct GlobalAsm {
1892 pub ctxt: SyntaxContext,
1895 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1896 pub struct EnumDef {
1897 pub variants: Vec<Variant>,
1900 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1901 pub struct Variant_ {
1903 pub attrs: Vec<Attribute>,
1904 pub data: VariantData,
1905 /// Explicit discriminant, e.g., `Foo = 1`.
1906 pub disr_expr: Option<AnonConst>,
1909 pub type Variant = Spanned<Variant_>;
1911 /// Part of `use` item to the right of its prefix.
1912 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1913 pub enum UseTreeKind {
1914 /// `use prefix` or `use prefix as rename`
1916 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1918 Simple(Option<Ident>, NodeId, NodeId),
1919 /// `use prefix::{...}`
1920 Nested(Vec<(UseTree, NodeId)>),
1925 /// A tree of paths sharing common prefixes.
1926 /// Used in `use` items both at top-level and inside of braces in import groups.
1927 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1928 pub struct UseTree {
1930 pub kind: UseTreeKind,
1935 pub fn ident(&self) -> Ident {
1937 UseTreeKind::Simple(Some(rename), ..) => rename,
1938 UseTreeKind::Simple(None, ..) => {
1942 .expect("empty prefix in a simple import")
1945 _ => panic!("`UseTree::ident` can only be used on a simple import"),
1950 /// Distinguishes between `Attribute`s that decorate items and Attributes that
1951 /// are contained as statements within items. These two cases need to be
1952 /// distinguished for pretty-printing.
1953 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1954 pub enum AttrStyle {
1960 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
1962 pub struct AttrId(pub usize);
1964 impl Idx for AttrId {
1965 fn new(idx: usize) -> Self {
1968 fn index(self) -> usize {
1973 /// Metadata associated with an item.
1974 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
1975 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1976 pub struct Attribute {
1978 pub style: AttrStyle,
1980 pub tokens: TokenStream,
1981 pub is_sugared_doc: bool,
1985 /// `TraitRef`s appear in impls.
1987 /// Resolve maps each `TraitRef`'s `ref_id` to its defining trait; that's all
1988 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
1989 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
1990 /// same as the impl's node-id).
1991 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1992 pub struct TraitRef {
1997 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1998 pub struct PolyTraitRef {
1999 /// The `'a` in `<'a> Foo<&'a T>`
2000 pub bound_generic_params: Vec<GenericParam>,
2002 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2003 pub trait_ref: TraitRef,
2009 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2011 bound_generic_params: generic_params,
2012 trait_ref: TraitRef {
2014 ref_id: DUMMY_NODE_ID,
2021 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2022 pub enum CrateSugar {
2023 /// Source is `pub(crate)`.
2026 /// Source is (just) `crate`.
2030 pub type Visibility = Spanned<VisibilityKind>;
2032 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2033 pub enum VisibilityKind {
2036 Restricted { path: P<Path>, id: NodeId },
2040 impl VisibilityKind {
2041 pub fn is_pub(&self) -> bool {
2042 if let VisibilityKind::Public = *self {
2050 /// Field of a struct.
2052 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2053 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2054 pub struct StructField {
2056 pub ident: Option<Ident>,
2057 pub vis: Visibility,
2060 pub attrs: Vec<Attribute>,
2063 /// Fields and Ids of enum variants and structs
2065 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2066 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2067 /// One shared Id can be successfully used for these two purposes.
2068 /// Id of the whole enum lives in `Item`.
2070 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2071 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2072 /// the variant itself" from enum variants.
2073 /// Id of the whole struct lives in `Item`.
2074 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2075 pub enum VariantData {
2078 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2079 Struct(Vec<StructField>, NodeId),
2082 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2083 Tuple(Vec<StructField>, NodeId),
2086 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2091 pub fn fields(&self) -> &[StructField] {
2093 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2097 pub fn id(&self) -> NodeId {
2099 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2102 pub fn is_struct(&self) -> bool {
2103 if let VariantData::Struct(..) = *self {
2109 pub fn is_tuple(&self) -> bool {
2110 if let VariantData::Tuple(..) = *self {
2116 pub fn is_unit(&self) -> bool {
2117 if let VariantData::Unit(..) = *self {
2127 /// The name might be a dummy name in case of anonymous items.
2128 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2131 pub attrs: Vec<Attribute>,
2134 pub vis: Visibility,
2137 /// Original tokens this item was parsed from. This isn't necessarily
2138 /// available for all items, although over time more and more items should
2139 /// have this be `Some`. Right now this is primarily used for procedural
2140 /// macros, notably custom attributes.
2142 /// Note that the tokens here do not include the outer attributes, but will
2143 /// include inner attributes.
2144 pub tokens: Option<TokenStream>,
2147 /// A function header.
2149 /// All the information between the visibility and the name of the function is
2150 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2151 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2152 pub struct FnHeader {
2153 pub unsafety: Unsafety,
2154 pub asyncness: IsAsync,
2155 pub constness: Spanned<Constness>,
2159 impl Default for FnHeader {
2160 fn default() -> FnHeader {
2162 unsafety: Unsafety::Normal,
2163 asyncness: IsAsync::NotAsync,
2164 constness: dummy_spanned(Constness::NotConst),
2170 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2172 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2174 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2175 ExternCrate(Option<Name>),
2176 /// A use declaration (`use` or `pub use`) item.
2178 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2180 /// A static item (`static` or `pub static`).
2182 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2183 Static(P<Ty>, Mutability, P<Expr>),
2184 /// A constant item (`const` or `pub const`).
2186 /// E.g., `const FOO: i32 = 42;`.
2187 Const(P<Ty>, P<Expr>),
2188 /// A function declaration (`fn` or `pub fn`).
2190 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2191 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2192 /// A module declaration (`mod` or `pub mod`).
2194 /// E.g., `mod foo;` or `mod foo { .. }`.
2196 /// An external module (`extern` or `pub extern`).
2198 /// E.g., `extern {}` or `extern "C" {}`.
2199 ForeignMod(ForeignMod),
2200 /// Module-level inline assembly (from `global_asm!()`).
2201 GlobalAsm(P<GlobalAsm>),
2202 /// A type alias (`type` or `pub type`).
2204 /// E.g., `type Foo = Bar<u8>;`.
2205 Ty(P<Ty>, Generics),
2206 /// An existential type declaration (`existential type`).
2208 /// E.g., `existential type Foo: Bar + Boo;`.
2209 Existential(GenericBounds, Generics),
2210 /// An enum definition (`enum` or `pub enum`).
2212 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2213 Enum(EnumDef, Generics),
2214 /// A struct definition (`struct` or `pub struct`).
2216 /// E.g., `struct Foo<A> { x: A }`.
2217 Struct(VariantData, Generics),
2218 /// A union definition (`union` or `pub union`).
2220 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2221 Union(VariantData, Generics),
2222 /// A Trait declaration (`trait` or `pub trait`).
2224 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2225 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2228 /// E.g., `trait Foo = Bar + Quux;`.
2229 TraitAlias(Generics, GenericBounds),
2230 /// An implementation.
2232 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2238 Option<TraitRef>, // (optional) trait this impl implements
2242 /// A macro invocation.
2244 /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2247 /// A macro definition.
2252 pub fn descriptive_variant(&self) -> &str {
2254 ItemKind::ExternCrate(..) => "extern crate",
2255 ItemKind::Use(..) => "use",
2256 ItemKind::Static(..) => "static item",
2257 ItemKind::Const(..) => "constant item",
2258 ItemKind::Fn(..) => "function",
2259 ItemKind::Mod(..) => "module",
2260 ItemKind::ForeignMod(..) => "foreign module",
2261 ItemKind::GlobalAsm(..) => "global asm",
2262 ItemKind::Ty(..) => "type alias",
2263 ItemKind::Existential(..) => "existential type",
2264 ItemKind::Enum(..) => "enum",
2265 ItemKind::Struct(..) => "struct",
2266 ItemKind::Union(..) => "union",
2267 ItemKind::Trait(..) => "trait",
2268 ItemKind::TraitAlias(..) => "trait alias",
2269 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2274 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2275 pub struct ForeignItem {
2277 pub attrs: Vec<Attribute>,
2278 pub node: ForeignItemKind,
2281 pub vis: Visibility,
2284 /// An item within an `extern` block.
2285 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2286 pub enum ForeignItemKind {
2287 /// A foreign function.
2288 Fn(P<FnDecl>, Generics),
2289 /// A foreign static item (`static ext: u8`), with optional mutability.
2290 /// (The boolean is `true` for mutable items).
2291 Static(P<Ty>, bool),
2294 /// A macro invocation.
2298 impl ForeignItemKind {
2299 pub fn descriptive_variant(&self) -> &str {
2301 ForeignItemKind::Fn(..) => "foreign function",
2302 ForeignItemKind::Static(..) => "foreign static item",
2303 ForeignItemKind::Ty => "foreign type",
2304 ForeignItemKind::Macro(..) => "macro in foreign module",
2314 // Are ASTs encodable?
2316 fn check_asts_encodable() {
2317 fn assert_encodable<T: serialize::Encodable>() {}
2318 assert_encodable::<Crate>();