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;
22 use rustc_data_structures::indexed_vec::Idx;
23 #[cfg(target_arch = "x86_64")]
24 use rustc_data_structures::static_assert;
25 use rustc_target::spec::abi::Abi;
26 use source_map::{dummy_spanned, respan, Spanned};
27 use symbol::{keywords, Symbol};
28 use syntax_pos::{Span, DUMMY_SP};
29 use tokenstream::{ThinTokenStream, TokenStream};
32 use rustc_data_structures::fx::FxHashSet;
33 use rustc_data_structures::sync::Lrc;
34 use serialize::{self, Decoder, Encoder};
38 pub use rustc_target::abi::FloatTy;
40 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
45 impl fmt::Debug for Label {
46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47 write!(f, "label({:?})", self.ident)
51 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
57 impl fmt::Debug for Lifetime {
58 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63 pprust::lifetime_to_string(self)
68 /// A "Path" is essentially Rust's notion of a name.
70 /// It's represented as a sequence of identifiers,
71 /// along with a bunch of supporting information.
73 /// E.g. `std::cmp::PartialEq`
74 #[derive(Clone, RustcEncodable, RustcDecodable)]
77 /// The segments in the path: the things separated by `::`.
78 /// Global paths begin with `keywords::CrateRoot`.
79 pub segments: Vec<PathSegment>,
82 impl<'a> PartialEq<&'a str> for Path {
83 fn eq(&self, string: &&'a str) -> bool {
84 self.segments.len() == 1 && self.segments[0].ident.name == *string
88 impl fmt::Debug for Path {
89 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90 write!(f, "path({})", pprust::path_to_string(self))
94 impl fmt::Display for Path {
95 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96 write!(f, "{}", pprust::path_to_string(self))
101 // convert a span and an identifier to the corresponding
103 pub fn from_ident(ident: Ident) -> Path {
105 segments: vec![PathSegment::from_ident(ident)],
110 // Make a "crate root" segment for this path unless it already has it
111 // or starts with something like `self`/`super`/`$crate`/etc.
112 pub fn make_root(&self) -> Option<PathSegment> {
113 if let Some(ident) = self.segments.get(0).map(|seg| seg.ident) {
114 if ident.is_path_segment_keyword() {
118 Some(PathSegment::crate_root(self.span.shrink_to_lo()))
121 pub fn is_global(&self) -> bool {
122 !self.segments.is_empty() && self.segments[0].ident.name == keywords::CrateRoot.name()
126 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
128 /// E.g. `std`, `String` or `Box<T>`
129 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
130 pub struct PathSegment {
131 /// The identifier portion of this path segment.
136 /// Type/lifetime parameters attached to this path. They come in
137 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
138 /// `None` means that no parameter list is supplied (`Path`),
139 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
140 /// but it can be empty (`Path<>`).
141 /// `P` is used as a size optimization for the common case with no parameters.
142 pub args: Option<P<GenericArgs>>,
146 pub fn from_ident(ident: Ident) -> Self {
147 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
149 pub fn crate_root(span: Span) -> Self {
150 PathSegment::from_ident(Ident::new(keywords::CrateRoot.name(), span))
154 /// Arguments of a path segment.
156 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
157 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
158 pub enum GenericArgs {
159 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
160 AngleBracketed(AngleBracketedArgs),
161 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
162 Parenthesized(ParenthesisedArgs),
166 pub fn span(&self) -> Span {
168 AngleBracketed(ref data) => data.span,
169 Parenthesized(ref data) => data.span,
174 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
175 pub enum GenericArg {
180 /// A path like `Foo<'a, T>`
181 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
182 pub struct AngleBracketedArgs {
185 /// The arguments for this path segment.
186 pub args: Vec<GenericArg>,
187 /// Bindings (equality constraints) on associated types, if present.
189 /// E.g., `Foo<A=Bar>`.
190 pub bindings: Vec<TypeBinding>,
193 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
194 fn into(self) -> Option<P<GenericArgs>> {
195 Some(P(GenericArgs::AngleBracketed(self)))
199 impl Into<Option<P<GenericArgs>>> for ParenthesisedArgs {
200 fn into(self) -> Option<P<GenericArgs>> {
201 Some(P(GenericArgs::Parenthesized(self)))
205 /// A path like `Foo(A,B) -> C`
206 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
207 pub struct ParenthesisedArgs {
212 pub inputs: Vec<P<Ty>>,
215 pub output: Option<P<Ty>>,
218 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
219 pub struct NodeId(u32);
222 pub fn new(x: usize) -> NodeId {
223 assert!(x < (u32::MAX as usize));
227 pub fn from_u32(x: u32) -> NodeId {
231 pub fn as_usize(&self) -> usize {
235 pub fn as_u32(&self) -> u32 {
239 pub fn placeholder_from_mark(mark: Mark) -> Self {
240 NodeId(mark.as_u32())
243 pub fn placeholder_to_mark(self) -> Mark {
244 Mark::from_u32(self.0)
248 impl fmt::Display for NodeId {
249 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
250 fmt::Display::fmt(&self.0, f)
254 impl serialize::UseSpecializedEncodable for NodeId {
255 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
260 impl serialize::UseSpecializedDecodable for NodeId {
261 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
262 d.read_u32().map(NodeId)
266 impl indexed_vec::Idx for NodeId {
267 fn new(idx: usize) -> Self {
271 fn index(self) -> usize {
276 /// Node id used to represent the root of the crate.
277 pub const CRATE_NODE_ID: NodeId = NodeId(0);
279 /// When parsing and doing expansions, we initially give all AST nodes this AST
280 /// node value. Then later, in the renumber pass, we renumber them to have
281 /// small, positive ids.
282 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
284 /// A modifier on a bound, currently this is only used for `?Sized`, where the
285 /// modifier is `Maybe`. Negative bounds should also be handled here.
286 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
287 pub enum TraitBoundModifier {
292 /// The AST represents all type param bounds as types.
293 /// `typeck::collect::compute_bounds` matches these against
294 /// the "special" built-in traits (see `middle::lang_items`) and
295 /// detects `Copy`, `Send` and `Sync`.
296 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
297 pub enum GenericBound {
298 Trait(PolyTraitRef, TraitBoundModifier),
303 pub fn span(&self) -> Span {
305 &GenericBound::Trait(ref t, ..) => t.span,
306 &GenericBound::Outlives(ref l) => l.ident.span,
311 pub type GenericBounds = Vec<GenericBound>;
313 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
314 pub enum GenericParamKind {
315 /// A lifetime definition, e.g. `'a: 'b+'c+'d`.
318 default: Option<P<Ty>>,
322 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
323 pub struct GenericParam {
326 pub attrs: ThinVec<Attribute>,
327 pub bounds: GenericBounds,
329 pub kind: GenericParamKind,
332 /// Represents lifetime, type and const parameters attached to a declaration of
333 /// a function, enum, trait, etc.
334 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
335 pub struct Generics {
336 pub params: Vec<GenericParam>,
337 pub where_clause: WhereClause,
341 impl Default for Generics {
342 /// Creates an instance of `Generics`.
343 fn default() -> Generics {
346 where_clause: WhereClause {
348 predicates: Vec::new(),
356 /// A `where` clause in a definition
357 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
358 pub struct WhereClause {
360 pub predicates: Vec<WherePredicate>,
364 /// A single predicate in a `where` clause
365 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
366 pub enum WherePredicate {
367 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
368 BoundPredicate(WhereBoundPredicate),
369 /// A lifetime predicate, e.g. `'a: 'b+'c`
370 RegionPredicate(WhereRegionPredicate),
371 /// An equality predicate (unsupported)
372 EqPredicate(WhereEqPredicate),
375 impl WherePredicate {
376 pub fn span(&self) -> Span {
378 &WherePredicate::BoundPredicate(ref p) => p.span,
379 &WherePredicate::RegionPredicate(ref p) => p.span,
380 &WherePredicate::EqPredicate(ref p) => p.span,
387 /// E.g. `for<'c> Foo: Send+Clone+'c`
388 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
389 pub struct WhereBoundPredicate {
391 /// Any generics from a `for` binding
392 pub bound_generic_params: Vec<GenericParam>,
393 /// The type being bounded
394 pub bounded_ty: P<Ty>,
395 /// Trait and lifetime bounds (`Clone+Send+'static`)
396 pub bounds: GenericBounds,
399 /// A lifetime predicate.
402 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
403 pub struct WhereRegionPredicate {
405 pub lifetime: Lifetime,
406 pub bounds: GenericBounds,
409 /// An equality predicate (unsupported).
412 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
413 pub struct WhereEqPredicate {
420 /// The set of MetaItems that define the compilation environment of the crate,
421 /// used to drive conditional compilation
422 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
424 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
427 pub attrs: Vec<Attribute>,
431 /// A spanned compile-time attribute list item.
432 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
434 /// Possible values inside of compile-time attribute lists.
436 /// E.g. the '..' in `#[name(..)]`.
437 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
438 pub enum NestedMetaItemKind {
439 /// A full MetaItem, for recursive meta items.
443 /// E.g. "foo", 64, true
447 /// A spanned compile-time attribute item.
449 /// E.g. `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`
450 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
451 pub struct MetaItem {
453 pub node: MetaItemKind,
457 /// A compile-time attribute item.
459 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
460 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
461 pub enum MetaItemKind {
464 /// E.g. `test` as in `#[test]`
468 /// E.g. `derive(..)` as in `#[derive(..)]`
469 List(Vec<NestedMetaItem>),
470 /// Name value meta item.
472 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
476 /// A Block (`{ .. }`).
478 /// E.g. `{ .. }` as in `fn foo() { .. }`
479 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
481 /// Statements in a block
482 pub stmts: Vec<Stmt>,
484 /// Distinguishes between `unsafe { ... }` and `{ ... }`
485 pub rules: BlockCheckMode,
490 #[derive(Clone, RustcEncodable, RustcDecodable)]
497 impl fmt::Debug for Pat {
498 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
499 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
504 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
505 let node = match &self.node {
506 PatKind::Wild => TyKind::Infer,
507 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
508 TyKind::Path(None, Path::from_ident(*ident))
510 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
511 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
512 PatKind::Ref(pat, mutbl) => pat
514 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
515 PatKind::Slice(pats, None, _) if pats.len() == 1 => {
516 pats[0].to_ty().map(TyKind::Slice)?
518 PatKind::Tuple(pats, None) => {
519 let mut tys = Vec::with_capacity(pats.len());
520 // FIXME(#48994) - could just be collected into an Option<Vec>
522 tys.push(pat.to_ty()?);
536 pub fn walk<F>(&self, it: &mut F) -> bool
538 F: FnMut(&Pat) -> bool,
545 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
546 PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
547 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
548 s.iter().all(|p| p.walk(it))
550 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
551 PatKind::Slice(ref before, ref slice, ref after) => {
552 before.iter().all(|p| p.walk(it))
553 && slice.iter().all(|p| p.walk(it))
554 && after.iter().all(|p| p.walk(it))
561 | PatKind::Mac(_) => true,
566 /// A single field in a struct pattern
568 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
569 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
570 /// except is_shorthand is true
571 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
572 pub struct FieldPat {
573 /// The identifier for the field
575 /// The pattern the field is destructured to
577 pub is_shorthand: bool,
578 pub attrs: ThinVec<Attribute>,
581 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
582 pub enum BindingMode {
587 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
589 Included(RangeSyntax),
593 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
594 pub enum RangeSyntax {
599 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
601 /// Represents a wildcard pattern (`_`)
604 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
605 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
606 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
607 /// during name resolution.
608 Ident(BindingMode, Ident, Option<P<Pat>>),
610 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
611 /// The `bool` is `true` in the presence of a `..`.
612 Struct(Path, Vec<Spanned<FieldPat>>, bool),
614 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
615 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
616 /// 0 <= position <= subpats.len()
617 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
619 /// A possibly qualified path pattern.
620 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
621 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
622 /// only legally refer to associated constants.
623 Path(Option<QSelf>, Path),
625 /// A tuple pattern `(a, b)`.
626 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
627 /// 0 <= position <= subpats.len()
628 Tuple(Vec<P<Pat>>, Option<usize>),
631 /// A reference pattern, e.g. `&mut (a, b)`
632 Ref(P<Pat>, Mutability),
635 /// A range pattern, e.g. `1...2`, `1..=2` or `1..2`
636 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
637 /// `[a, b, ..i, y, z]` is represented as:
638 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
639 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
640 /// Parentheses in patterns used for grouping, i.e. `(PAT)`.
642 /// A macro pattern; pre-expansion
647 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
649 pub enum Mutability {
654 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
656 /// The `+` operator (addition)
658 /// The `-` operator (subtraction)
660 /// The `*` operator (multiplication)
662 /// The `/` operator (division)
664 /// The `%` operator (modulus)
666 /// The `&&` operator (logical and)
668 /// The `||` operator (logical or)
670 /// The `^` operator (bitwise xor)
672 /// The `&` operator (bitwise and)
674 /// The `|` operator (bitwise or)
676 /// The `<<` operator (shift left)
678 /// The `>>` operator (shift right)
680 /// The `==` operator (equality)
682 /// The `<` operator (less than)
684 /// The `<=` operator (less than or equal to)
686 /// The `!=` operator (not equal to)
688 /// The `>=` operator (greater than or equal to)
690 /// The `>` operator (greater than)
695 pub fn to_string(&self) -> &'static str {
696 use self::BinOpKind::*;
718 pub fn lazy(&self) -> bool {
720 BinOpKind::And | BinOpKind::Or => true,
725 pub fn is_shift(&self) -> bool {
727 BinOpKind::Shl | BinOpKind::Shr => true,
732 pub fn is_comparison(&self) -> bool {
733 use self::BinOpKind::*;
735 Eq | Lt | Le | Ne | Gt | Ge => true,
736 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
740 /// Returns `true` if the binary operator takes its arguments by value
741 pub fn is_by_value(&self) -> bool {
742 !self.is_comparison()
746 pub type BinOp = Spanned<BinOpKind>;
748 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
750 /// The `*` operator for dereferencing
752 /// The `!` operator for logical inversion
754 /// The `-` operator for negation
759 /// Returns `true` if the unary operator takes its argument by value
760 pub fn is_by_value(u: UnOp) -> bool {
762 UnOp::Neg | UnOp::Not => true,
767 pub fn to_string(op: UnOp) -> &'static str {
777 #[derive(Clone, RustcEncodable, RustcDecodable)]
785 pub fn add_trailing_semicolon(mut self) -> Self {
786 self.node = match self.node {
787 StmtKind::Expr(expr) => StmtKind::Semi(expr),
788 StmtKind::Mac(mac) => {
789 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
796 pub fn is_item(&self) -> bool {
798 StmtKind::Item(_) => true,
803 pub fn is_expr(&self) -> bool {
805 StmtKind::Expr(_) => true,
811 impl fmt::Debug for Stmt {
812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
817 pprust::stmt_to_string(self)
822 #[derive(Clone, RustcEncodable, RustcDecodable)]
824 /// A local (let) binding.
827 /// An item definition.
830 /// Expr without trailing semi-colon.
832 /// Expr with a trailing semi-colon.
835 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
838 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
839 pub enum MacStmtStyle {
840 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
841 /// `foo!(...);`, `foo![...];`
843 /// The macro statement had braces; e.g. foo! { ... }
845 /// The macro statement had parentheses or brackets and no semicolon; e.g.
846 /// `foo!(...)`. All of these will end up being converted into macro
851 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
852 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
855 pub ty: Option<P<Ty>>,
856 /// Initializer expression to set the value, if any
857 pub init: Option<P<Expr>>,
860 pub attrs: ThinVec<Attribute>,
863 /// An arm of a 'match'.
865 /// E.g. `0..=10 => { println!("match!") }` as in
869 /// 0..=10 => { println!("match!") },
870 /// _ => { println!("no match!") },
873 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
875 pub attrs: Vec<Attribute>,
876 pub pats: Vec<P<Pat>>,
877 pub guard: Option<Guard>,
881 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
886 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
891 pub is_shorthand: bool,
892 pub attrs: ThinVec<Attribute>,
895 pub type SpannedIdent = Spanned<Ident>;
897 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
898 pub enum BlockCheckMode {
900 Unsafe(UnsafeSource),
903 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
904 pub enum UnsafeSource {
909 /// A constant (expression) that's not an item or associated item,
910 /// but needs its own `DefId` for type-checking, const-eval, etc.
911 /// These are usually found nested inside types (e.g. array lengths)
912 /// or expressions (e.g. repeat counts), and also used to define
913 /// explicit discriminant values for enum variants.
914 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
915 pub struct AnonConst {
921 #[derive(Clone, RustcEncodable, RustcDecodable)]
926 pub attrs: ThinVec<Attribute>,
929 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
930 #[cfg(target_arch = "x86_64")]
931 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 88);
934 /// Whether this expression would be valid somewhere that expects a value, for example, an `if`
936 pub fn returns(&self) -> bool {
937 if let ExprKind::Block(ref block, _) = self.node {
938 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
940 Some(&StmtKind::Expr(_)) => true,
941 Some(&StmtKind::Semi(ref expr)) => {
942 if let ExprKind::Ret(_) = expr.node {
943 // last statement is explicit return
949 // This is a block that doesn't end in either an implicit or explicit return
953 // This is not a block, it is a value
958 fn to_bound(&self) -> Option<GenericBound> {
960 ExprKind::Path(None, path) => Some(GenericBound::Trait(
961 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
962 TraitBoundModifier::None,
968 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
969 let node = match &self.node {
970 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
971 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
972 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
973 ExprKind::AddrOf(mutbl, expr) => expr
975 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
976 ExprKind::Repeat(expr, expr_len) => {
977 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
979 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
980 ExprKind::Tup(exprs) => {
983 .map(|expr| expr.to_ty())
984 .collect::<Option<Vec<_>>>()?;
987 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
988 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
989 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1004 pub fn precedence(&self) -> ExprPrecedence {
1006 ExprKind::Box(_) => ExprPrecedence::Box,
1007 ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
1008 ExprKind::Array(_) => ExprPrecedence::Array,
1009 ExprKind::Call(..) => ExprPrecedence::Call,
1010 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1011 ExprKind::Tup(_) => ExprPrecedence::Tup,
1012 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1013 ExprKind::Unary(..) => ExprPrecedence::Unary,
1014 ExprKind::Lit(_) => ExprPrecedence::Lit,
1015 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1016 ExprKind::If(..) => ExprPrecedence::If,
1017 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
1018 ExprKind::While(..) => ExprPrecedence::While,
1019 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
1020 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1021 ExprKind::Loop(..) => ExprPrecedence::Loop,
1022 ExprKind::Match(..) => ExprPrecedence::Match,
1023 ExprKind::Closure(..) => ExprPrecedence::Closure,
1024 ExprKind::Block(..) => ExprPrecedence::Block,
1025 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1026 ExprKind::Async(..) => ExprPrecedence::Async,
1027 ExprKind::Assign(..) => ExprPrecedence::Assign,
1028 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1029 ExprKind::Field(..) => ExprPrecedence::Field,
1030 ExprKind::Index(..) => ExprPrecedence::Index,
1031 ExprKind::Range(..) => ExprPrecedence::Range,
1032 ExprKind::Path(..) => ExprPrecedence::Path,
1033 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1034 ExprKind::Break(..) => ExprPrecedence::Break,
1035 ExprKind::Continue(..) => ExprPrecedence::Continue,
1036 ExprKind::Ret(..) => ExprPrecedence::Ret,
1037 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1038 ExprKind::Mac(..) => ExprPrecedence::Mac,
1039 ExprKind::Struct(..) => ExprPrecedence::Struct,
1040 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1041 ExprKind::Paren(..) => ExprPrecedence::Paren,
1042 ExprKind::Try(..) => ExprPrecedence::Try,
1043 ExprKind::Yield(..) => ExprPrecedence::Yield,
1048 impl fmt::Debug for Expr {
1049 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1050 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1054 /// Limit types of a range (inclusive or exclusive)
1055 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1056 pub enum RangeLimits {
1057 /// Inclusive at the beginning, exclusive at the end
1059 /// Inclusive at the beginning and end
1063 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1065 /// A `box x` expression.
1067 /// First expr is the place; second expr is the value.
1068 ObsoleteInPlace(P<Expr>, P<Expr>),
1069 /// An array (`[a, b, c, d]`)
1070 Array(Vec<P<Expr>>),
1073 /// The first field resolves to the function itself,
1074 /// and the second field is the list of arguments.
1075 /// This also represents calling the constructor of
1076 /// tuple-like ADTs such as tuple structs and enum variants.
1077 Call(P<Expr>, Vec<P<Expr>>),
1078 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1080 /// The `PathSegment` represents the method name and its generic arguments
1081 /// (within the angle brackets).
1082 /// The first element of the vector of `Expr`s is the expression that evaluates
1083 /// to the object on which the method is being called on (the receiver),
1084 /// and the remaining elements are the rest of the arguments.
1085 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1086 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1087 MethodCall(PathSegment, Vec<P<Expr>>),
1088 /// A tuple (`(a, b, c ,d)`)
1090 /// A binary operation (For example: `a + b`, `a * b`)
1091 Binary(BinOp, P<Expr>, P<Expr>),
1092 /// A unary operation (For example: `!x`, `*x`)
1093 Unary(UnOp, P<Expr>),
1094 /// A literal (For example: `1`, `"foo"`)
1096 /// A cast (`foo as f64`)
1097 Cast(P<Expr>, P<Ty>),
1098 Type(P<Expr>, P<Ty>),
1099 /// An `if` block, with an optional else block
1101 /// `if expr { block } else { expr }`
1102 If(P<Expr>, P<Block>, Option<P<Expr>>),
1103 /// An `if let` expression with an optional else block
1105 /// `if let pat = expr { block } else { expr }`
1107 /// This is desugared to a `match` expression.
1108 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1109 /// A while loop, with an optional label
1111 /// `'label: while expr { block }`
1112 While(P<Expr>, P<Block>, Option<Label>),
1113 /// A while-let loop, with an optional label
1115 /// `'label: while let pat = expr { block }`
1117 /// This is desugared to a combination of `loop` and `match` expressions.
1118 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1119 /// A for loop, with an optional label
1121 /// `'label: for pat in expr { block }`
1123 /// This is desugared to a combination of `loop` and `match` expressions.
1124 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1125 /// Conditionless loop (can be exited with break, continue, or return)
1127 /// `'label: loop { block }`
1128 Loop(P<Block>, Option<Label>),
1129 /// A `match` block.
1130 Match(P<Expr>, Vec<Arm>),
1131 /// A closure (for example, `move |a, b, c| a + b + c`)
1133 /// The final span is the span of the argument block `|...|`
1134 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1135 /// A block (`'label: { ... }`)
1136 Block(P<Block>, Option<Label>),
1137 /// An async block (`async move { ... }`)
1139 /// The `NodeId` is the `NodeId` for the closure that results from
1140 /// desugaring an async block, just like the NodeId field in the
1141 /// `IsAsync` enum. This is necessary in order to create a def for the
1142 /// closure which can be used as a parent of any child defs. Defs
1143 /// created during lowering cannot be made the parent of any other
1144 /// preexisting defs.
1145 Async(CaptureBy, NodeId, P<Block>),
1146 /// A try block (`try { ... }`)
1149 /// An assignment (`a = foo()`)
1150 Assign(P<Expr>, P<Expr>),
1151 /// An assignment with an operator
1153 /// For example, `a += 1`.
1154 AssignOp(BinOp, P<Expr>, P<Expr>),
1155 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct field
1156 Field(P<Expr>, Ident),
1157 /// An indexing operation (`foo[2]`)
1158 Index(P<Expr>, P<Expr>),
1159 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
1160 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1162 /// Variable reference, possibly containing `::` and/or type
1163 /// parameters, e.g. foo::bar::<baz>.
1165 /// Optionally "qualified",
1166 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
1167 Path(Option<QSelf>, Path),
1169 /// A referencing operation (`&a` or `&mut a`)
1170 AddrOf(Mutability, P<Expr>),
1171 /// A `break`, with an optional label to break, and an optional expression
1172 Break(Option<Label>, Option<P<Expr>>),
1173 /// A `continue`, with an optional label
1174 Continue(Option<Label>),
1175 /// A `return`, with an optional value to be returned
1176 Ret(Option<P<Expr>>),
1178 /// Output of the `asm!()` macro
1179 InlineAsm(P<InlineAsm>),
1181 /// A macro invocation; pre-expansion
1184 /// A struct literal expression.
1186 /// For example, `Foo {x: 1, y: 2}`, or
1187 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1188 Struct(Path, Vec<Field>, Option<P<Expr>>),
1190 /// An array literal constructed from one repeated element.
1192 /// For example, `[1; 5]`. The expression is the element to be
1193 /// repeated; the constant is the number of times to repeat it.
1194 Repeat(P<Expr>, AnonConst),
1196 /// No-op: used solely so we can pretty-print faithfully
1202 /// A `yield`, with an optional value to be yielded
1203 Yield(Option<P<Expr>>),
1206 /// The explicit Self type in a "qualified path". The actual
1207 /// path, including the trait and the associated item, is stored
1208 /// separately. `position` represents the index of the associated
1209 /// item qualified with this Self type.
1211 /// ```ignore (only-for-syntax-highlight)
1212 /// <Vec<T> as a::b::Trait>::AssociatedItem
1213 /// ^~~~~ ~~~~~~~~~~~~~~^
1216 /// <Vec<T>>::AssociatedItem
1220 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1224 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1225 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1226 /// 0`, this is an empty span.
1227 pub path_span: Span,
1228 pub position: usize,
1231 /// A capture clause
1232 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1233 pub enum CaptureBy {
1238 /// The movability of a generator / closure literal
1239 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1240 pub enum Movability {
1245 pub type Mac = Spanned<Mac_>;
1247 /// Represents a macro invocation. The Path indicates which macro
1248 /// is being invoked, and the vector of token-trees contains the source
1249 /// of the macro invocation.
1251 /// NB: the additional ident for a macro_rules-style macro is actually
1252 /// stored in the enclosing item. Oog.
1253 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1256 pub delim: MacDelimiter,
1257 pub tts: ThinTokenStream,
1260 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1261 pub enum MacDelimiter {
1268 pub fn stream(&self) -> TokenStream {
1269 self.tts.clone().into()
1273 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1274 pub struct MacroDef {
1275 pub tokens: ThinTokenStream,
1280 pub fn stream(&self) -> TokenStream {
1281 self.tokens.clone().into()
1285 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1287 /// A regular string, like `"foo"`
1289 /// A raw string, like `r##"foo"##`
1291 /// The value is the number of `#` symbols used.
1296 pub type Lit = Spanned<LitKind>;
1298 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1299 pub enum LitIntType {
1307 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1308 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1310 /// A string literal (`"foo"`)
1311 Str(Symbol, StrStyle),
1312 /// A byte string (`b"foo"`)
1313 ByteStr(Lrc<Vec<u8>>),
1314 /// A byte char (`b'f'`)
1316 /// A character literal (`'a'`)
1318 /// An integer literal (`1`)
1319 Int(u128, LitIntType),
1320 /// A float literal (`1f64` or `1E10f64`)
1321 Float(Symbol, FloatTy),
1322 /// A float literal without a suffix (`1.0 or 1.0E10`)
1323 FloatUnsuffixed(Symbol),
1324 /// A boolean literal
1329 /// Returns true if this literal is a string and false otherwise.
1330 pub fn is_str(&self) -> bool {
1332 LitKind::Str(..) => true,
1337 /// Returns true if this literal is byte literal string false otherwise.
1338 pub fn is_bytestr(&self) -> bool {
1340 LitKind::ByteStr(_) => true,
1345 /// Returns true if this is a numeric literal.
1346 pub fn is_numeric(&self) -> bool {
1348 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1353 /// Returns true if this literal has no suffix. Note: this will return true
1354 /// for literals with prefixes such as raw strings and byte strings.
1355 pub fn is_unsuffixed(&self) -> bool {
1357 // unsuffixed variants
1359 | LitKind::ByteStr(..)
1362 | LitKind::Int(_, LitIntType::Unsuffixed)
1363 | LitKind::FloatUnsuffixed(..)
1364 | LitKind::Bool(..) => true,
1365 // suffixed variants
1366 LitKind::Int(_, LitIntType::Signed(..))
1367 | LitKind::Int(_, LitIntType::Unsigned(..))
1368 | LitKind::Float(..) => false,
1372 /// Returns true if this literal has a suffix.
1373 pub fn is_suffixed(&self) -> bool {
1374 !self.is_unsuffixed()
1378 // NB: If you change this, you'll probably want to change the corresponding
1379 // type structure in middle/ty.rs as well.
1380 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1383 pub mutbl: Mutability,
1386 /// Represents a method's signature in a trait declaration,
1387 /// or in an implementation.
1388 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1389 pub struct MethodSig {
1390 pub header: FnHeader,
1391 pub decl: P<FnDecl>,
1394 /// Represents an item declaration within a trait declaration,
1395 /// possibly including a default implementation. A trait item is
1396 /// either required (meaning it doesn't have an implementation, just a
1397 /// signature) or provided (meaning it has a default implementation).
1398 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1399 pub struct TraitItem {
1402 pub attrs: Vec<Attribute>,
1403 pub generics: Generics,
1404 pub node: TraitItemKind,
1406 /// See `Item::tokens` for what this is
1407 pub tokens: Option<TokenStream>,
1410 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1411 pub enum TraitItemKind {
1412 Const(P<Ty>, Option<P<Expr>>),
1413 Method(MethodSig, Option<P<Block>>),
1414 Type(GenericBounds, Option<P<Ty>>),
1418 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1419 pub struct ImplItem {
1422 pub vis: Visibility,
1423 pub defaultness: Defaultness,
1424 pub attrs: Vec<Attribute>,
1425 pub generics: Generics,
1426 pub node: ImplItemKind,
1428 /// See `Item::tokens` for what this is
1429 pub tokens: Option<TokenStream>,
1432 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1433 pub enum ImplItemKind {
1434 Const(P<Ty>, P<Expr>),
1435 Method(MethodSig, P<Block>),
1437 Existential(GenericBounds),
1441 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1451 impl fmt::Debug for IntTy {
1452 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1453 fmt::Display::fmt(self, f)
1457 impl fmt::Display for IntTy {
1458 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1459 write!(f, "{}", self.ty_to_string())
1464 pub fn ty_to_string(&self) -> &'static str {
1466 IntTy::Isize => "isize",
1468 IntTy::I16 => "i16",
1469 IntTy::I32 => "i32",
1470 IntTy::I64 => "i64",
1471 IntTy::I128 => "i128",
1475 pub fn val_to_string(&self, val: i128) -> String {
1476 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1477 // are parsed as u128, so we wouldn't want to print an extra negative
1479 format!("{}{}", val as u128, self.ty_to_string())
1482 pub fn bit_width(&self) -> Option<usize> {
1484 IntTy::Isize => return None,
1494 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1505 pub fn ty_to_string(&self) -> &'static str {
1507 UintTy::Usize => "usize",
1509 UintTy::U16 => "u16",
1510 UintTy::U32 => "u32",
1511 UintTy::U64 => "u64",
1512 UintTy::U128 => "u128",
1516 pub fn val_to_string(&self, val: u128) -> String {
1517 format!("{}{}", val, self.ty_to_string())
1520 pub fn bit_width(&self) -> Option<usize> {
1522 UintTy::Usize => return None,
1527 UintTy::U128 => 128,
1532 impl fmt::Debug for UintTy {
1533 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1534 fmt::Display::fmt(self, f)
1538 impl fmt::Display for UintTy {
1539 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1540 write!(f, "{}", self.ty_to_string())
1544 // Bind a type to an associated type: `A=Foo`.
1545 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1546 pub struct TypeBinding {
1553 #[derive(Clone, RustcEncodable, RustcDecodable)]
1560 impl fmt::Debug for Ty {
1561 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1562 write!(f, "type({})", pprust::ty_to_string(self))
1566 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1567 pub struct BareFnTy {
1568 pub unsafety: Unsafety,
1570 pub generic_params: Vec<GenericParam>,
1571 pub decl: P<FnDecl>,
1574 /// The different kinds of types recognized by the compiler
1575 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1577 /// A variable-length slice (`[T]`)
1579 /// A fixed length array (`[T; n]`)
1580 Array(P<Ty>, AnonConst),
1581 /// A raw pointer (`*const T` or `*mut T`)
1583 /// A reference (`&'a T` or `&'a mut T`)
1584 Rptr(Option<Lifetime>, MutTy),
1585 /// A bare function (e.g. `fn(usize) -> bool`)
1586 BareFn(P<BareFnTy>),
1587 /// The never type (`!`)
1589 /// A tuple (`(A, B, C, D,...)`)
1591 /// A path (`module::module::...::Type`), optionally
1592 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1594 /// Type parameters are stored in the Path itself
1595 Path(Option<QSelf>, Path),
1596 /// A trait object type `Bound1 + Bound2 + Bound3`
1597 /// where `Bound` is a trait or a lifetime.
1598 TraitObject(GenericBounds, TraitObjectSyntax),
1599 /// An `impl Bound1 + Bound2 + Bound3` type
1600 /// where `Bound` is a trait or a lifetime.
1602 /// The `NodeId` exists to prevent lowering from having to
1603 /// generate `NodeId`s on the fly, which would complicate
1604 /// the generation of `existential type` items significantly
1605 ImplTrait(NodeId, GenericBounds),
1606 /// No-op; kept solely so that we can pretty-print faithfully
1610 /// TyKind::Infer means the type should be inferred instead of it having been
1611 /// specified. This can appear anywhere in a type.
1613 /// Inferred type of a `self` or `&self` argument in a method.
1615 // A macro in the type position.
1617 /// Placeholder for a kind that has failed to be defined.
1622 pub fn is_implicit_self(&self) -> bool {
1623 if let TyKind::ImplicitSelf = *self {
1630 pub fn is_unit(&self) -> bool {
1631 if let TyKind::Tup(ref tys) = *self {
1639 /// Syntax used to declare a trait object.
1640 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1641 pub enum TraitObjectSyntax {
1646 /// Inline assembly dialect.
1648 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1649 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1650 pub enum AsmDialect {
1655 /// Inline assembly.
1657 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1658 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1659 pub struct InlineAsmOutput {
1660 pub constraint: Symbol,
1663 pub is_indirect: bool,
1666 /// Inline assembly.
1668 /// E.g. `asm!("NOP");`
1669 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1670 pub struct InlineAsm {
1672 pub asm_str_style: StrStyle,
1673 pub outputs: Vec<InlineAsmOutput>,
1674 pub inputs: Vec<(Symbol, P<Expr>)>,
1675 pub clobbers: Vec<Symbol>,
1677 pub alignstack: bool,
1678 pub dialect: AsmDialect,
1679 pub ctxt: SyntaxContext,
1682 /// An argument in a function header.
1684 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1685 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1692 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1694 /// E.g. `&mut self` as in `fn foo(&mut self)`
1695 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1697 /// `self`, `mut self`
1699 /// `&'lt self`, `&'lt mut self`
1700 Region(Option<Lifetime>, Mutability),
1701 /// `self: TYPE`, `mut self: TYPE`
1702 Explicit(P<Ty>, Mutability),
1705 pub type ExplicitSelf = Spanned<SelfKind>;
1708 pub fn to_self(&self) -> Option<ExplicitSelf> {
1709 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1710 if ident.name == keywords::SelfValue.name() {
1711 return match self.ty.node {
1712 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1713 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1714 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1717 self.pat.span.to(self.ty.span),
1718 SelfKind::Explicit(self.ty.clone(), mutbl),
1726 pub fn is_self(&self) -> bool {
1727 if let PatKind::Ident(_, ident, _) = self.pat.node {
1728 ident.name == keywords::SelfValue.name()
1734 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1735 let span = eself.span.to(eself_ident.span);
1736 let infer_ty = P(Ty {
1738 node: TyKind::ImplicitSelf,
1741 let arg = |mutbl, ty| Arg {
1744 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1751 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1752 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1753 SelfKind::Region(lt, mutbl) => arg(
1754 Mutability::Immutable,
1771 /// Header (not the body) of a function declaration.
1773 /// E.g. `fn foo(bar: baz)`
1774 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1776 pub inputs: Vec<Arg>,
1777 pub output: FunctionRetTy,
1782 pub fn get_self(&self) -> Option<ExplicitSelf> {
1783 self.inputs.get(0).and_then(Arg::to_self)
1785 pub fn has_self(&self) -> bool {
1786 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1790 /// Is the trait definition an auto trait?
1791 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1797 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1803 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1807 return_impl_trait_id: NodeId,
1813 pub fn is_async(self) -> bool {
1814 if let IsAsync::Async { .. } = self {
1820 /// In case this is an `Async` return the `NodeId` for the generated impl Trait item
1821 pub fn opt_return_id(self) -> Option<NodeId> {
1824 return_impl_trait_id,
1826 } => Some(return_impl_trait_id),
1827 IsAsync::NotAsync => None,
1832 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1833 pub enum Constness {
1838 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1839 pub enum Defaultness {
1844 impl fmt::Display for Unsafety {
1845 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1848 Unsafety::Normal => "normal",
1849 Unsafety::Unsafe => "unsafe",
1856 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1857 pub enum ImplPolarity {
1858 /// `impl Trait for Type`
1860 /// `impl !Trait for Type`
1864 impl fmt::Debug for ImplPolarity {
1865 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1867 ImplPolarity::Positive => "positive".fmt(f),
1868 ImplPolarity::Negative => "negative".fmt(f),
1873 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1874 pub enum FunctionRetTy {
1875 /// Return type is not specified.
1877 /// Functions default to `()` and
1878 /// closures default to inference. Span points to where return
1879 /// type would be inserted.
1885 impl FunctionRetTy {
1886 pub fn span(&self) -> Span {
1888 FunctionRetTy::Default(span) => span,
1889 FunctionRetTy::Ty(ref ty) => ty.span,
1894 /// Module declaration.
1896 /// E.g. `mod foo;` or `mod foo { .. }`
1897 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1899 /// A span from the first token past `{` to the last token until `}`.
1900 /// For `mod foo;`, the inner span ranges from the first token
1901 /// to the last token in the external file.
1903 pub items: Vec<P<Item>>,
1904 /// For `mod foo;` inline is false, for `mod foo { .. }` it is true.
1908 /// Foreign module declaration.
1910 /// E.g. `extern { .. }` or `extern C { .. }`
1911 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1912 pub struct ForeignMod {
1914 pub items: Vec<ForeignItem>,
1917 /// Global inline assembly
1919 /// aka module-level assembly or file-scoped assembly
1920 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1921 pub struct GlobalAsm {
1923 pub ctxt: SyntaxContext,
1926 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1927 pub struct EnumDef {
1928 pub variants: Vec<Variant>,
1931 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1932 pub struct Variant_ {
1934 pub attrs: Vec<Attribute>,
1935 pub data: VariantData,
1936 /// Explicit discriminant, e.g. `Foo = 1`
1937 pub disr_expr: Option<AnonConst>,
1940 pub type Variant = Spanned<Variant_>;
1942 /// Part of `use` item to the right of its prefix.
1943 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1944 pub enum UseTreeKind {
1945 /// `use prefix` or `use prefix as rename`
1947 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1949 Simple(Option<Ident>, NodeId, NodeId),
1950 /// `use prefix::{...}`
1951 Nested(Vec<(UseTree, NodeId)>),
1956 /// A tree of paths sharing common prefixes.
1957 /// Used in `use` items both at top-level and inside of braces in import groups.
1958 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1959 pub struct UseTree {
1961 pub kind: UseTreeKind,
1966 pub fn ident(&self) -> Ident {
1968 UseTreeKind::Simple(Some(rename), ..) => rename,
1969 UseTreeKind::Simple(None, ..) => {
1973 .expect("empty prefix in a simple import")
1976 _ => panic!("`UseTree::ident` can only be used on a simple import"),
1981 /// Distinguishes between Attributes that decorate items and Attributes that
1982 /// are contained as statements within items. These two cases need to be
1983 /// distinguished for pretty-printing.
1984 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1985 pub enum AttrStyle {
1991 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
1993 pub struct AttrId(pub usize);
1995 impl Idx for AttrId {
1996 fn new(idx: usize) -> Self {
1999 fn index(self) -> usize {
2004 /// Meta-data associated with an item
2005 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
2006 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2007 pub struct Attribute {
2009 pub style: AttrStyle,
2011 pub tokens: TokenStream,
2012 pub is_sugared_doc: bool,
2016 /// TraitRef's appear in impls.
2018 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
2019 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
2020 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
2021 /// same as the impl's node id).
2022 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2023 pub struct TraitRef {
2028 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2029 pub struct PolyTraitRef {
2030 /// The `'a` in `<'a> Foo<&'a T>`
2031 pub bound_generic_params: Vec<GenericParam>,
2033 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2034 pub trait_ref: TraitRef,
2040 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2042 bound_generic_params: generic_params,
2043 trait_ref: TraitRef {
2045 ref_id: DUMMY_NODE_ID,
2052 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2053 pub enum CrateSugar {
2054 /// Source is `pub(crate)`
2057 /// Source is (just) `crate`
2061 pub type Visibility = Spanned<VisibilityKind>;
2063 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2064 pub enum VisibilityKind {
2067 Restricted { path: P<Path>, id: NodeId },
2071 impl VisibilityKind {
2072 pub fn is_pub(&self) -> bool {
2073 if let VisibilityKind::Public = *self {
2081 /// Field of a struct.
2083 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
2084 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2085 pub struct StructField {
2087 pub ident: Option<Ident>,
2088 pub vis: Visibility,
2091 pub attrs: Vec<Attribute>,
2094 /// Fields and Ids of enum variants and structs
2096 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2097 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2098 /// One shared Id can be successfully used for these two purposes.
2099 /// Id of the whole enum lives in `Item`.
2101 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2102 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2103 /// the variant itself" from enum variants.
2104 /// Id of the whole struct lives in `Item`.
2105 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2106 pub enum VariantData {
2109 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
2110 Struct(Vec<StructField>, NodeId),
2113 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
2114 Tuple(Vec<StructField>, NodeId),
2117 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
2122 pub fn fields(&self) -> &[StructField] {
2124 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2128 pub fn id(&self) -> NodeId {
2130 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2133 pub fn is_struct(&self) -> bool {
2134 if let VariantData::Struct(..) = *self {
2140 pub fn is_tuple(&self) -> bool {
2141 if let VariantData::Tuple(..) = *self {
2147 pub fn is_unit(&self) -> bool {
2148 if let VariantData::Unit(..) = *self {
2158 /// The name might be a dummy name in case of anonymous items
2159 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2162 pub attrs: Vec<Attribute>,
2165 pub vis: Visibility,
2168 /// Original tokens this item was parsed from. This isn't necessarily
2169 /// available for all items, although over time more and more items should
2170 /// have this be `Some`. Right now this is primarily used for procedural
2171 /// macros, notably custom attributes.
2173 /// Note that the tokens here do not include the outer attributes, but will
2174 /// include inner attributes.
2175 pub tokens: Option<TokenStream>,
2178 /// A function header
2180 /// All the information between the visibility & the name of the function is
2181 /// included in this struct (e.g. `async unsafe fn` or `const extern "C" fn`)
2182 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2183 pub struct FnHeader {
2184 pub unsafety: Unsafety,
2185 pub asyncness: IsAsync,
2186 pub constness: Spanned<Constness>,
2190 impl Default for FnHeader {
2191 fn default() -> FnHeader {
2193 unsafety: Unsafety::Normal,
2194 asyncness: IsAsync::NotAsync,
2195 constness: dummy_spanned(Constness::NotConst),
2201 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2203 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2205 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2206 ExternCrate(Option<Name>),
2207 /// A use declaration (`use` or `pub use`) item.
2209 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
2211 /// A static item (`static` or `pub static`).
2213 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
2214 Static(P<Ty>, Mutability, P<Expr>),
2215 /// A constant item (`const` or `pub const`).
2217 /// E.g. `const FOO: i32 = 42;`
2218 Const(P<Ty>, P<Expr>),
2219 /// A function declaration (`fn` or `pub fn`).
2221 /// E.g. `fn foo(bar: usize) -> usize { .. }`
2222 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2223 /// A module declaration (`mod` or `pub mod`).
2225 /// E.g. `mod foo;` or `mod foo { .. }`
2227 /// An external module (`extern` or `pub extern`).
2229 /// E.g. `extern {}` or `extern "C" {}`
2230 ForeignMod(ForeignMod),
2231 /// Module-level inline assembly (from `global_asm!()`)
2232 GlobalAsm(P<GlobalAsm>),
2233 /// A type alias (`type` or `pub type`).
2235 /// E.g. `type Foo = Bar<u8>;`
2236 Ty(P<Ty>, Generics),
2237 /// An existential type declaration (`existential type`).
2239 /// E.g. `existential type Foo: Bar + Boo;`
2240 Existential(GenericBounds, Generics),
2241 /// An enum definition (`enum` or `pub enum`).
2243 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
2244 Enum(EnumDef, Generics),
2245 /// A struct definition (`struct` or `pub struct`).
2247 /// E.g. `struct Foo<A> { x: A }`
2248 Struct(VariantData, Generics),
2249 /// A union definition (`union` or `pub union`).
2251 /// E.g. `union Foo<A, B> { x: A, y: B }`
2252 Union(VariantData, Generics),
2253 /// A Trait declaration (`trait` or `pub trait`).
2255 /// E.g. `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`
2256 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2259 /// E.g. `trait Foo = Bar + Quux;`
2260 TraitAlias(Generics, GenericBounds),
2261 /// An implementation.
2263 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
2269 Option<TraitRef>, // (optional) trait this impl implements
2273 /// A macro invocation.
2275 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
2278 /// A macro definition.
2283 pub fn descriptive_variant(&self) -> &str {
2285 ItemKind::ExternCrate(..) => "extern crate",
2286 ItemKind::Use(..) => "use",
2287 ItemKind::Static(..) => "static item",
2288 ItemKind::Const(..) => "constant item",
2289 ItemKind::Fn(..) => "function",
2290 ItemKind::Mod(..) => "module",
2291 ItemKind::ForeignMod(..) => "foreign module",
2292 ItemKind::GlobalAsm(..) => "global asm",
2293 ItemKind::Ty(..) => "type alias",
2294 ItemKind::Existential(..) => "existential type",
2295 ItemKind::Enum(..) => "enum",
2296 ItemKind::Struct(..) => "struct",
2297 ItemKind::Union(..) => "union",
2298 ItemKind::Trait(..) => "trait",
2299 ItemKind::TraitAlias(..) => "trait alias",
2300 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2305 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2306 pub struct ForeignItem {
2308 pub attrs: Vec<Attribute>,
2309 pub node: ForeignItemKind,
2312 pub vis: Visibility,
2315 /// An item within an `extern` block
2316 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2317 pub enum ForeignItemKind {
2318 /// A foreign function
2319 Fn(P<FnDecl>, Generics),
2320 /// A foreign static item (`static ext: u8`), with optional mutability
2321 /// (the boolean is true when mutable)
2322 Static(P<Ty>, bool),
2325 /// A macro invocation
2329 impl ForeignItemKind {
2330 pub fn descriptive_variant(&self) -> &str {
2332 ForeignItemKind::Fn(..) => "foreign function",
2333 ForeignItemKind::Static(..) => "foreign static item",
2334 ForeignItemKind::Ty => "foreign type",
2335 ForeignItemKind::Macro(..) => "macro in foreign module",
2345 // are ASTs encodable?
2347 fn check_asts_encodable() {
2348 fn assert_encodable<T: serialize::Encodable>() {}
2349 assert_encodable::<Crate>();