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.
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 MetaItems 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 `Expr`s 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 (`(a, b, c ,d)`)
1060 /// A binary operation (For example: `a + b`, `a * b`)
1061 Binary(BinOp, P<Expr>, P<Expr>),
1062 /// A unary operation (For example: `!x`, `*x`)
1063 Unary(UnOp, P<Expr>),
1064 /// A literal (For example: `1`, `"foo"`)
1066 /// A cast (`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 (for example, `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
1123 /// For example, `a += 1`.
1124 AssignOp(BinOp, P<Expr>, P<Expr>),
1125 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct field
1126 Field(P<Expr>, Ident),
1127 /// An indexing operation (`foo[2]`)
1128 Index(P<Expr>, P<Expr>),
1129 /// A range (`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",
1136 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
1137 Path(Option<QSelf>, Path),
1139 /// A referencing operation (`&a` or `&mut a`)
1140 AddrOf(Mutability, P<Expr>),
1141 /// A `break`, with an optional label to break, and an optional expression
1142 Break(Option<Label>, Option<P<Expr>>),
1143 /// A `continue`, with an optional label
1144 Continue(Option<Label>),
1145 /// A `return`, with an optional value to be returned
1146 Ret(Option<P<Expr>>),
1148 /// Output of the `asm!()` macro
1149 InlineAsm(P<InlineAsm>),
1151 /// A macro invocation; pre-expansion
1154 /// A struct literal expression.
1156 /// For example, `Foo {x: 1, y: 2}`, or
1157 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1158 Struct(Path, Vec<Field>, Option<P<Expr>>),
1160 /// An array literal constructed from one repeated element.
1162 /// For example, `[1; 5]`. The expression is the element to be
1163 /// repeated; the constant is the number of times to repeat it.
1164 Repeat(P<Expr>, AnonConst),
1166 /// No-op: used solely so we can pretty-print faithfully
1172 /// A `yield`, with an optional value to be yielded
1173 Yield(Option<P<Expr>>),
1176 /// The explicit Self type in a "qualified path". The actual
1177 /// path, including the trait and the associated item, is stored
1178 /// separately. `position` represents the index of the associated
1179 /// item qualified with this Self type.
1181 /// ```ignore (only-for-syntax-highlight)
1182 /// <Vec<T> as a::b::Trait>::AssociatedItem
1183 /// ^~~~~ ~~~~~~~~~~~~~~^
1186 /// <Vec<T>>::AssociatedItem
1190 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1194 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1195 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1196 /// 0`, this is an empty span.
1197 pub path_span: Span,
1198 pub position: usize,
1201 /// A capture clause
1202 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1203 pub enum CaptureBy {
1208 /// The movability of a generator / closure literal
1209 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1210 pub enum Movability {
1215 pub type Mac = Spanned<Mac_>;
1217 /// Represents a macro invocation. The Path indicates which macro
1218 /// is being invoked, and the vector of token-trees contains the source
1219 /// of the macro invocation.
1221 /// NB: the additional ident for a macro_rules-style macro is actually
1222 /// stored in the enclosing item. Oog.
1223 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1226 pub delim: MacDelimiter,
1227 pub tts: ThinTokenStream,
1230 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1231 pub enum MacDelimiter {
1238 pub fn stream(&self) -> TokenStream {
1239 self.tts.clone().into()
1243 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1244 pub struct MacroDef {
1245 pub tokens: ThinTokenStream,
1250 pub fn stream(&self) -> TokenStream {
1251 self.tokens.clone().into()
1255 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1257 /// A regular string, like `"foo"`
1259 /// A raw string, like `r##"foo"##`
1261 /// The value is the number of `#` symbols used.
1266 pub type Lit = Spanned<LitKind>;
1268 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1269 pub enum LitIntType {
1277 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1278 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1280 /// A string literal (`"foo"`)
1281 Str(Symbol, StrStyle),
1282 /// A byte string (`b"foo"`)
1283 ByteStr(Lrc<Vec<u8>>),
1284 /// A byte char (`b'f'`)
1286 /// A character literal (`'a'`)
1288 /// An integer literal (`1`)
1289 Int(u128, LitIntType),
1290 /// A float literal (`1f64` or `1E10f64`)
1291 Float(Symbol, FloatTy),
1292 /// A float literal without a suffix (`1.0 or 1.0E10`)
1293 FloatUnsuffixed(Symbol),
1294 /// A boolean literal
1299 /// Returns true if this literal is a string and false otherwise.
1300 pub fn is_str(&self) -> bool {
1302 LitKind::Str(..) => true,
1307 /// Returns true if this literal is byte literal string false otherwise.
1308 pub fn is_bytestr(&self) -> bool {
1310 LitKind::ByteStr(_) => true,
1315 /// Returns true if this is a numeric literal.
1316 pub fn is_numeric(&self) -> bool {
1318 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1323 /// Returns true if this literal has no suffix. Note: this will return true
1324 /// for literals with prefixes such as raw strings and byte strings.
1325 pub fn is_unsuffixed(&self) -> bool {
1327 // unsuffixed variants
1329 | LitKind::ByteStr(..)
1332 | LitKind::Int(_, LitIntType::Unsuffixed)
1333 | LitKind::FloatUnsuffixed(..)
1334 | LitKind::Bool(..) => true,
1335 // suffixed variants
1336 LitKind::Int(_, LitIntType::Signed(..))
1337 | LitKind::Int(_, LitIntType::Unsigned(..))
1338 | LitKind::Float(..) => false,
1342 /// Returns true if this literal has a suffix.
1343 pub fn is_suffixed(&self) -> bool {
1344 !self.is_unsuffixed()
1348 // NB: If you change this, you'll probably want to change the corresponding
1349 // type structure in middle/ty.rs as well.
1350 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1353 pub mutbl: Mutability,
1356 /// Represents a method's signature in a trait declaration,
1357 /// or in an implementation.
1358 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1359 pub struct MethodSig {
1360 pub header: FnHeader,
1361 pub decl: P<FnDecl>,
1364 /// Represents an item declaration within a trait declaration,
1365 /// possibly including a default implementation. A trait item is
1366 /// either required (meaning it doesn't have an implementation, just a
1367 /// signature) or provided (meaning it has a default implementation).
1368 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1369 pub struct TraitItem {
1372 pub attrs: Vec<Attribute>,
1373 pub generics: Generics,
1374 pub node: TraitItemKind,
1376 /// See `Item::tokens` for what this is
1377 pub tokens: Option<TokenStream>,
1380 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1381 pub enum TraitItemKind {
1382 Const(P<Ty>, Option<P<Expr>>),
1383 Method(MethodSig, Option<P<Block>>),
1384 Type(GenericBounds, Option<P<Ty>>),
1388 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1389 pub struct ImplItem {
1392 pub vis: Visibility,
1393 pub defaultness: Defaultness,
1394 pub attrs: Vec<Attribute>,
1395 pub generics: Generics,
1396 pub node: ImplItemKind,
1398 /// See `Item::tokens` for what this is
1399 pub tokens: Option<TokenStream>,
1402 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1403 pub enum ImplItemKind {
1404 Const(P<Ty>, P<Expr>),
1405 Method(MethodSig, P<Block>),
1407 Existential(GenericBounds),
1411 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1421 impl fmt::Debug for IntTy {
1422 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1423 fmt::Display::fmt(self, f)
1427 impl fmt::Display for IntTy {
1428 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1429 write!(f, "{}", self.ty_to_string())
1434 pub fn ty_to_string(&self) -> &'static str {
1436 IntTy::Isize => "isize",
1438 IntTy::I16 => "i16",
1439 IntTy::I32 => "i32",
1440 IntTy::I64 => "i64",
1441 IntTy::I128 => "i128",
1445 pub fn val_to_string(&self, val: i128) -> String {
1446 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1447 // are parsed as u128, so we wouldn't want to print an extra negative
1449 format!("{}{}", val as u128, self.ty_to_string())
1452 pub fn bit_width(&self) -> Option<usize> {
1454 IntTy::Isize => return None,
1464 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1475 pub fn ty_to_string(&self) -> &'static str {
1477 UintTy::Usize => "usize",
1479 UintTy::U16 => "u16",
1480 UintTy::U32 => "u32",
1481 UintTy::U64 => "u64",
1482 UintTy::U128 => "u128",
1486 pub fn val_to_string(&self, val: u128) -> String {
1487 format!("{}{}", val, self.ty_to_string())
1490 pub fn bit_width(&self) -> Option<usize> {
1492 UintTy::Usize => return None,
1497 UintTy::U128 => 128,
1502 impl fmt::Debug for UintTy {
1503 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1504 fmt::Display::fmt(self, f)
1508 impl fmt::Display for UintTy {
1509 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1510 write!(f, "{}", self.ty_to_string())
1514 // Bind a type to an associated type: `A=Foo`.
1515 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1516 pub struct TypeBinding {
1523 #[derive(Clone, RustcEncodable, RustcDecodable)]
1530 impl fmt::Debug for Ty {
1531 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1532 write!(f, "type({})", pprust::ty_to_string(self))
1536 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1537 pub struct BareFnTy {
1538 pub unsafety: Unsafety,
1540 pub generic_params: Vec<GenericParam>,
1541 pub decl: P<FnDecl>,
1544 /// The different kinds of types recognized by the compiler
1545 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1547 /// A variable-length slice (`[T]`)
1549 /// A fixed length array (`[T; n]`)
1550 Array(P<Ty>, AnonConst),
1551 /// A raw pointer (`*const T` or `*mut T`)
1553 /// A reference (`&'a T` or `&'a mut T`)
1554 Rptr(Option<Lifetime>, MutTy),
1555 /// A bare function (e.g. `fn(usize) -> bool`)
1556 BareFn(P<BareFnTy>),
1557 /// The never type (`!`)
1559 /// A tuple (`(A, B, C, D,...)`)
1561 /// A path (`module::module::...::Type`), optionally
1562 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1564 /// Type parameters are stored in the Path itself
1565 Path(Option<QSelf>, Path),
1566 /// A trait object type `Bound1 + Bound2 + Bound3`
1567 /// where `Bound` is a trait or a lifetime.
1568 TraitObject(GenericBounds, TraitObjectSyntax),
1569 /// An `impl Bound1 + Bound2 + Bound3` type
1570 /// where `Bound` is a trait or a lifetime.
1572 /// The `NodeId` exists to prevent lowering from having to
1573 /// generate `NodeId`s on the fly, which would complicate
1574 /// the generation of `existential type` items significantly
1575 ImplTrait(NodeId, GenericBounds),
1576 /// No-op; kept solely so that we can pretty-print faithfully
1580 /// TyKind::Infer means the type should be inferred instead of it having been
1581 /// specified. This can appear anywhere in a type.
1583 /// Inferred type of a `self` or `&self` argument in a method.
1585 // A macro in the type position.
1587 /// Placeholder for a kind that has failed to be defined.
1592 pub fn is_implicit_self(&self) -> bool {
1593 if let TyKind::ImplicitSelf = *self {
1600 pub fn is_unit(&self) -> bool {
1601 if let TyKind::Tup(ref tys) = *self {
1609 /// Syntax used to declare a trait object.
1610 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1611 pub enum TraitObjectSyntax {
1616 /// Inline assembly dialect.
1618 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1619 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1620 pub enum AsmDialect {
1625 /// Inline assembly.
1627 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1628 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1629 pub struct InlineAsmOutput {
1630 pub constraint: Symbol,
1633 pub is_indirect: bool,
1636 /// Inline assembly.
1638 /// E.g. `asm!("NOP");`
1639 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1640 pub struct InlineAsm {
1642 pub asm_str_style: StrStyle,
1643 pub outputs: Vec<InlineAsmOutput>,
1644 pub inputs: Vec<(Symbol, P<Expr>)>,
1645 pub clobbers: Vec<Symbol>,
1647 pub alignstack: bool,
1648 pub dialect: AsmDialect,
1649 pub ctxt: SyntaxContext,
1652 /// An argument in a function header.
1654 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1655 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1662 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1664 /// E.g. `&mut self` as in `fn foo(&mut self)`
1665 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1667 /// `self`, `mut self`
1669 /// `&'lt self`, `&'lt mut self`
1670 Region(Option<Lifetime>, Mutability),
1671 /// `self: TYPE`, `mut self: TYPE`
1672 Explicit(P<Ty>, Mutability),
1675 pub type ExplicitSelf = Spanned<SelfKind>;
1678 pub fn to_self(&self) -> Option<ExplicitSelf> {
1679 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1680 if ident.name == keywords::SelfLower.name() {
1681 return match self.ty.node {
1682 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1683 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1684 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1687 self.pat.span.to(self.ty.span),
1688 SelfKind::Explicit(self.ty.clone(), mutbl),
1696 pub fn is_self(&self) -> bool {
1697 if let PatKind::Ident(_, ident, _) = self.pat.node {
1698 ident.name == keywords::SelfLower.name()
1704 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1705 let span = eself.span.to(eself_ident.span);
1706 let infer_ty = P(Ty {
1708 node: TyKind::ImplicitSelf,
1711 let arg = |mutbl, ty| Arg {
1714 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1721 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1722 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1723 SelfKind::Region(lt, mutbl) => arg(
1724 Mutability::Immutable,
1741 /// Header (not the body) of a function declaration.
1743 /// E.g. `fn foo(bar: baz)`
1744 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1746 pub inputs: Vec<Arg>,
1747 pub output: FunctionRetTy,
1752 pub fn get_self(&self) -> Option<ExplicitSelf> {
1753 self.inputs.get(0).and_then(Arg::to_self)
1755 pub fn has_self(&self) -> bool {
1756 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1760 /// Is the trait definition an auto trait?
1761 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1767 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1773 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1777 return_impl_trait_id: NodeId,
1783 pub fn is_async(self) -> bool {
1784 if let IsAsync::Async { .. } = self {
1790 /// In 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
1848 /// closures default to inference. Span points to where return
1849 /// type would be inserted.
1855 impl FunctionRetTy {
1856 pub fn span(&self) -> Span {
1858 FunctionRetTy::Default(span) => span,
1859 FunctionRetTy::Ty(ref ty) => ty.span,
1864 /// Module declaration.
1866 /// E.g. `mod foo;` or `mod foo { .. }`
1867 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1869 /// A span from the first token past `{` to the last token until `}`.
1870 /// For `mod foo;`, the inner span ranges from the first token
1871 /// to the last token in the external file.
1873 pub items: Vec<P<Item>>,
1874 /// For `mod foo;` inline is false, for `mod foo { .. }` it is true.
1878 /// Foreign module declaration.
1880 /// E.g. `extern { .. }` or `extern C { .. }`
1881 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1882 pub struct ForeignMod {
1884 pub items: Vec<ForeignItem>,
1887 /// Global inline assembly
1889 /// aka module-level assembly or file-scoped assembly
1890 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1891 pub struct GlobalAsm {
1893 pub ctxt: SyntaxContext,
1896 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1897 pub struct EnumDef {
1898 pub variants: Vec<Variant>,
1901 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1902 pub struct Variant_ {
1904 pub attrs: Vec<Attribute>,
1905 pub data: VariantData,
1906 /// Explicit discriminant, e.g. `Foo = 1`
1907 pub disr_expr: Option<AnonConst>,
1910 pub type Variant = Spanned<Variant_>;
1912 /// Part of `use` item to the right of its prefix.
1913 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1914 pub enum UseTreeKind {
1915 /// `use prefix` or `use prefix as rename`
1917 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1919 Simple(Option<Ident>, NodeId, NodeId),
1920 /// `use prefix::{...}`
1921 Nested(Vec<(UseTree, NodeId)>),
1926 /// A tree of paths sharing common prefixes.
1927 /// Used in `use` items both at top-level and inside of braces in import groups.
1928 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1929 pub struct UseTree {
1931 pub kind: UseTreeKind,
1936 pub fn ident(&self) -> Ident {
1938 UseTreeKind::Simple(Some(rename), ..) => rename,
1939 UseTreeKind::Simple(None, ..) => {
1943 .expect("empty prefix in a simple import")
1946 _ => panic!("`UseTree::ident` can only be used on a simple import"),
1951 /// Distinguishes between Attributes that decorate items and Attributes that
1952 /// are contained as statements within items. These two cases need to be
1953 /// distinguished for pretty-printing.
1954 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1955 pub enum AttrStyle {
1961 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
1963 pub struct AttrId(pub usize);
1965 impl Idx for AttrId {
1966 fn new(idx: usize) -> Self {
1969 fn index(self) -> usize {
1974 /// Meta-data associated with an item
1975 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1976 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1977 pub struct Attribute {
1979 pub style: AttrStyle,
1981 pub tokens: TokenStream,
1982 pub is_sugared_doc: bool,
1986 /// TraitRef's appear in impls.
1988 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1989 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1990 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1991 /// same as the impl's node id).
1992 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1993 pub struct TraitRef {
1998 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1999 pub struct PolyTraitRef {
2000 /// The `'a` in `<'a> Foo<&'a T>`
2001 pub bound_generic_params: Vec<GenericParam>,
2003 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2004 pub trait_ref: TraitRef,
2010 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2012 bound_generic_params: generic_params,
2013 trait_ref: TraitRef {
2015 ref_id: DUMMY_NODE_ID,
2022 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2023 pub enum CrateSugar {
2024 /// Source is `pub(crate)`
2027 /// Source is (just) `crate`
2031 pub type Visibility = Spanned<VisibilityKind>;
2033 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2034 pub enum VisibilityKind {
2037 Restricted { path: P<Path>, id: NodeId },
2041 impl VisibilityKind {
2042 pub fn is_pub(&self) -> bool {
2043 if let VisibilityKind::Public = *self {
2051 /// Field of a struct.
2053 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
2054 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2055 pub struct StructField {
2057 pub ident: Option<Ident>,
2058 pub vis: Visibility,
2061 pub attrs: Vec<Attribute>,
2064 /// Fields and Ids of enum variants and structs
2066 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2067 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2068 /// One shared Id can be successfully used for these two purposes.
2069 /// Id of the whole enum lives in `Item`.
2071 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2072 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2073 /// the variant itself" from enum variants.
2074 /// Id of the whole struct lives in `Item`.
2075 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2076 pub enum VariantData {
2079 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
2080 Struct(Vec<StructField>, NodeId),
2083 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
2084 Tuple(Vec<StructField>, NodeId),
2087 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
2092 pub fn fields(&self) -> &[StructField] {
2094 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2098 pub fn id(&self) -> NodeId {
2100 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2103 pub fn is_struct(&self) -> bool {
2104 if let VariantData::Struct(..) = *self {
2110 pub fn is_tuple(&self) -> bool {
2111 if let VariantData::Tuple(..) = *self {
2117 pub fn is_unit(&self) -> bool {
2118 if let VariantData::Unit(..) = *self {
2128 /// The name might be a dummy name in case of anonymous items
2129 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2132 pub attrs: Vec<Attribute>,
2135 pub vis: Visibility,
2138 /// Original tokens this item was parsed from. This isn't necessarily
2139 /// available for all items, although over time more and more items should
2140 /// have this be `Some`. Right now this is primarily used for procedural
2141 /// macros, notably custom attributes.
2143 /// Note that the tokens here do not include the outer attributes, but will
2144 /// include inner attributes.
2145 pub tokens: Option<TokenStream>,
2148 /// A function header
2150 /// All the information between the visibility & the name of the function is
2151 /// included in this struct (e.g. `async unsafe fn` or `const extern "C" fn`)
2152 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2153 pub struct FnHeader {
2154 pub unsafety: Unsafety,
2155 pub asyncness: IsAsync,
2156 pub constness: Spanned<Constness>,
2160 impl Default for FnHeader {
2161 fn default() -> FnHeader {
2163 unsafety: Unsafety::Normal,
2164 asyncness: IsAsync::NotAsync,
2165 constness: dummy_spanned(Constness::NotConst),
2171 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2173 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2175 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2176 ExternCrate(Option<Name>),
2177 /// A use declaration (`use` or `pub use`) item.
2179 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
2181 /// A static item (`static` or `pub static`).
2183 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
2184 Static(P<Ty>, Mutability, P<Expr>),
2185 /// A constant item (`const` or `pub const`).
2187 /// E.g. `const FOO: i32 = 42;`
2188 Const(P<Ty>, P<Expr>),
2189 /// A function declaration (`fn` or `pub fn`).
2191 /// E.g. `fn foo(bar: usize) -> usize { .. }`
2192 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2193 /// A module declaration (`mod` or `pub mod`).
2195 /// E.g. `mod foo;` or `mod foo { .. }`
2197 /// An external module (`extern` or `pub extern`).
2199 /// E.g. `extern {}` or `extern "C" {}`
2200 ForeignMod(ForeignMod),
2201 /// Module-level inline assembly (from `global_asm!()`)
2202 GlobalAsm(P<GlobalAsm>),
2203 /// A type alias (`type` or `pub type`).
2205 /// E.g. `type Foo = Bar<u8>;`
2206 Ty(P<Ty>, Generics),
2207 /// An existential type declaration (`existential type`).
2209 /// E.g. `existential type Foo: Bar + Boo;`
2210 Existential(GenericBounds, Generics),
2211 /// An enum definition (`enum` or `pub enum`).
2213 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
2214 Enum(EnumDef, Generics),
2215 /// A struct definition (`struct` or `pub struct`).
2217 /// E.g. `struct Foo<A> { x: A }`
2218 Struct(VariantData, Generics),
2219 /// A union definition (`union` or `pub union`).
2221 /// E.g. `union Foo<A, B> { x: A, y: B }`
2222 Union(VariantData, Generics),
2223 /// A Trait declaration (`trait` or `pub trait`).
2225 /// E.g. `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`
2226 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2229 /// E.g. `trait Foo = Bar + Quux;`
2230 TraitAlias(Generics, GenericBounds),
2231 /// An implementation.
2233 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
2239 Option<TraitRef>, // (optional) trait this impl implements
2243 /// A macro invocation.
2245 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
2248 /// A macro definition.
2253 pub fn descriptive_variant(&self) -> &str {
2255 ItemKind::ExternCrate(..) => "extern crate",
2256 ItemKind::Use(..) => "use",
2257 ItemKind::Static(..) => "static item",
2258 ItemKind::Const(..) => "constant item",
2259 ItemKind::Fn(..) => "function",
2260 ItemKind::Mod(..) => "module",
2261 ItemKind::ForeignMod(..) => "foreign module",
2262 ItemKind::GlobalAsm(..) => "global asm",
2263 ItemKind::Ty(..) => "type alias",
2264 ItemKind::Existential(..) => "existential type",
2265 ItemKind::Enum(..) => "enum",
2266 ItemKind::Struct(..) => "struct",
2267 ItemKind::Union(..) => "union",
2268 ItemKind::Trait(..) => "trait",
2269 ItemKind::TraitAlias(..) => "trait alias",
2270 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2275 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2276 pub struct ForeignItem {
2278 pub attrs: Vec<Attribute>,
2279 pub node: ForeignItemKind,
2282 pub vis: Visibility,
2285 /// An item within an `extern` block
2286 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2287 pub enum ForeignItemKind {
2288 /// A foreign function
2289 Fn(P<FnDecl>, Generics),
2290 /// A foreign static item (`static ext: u8`), with optional mutability
2291 /// (the boolean is true when mutable)
2292 Static(P<Ty>, bool),
2295 /// A macro invocation
2299 impl ForeignItemKind {
2300 pub fn descriptive_variant(&self) -> &str {
2302 ForeignItemKind::Fn(..) => "foreign function",
2303 ForeignItemKind::Static(..) => "foreign static item",
2304 ForeignItemKind::Ty => "foreign type",
2305 ForeignItemKind::Macro(..) => "macro in foreign module",
2315 // are ASTs encodable?
2317 fn check_asts_encodable() {
2318 fn assert_encodable<T: serialize::Encodable>() {}
2319 assert_encodable::<Crate>();