1 // The Rust abstract syntax tree.
3 pub use self::GenericArgs::*;
4 pub use self::UnsafeSource::*;
5 pub use symbol::{Ident, Symbol as Name};
6 pub use util::parser::ExprPrecedence;
8 use ext::hygiene::{Mark, SyntaxContext};
11 use rustc_data_structures::indexed_vec::Idx;
12 #[cfg(target_arch = "x86_64")]
13 use rustc_data_structures::static_assert;
14 use rustc_target::spec::abi::Abi;
15 use source_map::{dummy_spanned, respan, Spanned};
16 use symbol::{keywords, Symbol};
17 use syntax_pos::{Span, DUMMY_SP};
18 use tokenstream::{ThinTokenStream, TokenStream};
21 use rustc_data_structures::fx::FxHashSet;
22 use rustc_data_structures::sync::Lrc;
23 use serialize::{self, Decoder, Encoder};
26 pub use rustc_target::abi::FloatTy;
28 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
33 impl fmt::Debug for Label {
34 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
35 write!(f, "label({:?})", self.ident)
39 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
45 impl fmt::Debug for Lifetime {
46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51 pprust::lifetime_to_string(self)
56 /// A "Path" is essentially Rust's notion of a name.
58 /// It's represented as a sequence of identifiers,
59 /// along with a bunch of supporting information.
61 /// E.g., `std::cmp::PartialEq`.
62 #[derive(Clone, RustcEncodable, RustcDecodable)]
65 /// The segments in the path: the things separated by `::`.
66 /// Global paths begin with `keywords::PathRoot`.
67 pub segments: Vec<PathSegment>,
70 impl<'a> PartialEq<&'a str> for Path {
71 fn eq(&self, string: &&'a str) -> bool {
72 self.segments.len() == 1 && self.segments[0].ident.name == *string
76 impl fmt::Debug for Path {
77 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78 write!(f, "path({})", pprust::path_to_string(self))
82 impl fmt::Display for Path {
83 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84 write!(f, "{}", pprust::path_to_string(self))
89 // Convert a span and an identifier to the corresponding
91 pub fn from_ident(ident: Ident) -> Path {
93 segments: vec![PathSegment::from_ident(ident)],
98 pub fn is_global(&self) -> bool {
99 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
103 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
105 /// E.g., `std`, `String` or `Box<T>`.
106 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
107 pub struct PathSegment {
108 /// The identifier portion of this path segment.
113 /// Type/lifetime parameters attached to this path. They come in
114 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
115 /// `None` means that no parameter list is supplied (`Path`),
116 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
117 /// but it can be empty (`Path<>`).
118 /// `P` is used as a size optimization for the common case with no parameters.
119 pub args: Option<P<GenericArgs>>,
123 pub fn from_ident(ident: Ident) -> Self {
124 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
126 pub fn path_root(span: Span) -> Self {
127 PathSegment::from_ident(Ident::new(keywords::PathRoot.name(), span))
131 /// Arguments of a path segment.
133 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
134 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
135 pub enum GenericArgs {
136 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
137 AngleBracketed(AngleBracketedArgs),
138 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
139 Parenthesized(ParenthesisedArgs),
143 pub fn span(&self) -> Span {
145 AngleBracketed(ref data) => data.span,
146 Parenthesized(ref data) => data.span,
151 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
152 pub enum GenericArg {
157 /// A path like `Foo<'a, T>`
158 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
159 pub struct AngleBracketedArgs {
162 /// The arguments for this path segment.
163 pub args: Vec<GenericArg>,
164 /// Bindings (equality constraints) on associated types, if present.
166 /// E.g., `Foo<A=Bar>`.
167 pub bindings: Vec<TypeBinding>,
170 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
171 fn into(self) -> Option<P<GenericArgs>> {
172 Some(P(GenericArgs::AngleBracketed(self)))
176 impl Into<Option<P<GenericArgs>>> for ParenthesisedArgs {
177 fn into(self) -> Option<P<GenericArgs>> {
178 Some(P(GenericArgs::Parenthesized(self)))
182 /// A path like `Foo(A,B) -> C`
183 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
184 pub struct ParenthesisedArgs {
189 pub inputs: Vec<P<Ty>>,
192 pub output: Option<P<Ty>>,
195 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
197 use rustc_data_structures::indexed_vec::Idx;
201 DEBUG_FORMAT = "NodeId({})"
206 pub use self::node_id_inner::NodeId;
209 pub fn placeholder_from_mark(mark: Mark) -> Self {
210 NodeId::from_u32(mark.as_u32())
213 pub fn placeholder_to_mark(self) -> Mark {
214 Mark::from_u32(self.as_u32())
218 impl fmt::Display for NodeId {
219 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
220 fmt::Display::fmt(&self.as_u32(), f)
224 impl serialize::UseSpecializedEncodable for NodeId {
225 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
226 s.emit_u32(self.as_u32())
230 impl serialize::UseSpecializedDecodable for NodeId {
231 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
232 d.read_u32().map(NodeId::from_u32)
236 /// Node id used to represent the root of the crate.
237 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
239 /// When parsing and doing expansions, we initially give all AST nodes this AST
240 /// node value. Then later, in the renumber pass, we renumber them to have
241 /// small, positive ids.
242 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
244 /// A modifier on a bound, currently this is only used for `?Sized`, where the
245 /// modifier is `Maybe`. Negative bounds should also be handled here.
246 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
247 pub enum TraitBoundModifier {
252 /// The AST represents all type param bounds as types.
253 /// `typeck::collect::compute_bounds` matches these against
254 /// the "special" built-in traits (see `middle::lang_items`) and
255 /// detects `Copy`, `Send` and `Sync`.
256 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
257 pub enum GenericBound {
258 Trait(PolyTraitRef, TraitBoundModifier),
263 pub fn span(&self) -> Span {
265 &GenericBound::Trait(ref t, ..) => t.span,
266 &GenericBound::Outlives(ref l) => l.ident.span,
271 pub type GenericBounds = Vec<GenericBound>;
273 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
274 pub enum GenericParamKind {
275 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
278 default: Option<P<Ty>>,
282 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
283 pub struct GenericParam {
286 pub attrs: ThinVec<Attribute>,
287 pub bounds: GenericBounds,
289 pub kind: GenericParamKind,
292 /// Represents lifetime, type and const parameters attached to a declaration of
293 /// a function, enum, trait, etc.
294 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
295 pub struct Generics {
296 pub params: Vec<GenericParam>,
297 pub where_clause: WhereClause,
301 impl Default for Generics {
302 /// Creates an instance of `Generics`.
303 fn default() -> Generics {
306 where_clause: WhereClause {
308 predicates: Vec::new(),
316 /// A `where` clause in a definition
317 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
318 pub struct WhereClause {
320 pub predicates: Vec<WherePredicate>,
324 /// A single predicate in a `where` clause
325 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
326 pub enum WherePredicate {
327 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
328 BoundPredicate(WhereBoundPredicate),
329 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
330 RegionPredicate(WhereRegionPredicate),
331 /// An equality predicate (unsupported).
332 EqPredicate(WhereEqPredicate),
335 impl WherePredicate {
336 pub fn span(&self) -> Span {
338 &WherePredicate::BoundPredicate(ref p) => p.span,
339 &WherePredicate::RegionPredicate(ref p) => p.span,
340 &WherePredicate::EqPredicate(ref p) => p.span,
347 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
348 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
349 pub struct WhereBoundPredicate {
351 /// Any generics from a `for` binding
352 pub bound_generic_params: Vec<GenericParam>,
353 /// The type being bounded
354 pub bounded_ty: P<Ty>,
355 /// Trait and lifetime bounds (`Clone+Send+'static`)
356 pub bounds: GenericBounds,
359 /// A lifetime predicate.
361 /// E.g., `'a: 'b + 'c`.
362 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
363 pub struct WhereRegionPredicate {
365 pub lifetime: Lifetime,
366 pub bounds: GenericBounds,
369 /// An equality predicate (unsupported).
372 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
373 pub struct WhereEqPredicate {
380 /// The set of `MetaItem`s that define the compilation environment of the crate,
381 /// used to drive conditional compilation.
382 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
384 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
387 pub attrs: Vec<Attribute>,
391 /// A spanned compile-time attribute list item.
392 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
394 /// Possible values inside of compile-time attribute lists.
396 /// E.g., the '..' in `#[name(..)]`.
397 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
398 pub enum NestedMetaItemKind {
399 /// A full MetaItem, for recursive meta items.
403 /// E.g., `"foo"`, `64`, `true`.
407 /// A spanned compile-time attribute item.
409 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
410 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
411 pub struct MetaItem {
413 pub node: MetaItemKind,
417 /// A compile-time attribute item.
419 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
420 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
421 pub enum MetaItemKind {
424 /// E.g., `test` as in `#[test]`.
428 /// E.g., `derive(..)` as in `#[derive(..)]`.
429 List(Vec<NestedMetaItem>),
430 /// Name value meta item.
432 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
436 /// A Block (`{ .. }`).
438 /// E.g., `{ .. }` as in `fn foo() { .. }`.
439 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
441 /// Statements in a block
442 pub stmts: Vec<Stmt>,
444 /// Distinguishes between `unsafe { ... }` and `{ ... }`
445 pub rules: BlockCheckMode,
449 #[derive(Clone, RustcEncodable, RustcDecodable)]
456 impl fmt::Debug for Pat {
457 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
458 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
463 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
464 let node = match &self.node {
465 PatKind::Wild => TyKind::Infer,
466 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
467 TyKind::Path(None, Path::from_ident(*ident))
469 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
470 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
471 PatKind::Ref(pat, mutbl) => pat
473 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
474 PatKind::Slice(pats, None, _) if pats.len() == 1 => {
475 pats[0].to_ty().map(TyKind::Slice)?
477 PatKind::Tuple(pats, None) => {
478 let mut tys = Vec::with_capacity(pats.len());
479 // FIXME(#48994) - could just be collected into an Option<Vec>
481 tys.push(pat.to_ty()?);
495 pub fn walk<F>(&self, it: &mut F) -> bool
497 F: FnMut(&Pat) -> bool,
504 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
505 PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
506 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
507 s.iter().all(|p| p.walk(it))
509 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
510 PatKind::Slice(ref before, ref slice, ref after) => {
511 before.iter().all(|p| p.walk(it))
512 && slice.iter().all(|p| p.walk(it))
513 && after.iter().all(|p| p.walk(it))
520 | PatKind::Mac(_) => true,
525 /// A single field in a struct pattern
527 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
528 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
529 /// except is_shorthand is true
530 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
531 pub struct FieldPat {
532 /// The identifier for the field
534 /// The pattern the field is destructured to
536 pub is_shorthand: bool,
537 pub attrs: ThinVec<Attribute>,
540 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
541 pub enum BindingMode {
546 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
548 Included(RangeSyntax),
552 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
553 pub enum RangeSyntax {
558 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
560 /// Represents a wildcard pattern (`_`).
563 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
564 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
565 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
566 /// during name resolution.
567 Ident(BindingMode, Ident, Option<P<Pat>>),
569 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
570 /// The `bool` is `true` in the presence of a `..`.
571 Struct(Path, Vec<Spanned<FieldPat>>, bool),
573 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
574 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
575 /// `0 <= position <= subpats.len()`.
576 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
578 /// A possibly qualified path pattern.
579 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
580 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
581 /// only legally refer to associated constants.
582 Path(Option<QSelf>, Path),
584 /// A tuple pattern (`(a, b)`).
585 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
586 /// `0 <= position <= subpats.len()`.
587 Tuple(Vec<P<Pat>>, Option<usize>),
590 /// A reference pattern (e.g., `&mut (a, b)`).
591 Ref(P<Pat>, Mutability),
594 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
595 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
596 /// `[a, b, ..i, y, z]` is represented as:
597 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
598 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
599 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
601 /// A macro pattern; pre-expansion.
606 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
608 pub enum Mutability {
613 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
615 /// The `+` operator (addition)
617 /// The `-` operator (subtraction)
619 /// The `*` operator (multiplication)
621 /// The `/` operator (division)
623 /// The `%` operator (modulus)
625 /// The `&&` operator (logical and)
627 /// The `||` operator (logical or)
629 /// The `^` operator (bitwise xor)
631 /// The `&` operator (bitwise and)
633 /// The `|` operator (bitwise or)
635 /// The `<<` operator (shift left)
637 /// The `>>` operator (shift right)
639 /// The `==` operator (equality)
641 /// The `<` operator (less than)
643 /// The `<=` operator (less than or equal to)
645 /// The `!=` operator (not equal to)
647 /// The `>=` operator (greater than or equal to)
649 /// The `>` operator (greater than)
654 pub fn to_string(&self) -> &'static str {
655 use self::BinOpKind::*;
677 pub fn lazy(&self) -> bool {
679 BinOpKind::And | BinOpKind::Or => true,
684 pub fn is_shift(&self) -> bool {
686 BinOpKind::Shl | BinOpKind::Shr => true,
691 pub fn is_comparison(&self) -> bool {
692 use self::BinOpKind::*;
694 Eq | Lt | Le | Ne | Gt | Ge => true,
695 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
699 /// Returns `true` if the binary operator takes its arguments by value
700 pub fn is_by_value(&self) -> bool {
701 !self.is_comparison()
705 pub type BinOp = Spanned<BinOpKind>;
707 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
709 /// The `*` operator for dereferencing
711 /// The `!` operator for logical inversion
713 /// The `-` operator for negation
718 /// Returns `true` if the unary operator takes its argument by value
719 pub fn is_by_value(u: UnOp) -> bool {
721 UnOp::Neg | UnOp::Not => true,
726 pub fn to_string(op: UnOp) -> &'static str {
736 #[derive(Clone, RustcEncodable, RustcDecodable)]
744 pub fn add_trailing_semicolon(mut self) -> Self {
745 self.node = match self.node {
746 StmtKind::Expr(expr) => StmtKind::Semi(expr),
747 StmtKind::Mac(mac) => {
748 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
755 pub fn is_item(&self) -> bool {
757 StmtKind::Item(_) => true,
762 pub fn is_expr(&self) -> bool {
764 StmtKind::Expr(_) => true,
770 impl fmt::Debug for Stmt {
771 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
776 pprust::stmt_to_string(self)
781 #[derive(Clone, RustcEncodable, RustcDecodable)]
783 /// A local (let) binding.
786 /// An item definition.
789 /// Expr without trailing semi-colon.
791 /// Expr with a trailing semi-colon.
794 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
797 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
798 pub enum MacStmtStyle {
799 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
800 /// `foo!(...);`, `foo![...];`).
802 /// The macro statement had braces (e.g., `foo! { ... }`).
804 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
805 /// `foo!(...)`). All of these will end up being converted into macro
810 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
811 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
814 pub ty: Option<P<Ty>>,
815 /// Initializer expression to set the value, if any.
816 pub init: Option<P<Expr>>,
819 pub attrs: ThinVec<Attribute>,
822 /// An arm of a 'match'.
824 /// E.g., `0..=10 => { println!("match!") }` as in
828 /// 0..=10 => { println!("match!") },
829 /// _ => { println!("no match!") },
832 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
834 pub attrs: Vec<Attribute>,
835 pub pats: Vec<P<Pat>>,
836 pub guard: Option<Guard>,
840 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
845 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
850 pub is_shorthand: bool,
851 pub attrs: ThinVec<Attribute>,
854 pub type SpannedIdent = Spanned<Ident>;
856 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
857 pub enum BlockCheckMode {
859 Unsafe(UnsafeSource),
862 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
863 pub enum UnsafeSource {
868 /// A constant (expression) that's not an item or associated item,
869 /// but needs its own `DefId` for type-checking, const-eval, etc.
870 /// These are usually found nested inside types (e.g., array lengths)
871 /// or expressions (e.g., repeat counts), and also used to define
872 /// explicit discriminant values for enum variants.
873 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
874 pub struct AnonConst {
880 #[derive(Clone, RustcEncodable, RustcDecodable)]
885 pub attrs: ThinVec<Attribute>,
888 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
889 #[cfg(target_arch = "x86_64")]
890 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 88);
893 /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
895 pub fn returns(&self) -> bool {
896 if let ExprKind::Block(ref block, _) = self.node {
897 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
899 Some(&StmtKind::Expr(_)) => true,
900 Some(&StmtKind::Semi(ref expr)) => {
901 if let ExprKind::Ret(_) = expr.node {
902 // last statement is explicit return
908 // This is a block that doesn't end in either an implicit or explicit return
912 // This is not a block, it is a value
917 fn to_bound(&self) -> Option<GenericBound> {
919 ExprKind::Path(None, path) => Some(GenericBound::Trait(
920 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
921 TraitBoundModifier::None,
927 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
928 let node = match &self.node {
929 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
930 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
931 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
932 ExprKind::AddrOf(mutbl, expr) => expr
934 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
935 ExprKind::Repeat(expr, expr_len) => {
936 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
938 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
939 ExprKind::Tup(exprs) => {
942 .map(|expr| expr.to_ty())
943 .collect::<Option<Vec<_>>>()?;
946 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
947 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
948 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
963 pub fn precedence(&self) -> ExprPrecedence {
965 ExprKind::Box(_) => ExprPrecedence::Box,
966 ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
967 ExprKind::Array(_) => ExprPrecedence::Array,
968 ExprKind::Call(..) => ExprPrecedence::Call,
969 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
970 ExprKind::Tup(_) => ExprPrecedence::Tup,
971 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
972 ExprKind::Unary(..) => ExprPrecedence::Unary,
973 ExprKind::Lit(_) => ExprPrecedence::Lit,
974 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
975 ExprKind::If(..) => ExprPrecedence::If,
976 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
977 ExprKind::While(..) => ExprPrecedence::While,
978 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
979 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
980 ExprKind::Loop(..) => ExprPrecedence::Loop,
981 ExprKind::Match(..) => ExprPrecedence::Match,
982 ExprKind::Closure(..) => ExprPrecedence::Closure,
983 ExprKind::Block(..) => ExprPrecedence::Block,
984 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
985 ExprKind::Async(..) => ExprPrecedence::Async,
986 ExprKind::Assign(..) => ExprPrecedence::Assign,
987 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
988 ExprKind::Field(..) => ExprPrecedence::Field,
989 ExprKind::Index(..) => ExprPrecedence::Index,
990 ExprKind::Range(..) => ExprPrecedence::Range,
991 ExprKind::Path(..) => ExprPrecedence::Path,
992 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
993 ExprKind::Break(..) => ExprPrecedence::Break,
994 ExprKind::Continue(..) => ExprPrecedence::Continue,
995 ExprKind::Ret(..) => ExprPrecedence::Ret,
996 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
997 ExprKind::Mac(..) => ExprPrecedence::Mac,
998 ExprKind::Struct(..) => ExprPrecedence::Struct,
999 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1000 ExprKind::Paren(..) => ExprPrecedence::Paren,
1001 ExprKind::Try(..) => ExprPrecedence::Try,
1002 ExprKind::Yield(..) => ExprPrecedence::Yield,
1003 ExprKind::Err => ExprPrecedence::Err,
1008 impl fmt::Debug for Expr {
1009 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1010 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1014 /// Limit types of a range (inclusive or exclusive)
1015 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1016 pub enum RangeLimits {
1017 /// Inclusive at the beginning, exclusive at the end
1019 /// Inclusive at the beginning and end
1023 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1025 /// A `box x` expression.
1027 /// First expr is the place; second expr is the value.
1028 ObsoleteInPlace(P<Expr>, P<Expr>),
1029 /// An array (`[a, b, c, d]`)
1030 Array(Vec<P<Expr>>),
1033 /// The first field resolves to the function itself,
1034 /// and the second field is the list of arguments.
1035 /// This also represents calling the constructor of
1036 /// tuple-like ADTs such as tuple structs and enum variants.
1037 Call(P<Expr>, Vec<P<Expr>>),
1038 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1040 /// The `PathSegment` represents the method name and its generic arguments
1041 /// (within the angle brackets).
1042 /// The first element of the vector of an `Expr` is the expression that evaluates
1043 /// to the object on which the method is being called on (the receiver),
1044 /// and the remaining elements are the rest of the arguments.
1045 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1046 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1047 MethodCall(PathSegment, Vec<P<Expr>>),
1048 /// A tuple (e.g., `(a, b, c, d)`).
1050 /// A binary operation (e.g., `a + b`, `a * b`).
1051 Binary(BinOp, P<Expr>, P<Expr>),
1052 /// A unary operation (e.g., `!x`, `*x`).
1053 Unary(UnOp, P<Expr>),
1054 /// A literal (e.g., `1`, `"foo"`).
1056 /// A cast (e.g., `foo as f64`).
1057 Cast(P<Expr>, P<Ty>),
1058 Type(P<Expr>, P<Ty>),
1059 /// An `if` block, with an optional `else` block.
1061 /// `if expr { block } else { expr }`
1062 If(P<Expr>, P<Block>, Option<P<Expr>>),
1063 /// An `if let` expression with an optional else block
1065 /// `if let pat = expr { block } else { expr }`
1067 /// This is desugared to a `match` expression.
1068 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1069 /// A while loop, with an optional label
1071 /// `'label: while expr { block }`
1072 While(P<Expr>, P<Block>, Option<Label>),
1073 /// A `while let` loop, with an optional label.
1075 /// `'label: while let pat = expr { block }`
1077 /// This is desugared to a combination of `loop` and `match` expressions.
1078 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1079 /// A `for` loop, with an optional label.
1081 /// `'label: for pat in expr { block }`
1083 /// This is desugared to a combination of `loop` and `match` expressions.
1084 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1085 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1087 /// `'label: loop { block }`
1088 Loop(P<Block>, Option<Label>),
1089 /// A `match` block.
1090 Match(P<Expr>, Vec<Arm>),
1091 /// A closure (e.g., `move |a, b, c| a + b + c`).
1093 /// The final span is the span of the argument block `|...|`.
1094 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1095 /// A block (`'label: { ... }`).
1096 Block(P<Block>, Option<Label>),
1097 /// An async block (`async move { ... }`).
1099 /// The `NodeId` is the `NodeId` for the closure that results from
1100 /// desugaring an async block, just like the NodeId field in the
1101 /// `IsAsync` enum. This is necessary in order to create a def for the
1102 /// closure which can be used as a parent of any child defs. Defs
1103 /// created during lowering cannot be made the parent of any other
1104 /// preexisting defs.
1105 Async(CaptureBy, NodeId, P<Block>),
1106 /// A try block (`try { ... }`).
1109 /// An assignment (`a = foo()`).
1110 Assign(P<Expr>, P<Expr>),
1111 /// An assignment with an operator.
1114 AssignOp(BinOp, P<Expr>, P<Expr>),
1115 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1116 Field(P<Expr>, Ident),
1117 /// An indexing operation (e.g., `foo[2]`).
1118 Index(P<Expr>, P<Expr>),
1119 /// A range (e.g., `1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`).
1120 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1122 /// Variable reference, possibly containing `::` and/or type
1123 /// parameters (e.g., `foo::bar::<baz>`).
1125 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1126 Path(Option<QSelf>, Path),
1128 /// A referencing operation (`&a` or `&mut a`).
1129 AddrOf(Mutability, P<Expr>),
1130 /// A `break`, with an optional label to break, and an optional expression.
1131 Break(Option<Label>, Option<P<Expr>>),
1132 /// A `continue`, with an optional label.
1133 Continue(Option<Label>),
1134 /// A `return`, with an optional value to be returned.
1135 Ret(Option<P<Expr>>),
1137 /// Output of the `asm!()` macro.
1138 InlineAsm(P<InlineAsm>),
1140 /// A macro invocation; pre-expansion.
1143 /// A struct literal expression.
1145 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1146 /// where `base` is the `Option<Expr>`.
1147 Struct(Path, Vec<Field>, Option<P<Expr>>),
1149 /// An array literal constructed from one repeated element.
1151 /// E.g., `[1; 5]`. The expression is the element to be
1152 /// repeated; the constant is the number of times to repeat it.
1153 Repeat(P<Expr>, AnonConst),
1155 /// No-op: used solely so we can pretty-print faithfully.
1158 /// A try expression (`expr?`).
1161 /// A `yield`, with an optional value to be yielded.
1162 Yield(Option<P<Expr>>),
1164 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1168 /// The explicit `Self` type in a "qualified path". The actual
1169 /// path, including the trait and the associated item, is stored
1170 /// separately. `position` represents the index of the associated
1171 /// item qualified with this `Self` type.
1173 /// ```ignore (only-for-syntax-highlight)
1174 /// <Vec<T> as a::b::Trait>::AssociatedItem
1175 /// ^~~~~ ~~~~~~~~~~~~~~^
1178 /// <Vec<T>>::AssociatedItem
1182 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1186 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1187 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1188 /// 0`, this is an empty span.
1189 pub path_span: Span,
1190 pub position: usize,
1193 /// A capture clause.
1194 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1195 pub enum CaptureBy {
1200 /// The movability of a generator / closure literal.
1201 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1202 pub enum Movability {
1207 pub type Mac = Spanned<Mac_>;
1209 /// Represents a macro invocation. The `Path` indicates which macro
1210 /// is being invoked, and the vector of token-trees contains the source
1211 /// of the macro invocation.
1213 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1214 /// stored in the enclosing item.
1215 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1218 pub delim: MacDelimiter,
1219 pub tts: ThinTokenStream,
1222 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1223 pub enum MacDelimiter {
1230 pub fn stream(&self) -> TokenStream {
1235 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1236 pub struct MacroDef {
1237 pub tokens: ThinTokenStream,
1242 pub fn stream(&self) -> TokenStream {
1243 self.tokens.clone().into()
1247 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1249 /// A regular string, like `"foo"`.
1251 /// A raw string, like `r##"foo"##`.
1253 /// The value is the number of `#` symbols used.
1258 pub type Lit = Spanned<LitKind>;
1260 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1261 pub enum LitIntType {
1269 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1270 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1272 /// A string literal (`"foo"`).
1273 Str(Symbol, StrStyle),
1274 /// A byte string (`b"foo"`).
1275 ByteStr(Lrc<Vec<u8>>),
1276 /// A byte char (`b'f'`).
1278 /// A character literal (`'a'`).
1280 /// An integer literal (`1`).
1281 Int(u128, LitIntType),
1282 /// A float literal (`1f64` or `1E10f64`).
1283 Float(Symbol, FloatTy),
1284 /// A float literal without a suffix (`1.0 or 1.0E10`).
1285 FloatUnsuffixed(Symbol),
1286 /// A boolean literal.
1291 /// Returns `true` if this literal is a string.
1292 pub fn is_str(&self) -> bool {
1294 LitKind::Str(..) => true,
1299 /// Returns `true` if this literal is byte literal string.
1300 pub fn is_bytestr(&self) -> bool {
1302 LitKind::ByteStr(_) => true,
1307 /// Returns `true` if this is a numeric literal.
1308 pub fn is_numeric(&self) -> bool {
1310 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1315 /// Returns `true` if this literal has no suffix.
1316 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1317 pub fn is_unsuffixed(&self) -> bool {
1319 // unsuffixed variants
1321 | LitKind::ByteStr(..)
1324 | LitKind::Int(_, LitIntType::Unsuffixed)
1325 | LitKind::FloatUnsuffixed(..)
1326 | LitKind::Bool(..) => true,
1327 // suffixed variants
1328 LitKind::Int(_, LitIntType::Signed(..))
1329 | LitKind::Int(_, LitIntType::Unsigned(..))
1330 | LitKind::Float(..) => false,
1334 /// Returns `true` if this literal has a suffix.
1335 pub fn is_suffixed(&self) -> bool {
1336 !self.is_unsuffixed()
1340 // N.B., If you change this, you'll probably want to change the corresponding
1341 // type structure in `middle/ty.rs` as well.
1342 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1345 pub mutbl: Mutability,
1348 /// Represents a method's signature in a trait declaration,
1349 /// or in an implementation.
1350 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1351 pub struct MethodSig {
1352 pub header: FnHeader,
1353 pub decl: P<FnDecl>,
1356 /// Represents an item declaration within a trait declaration,
1357 /// possibly including a default implementation. A trait item is
1358 /// either required (meaning it doesn't have an implementation, just a
1359 /// signature) or provided (meaning it has a default implementation).
1360 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1361 pub struct TraitItem {
1364 pub attrs: Vec<Attribute>,
1365 pub generics: Generics,
1366 pub node: TraitItemKind,
1368 /// See `Item::tokens` for what this is.
1369 pub tokens: Option<TokenStream>,
1372 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1373 pub enum TraitItemKind {
1374 Const(P<Ty>, Option<P<Expr>>),
1375 Method(MethodSig, Option<P<Block>>),
1376 Type(GenericBounds, Option<P<Ty>>),
1380 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1381 pub struct ImplItem {
1384 pub vis: Visibility,
1385 pub defaultness: Defaultness,
1386 pub attrs: Vec<Attribute>,
1387 pub generics: Generics,
1388 pub node: ImplItemKind,
1390 /// See `Item::tokens` for what this is.
1391 pub tokens: Option<TokenStream>,
1394 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1395 pub enum ImplItemKind {
1396 Const(P<Ty>, P<Expr>),
1397 Method(MethodSig, P<Block>),
1399 Existential(GenericBounds),
1403 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1413 impl fmt::Debug for IntTy {
1414 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1415 fmt::Display::fmt(self, f)
1419 impl fmt::Display for IntTy {
1420 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1421 write!(f, "{}", self.ty_to_string())
1426 pub fn ty_to_string(&self) -> &'static str {
1428 IntTy::Isize => "isize",
1430 IntTy::I16 => "i16",
1431 IntTy::I32 => "i32",
1432 IntTy::I64 => "i64",
1433 IntTy::I128 => "i128",
1437 pub fn val_to_string(&self, val: i128) -> String {
1438 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1439 // are parsed as `u128`, so we wouldn't want to print an extra negative
1441 format!("{}{}", val as u128, self.ty_to_string())
1444 pub fn bit_width(&self) -> Option<usize> {
1446 IntTy::Isize => return None,
1456 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1467 pub fn ty_to_string(&self) -> &'static str {
1469 UintTy::Usize => "usize",
1471 UintTy::U16 => "u16",
1472 UintTy::U32 => "u32",
1473 UintTy::U64 => "u64",
1474 UintTy::U128 => "u128",
1478 pub fn val_to_string(&self, val: u128) -> String {
1479 format!("{}{}", val, self.ty_to_string())
1482 pub fn bit_width(&self) -> Option<usize> {
1484 UintTy::Usize => return None,
1489 UintTy::U128 => 128,
1494 impl fmt::Debug for UintTy {
1495 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1496 fmt::Display::fmt(self, f)
1500 impl fmt::Display for UintTy {
1501 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1502 write!(f, "{}", self.ty_to_string())
1506 // Bind a type to an associated type: `A = Foo`.
1507 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1508 pub struct TypeBinding {
1515 #[derive(Clone, RustcEncodable, RustcDecodable)]
1522 impl fmt::Debug for Ty {
1523 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1524 write!(f, "type({})", pprust::ty_to_string(self))
1528 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1529 pub struct BareFnTy {
1530 pub unsafety: Unsafety,
1532 pub generic_params: Vec<GenericParam>,
1533 pub decl: P<FnDecl>,
1536 /// The different kinds of types recognized by the compiler.
1537 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1539 /// A variable-length slice (`[T]`).
1541 /// A fixed length array (`[T; n]`).
1542 Array(P<Ty>, AnonConst),
1543 /// A raw pointer (`*const T` or `*mut T`).
1545 /// A reference (`&'a T` or `&'a mut T`).
1546 Rptr(Option<Lifetime>, MutTy),
1547 /// A bare function (e.g., `fn(usize) -> bool`).
1548 BareFn(P<BareFnTy>),
1549 /// The never type (`!`).
1551 /// A tuple (`(A, B, C, D,...)`).
1553 /// A path (`module::module::...::Type`), optionally
1554 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1556 /// Type parameters are stored in the `Path` itself.
1557 Path(Option<QSelf>, Path),
1558 /// A trait object type `Bound1 + Bound2 + Bound3`
1559 /// where `Bound` is a trait or a lifetime.
1560 TraitObject(GenericBounds, TraitObjectSyntax),
1561 /// An `impl Bound1 + Bound2 + Bound3` type
1562 /// where `Bound` is a trait or a lifetime.
1564 /// The `NodeId` exists to prevent lowering from having to
1565 /// generate `NodeId`s on the fly, which would complicate
1566 /// the generation of `existential type` items significantly.
1567 ImplTrait(NodeId, GenericBounds),
1568 /// No-op; kept solely so that we can pretty-print faithfully.
1572 /// This means the type should be inferred instead of it having been
1573 /// specified. This can appear anywhere in a type.
1575 /// Inferred type of a `self` or `&self` argument in a method.
1577 /// A macro in the type position.
1579 /// Placeholder for a kind that has failed to be defined.
1584 pub fn is_implicit_self(&self) -> bool {
1585 if let TyKind::ImplicitSelf = *self {
1592 pub fn is_unit(&self) -> bool {
1593 if let TyKind::Tup(ref tys) = *self {
1601 /// Syntax used to declare a trait object.
1602 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1603 pub enum TraitObjectSyntax {
1608 /// Inline assembly dialect.
1610 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1611 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1612 pub enum AsmDialect {
1617 /// Inline assembly.
1619 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1620 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1621 pub struct InlineAsmOutput {
1622 pub constraint: Symbol,
1625 pub is_indirect: bool,
1628 /// Inline assembly.
1630 /// E.g., `asm!("NOP");`.
1631 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1632 pub struct InlineAsm {
1634 pub asm_str_style: StrStyle,
1635 pub outputs: Vec<InlineAsmOutput>,
1636 pub inputs: Vec<(Symbol, P<Expr>)>,
1637 pub clobbers: Vec<Symbol>,
1639 pub alignstack: bool,
1640 pub dialect: AsmDialect,
1641 pub ctxt: SyntaxContext,
1644 /// An argument in a function header.
1646 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1647 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1654 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1656 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1657 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1659 /// `self`, `mut self`
1661 /// `&'lt self`, `&'lt mut self`
1662 Region(Option<Lifetime>, Mutability),
1663 /// `self: TYPE`, `mut self: TYPE`
1664 Explicit(P<Ty>, Mutability),
1667 pub type ExplicitSelf = Spanned<SelfKind>;
1670 pub fn to_self(&self) -> Option<ExplicitSelf> {
1671 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1672 if ident.name == keywords::SelfLower.name() {
1673 return match self.ty.node {
1674 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1675 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1676 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1679 self.pat.span.to(self.ty.span),
1680 SelfKind::Explicit(self.ty.clone(), mutbl),
1688 pub fn is_self(&self) -> bool {
1689 if let PatKind::Ident(_, ident, _) = self.pat.node {
1690 ident.name == keywords::SelfLower.name()
1696 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1697 let span = eself.span.to(eself_ident.span);
1698 let infer_ty = P(Ty {
1700 node: TyKind::ImplicitSelf,
1703 let arg = |mutbl, ty| Arg {
1706 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1713 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1714 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1715 SelfKind::Region(lt, mutbl) => arg(
1716 Mutability::Immutable,
1733 /// Header (not the body) of a function declaration.
1735 /// E.g., `fn foo(bar: baz)`.
1736 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1738 pub inputs: Vec<Arg>,
1739 pub output: FunctionRetTy,
1744 pub fn get_self(&self) -> Option<ExplicitSelf> {
1745 self.inputs.get(0).and_then(Arg::to_self)
1747 pub fn has_self(&self) -> bool {
1748 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1752 /// Is the trait definition an auto trait?
1753 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1759 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1765 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1769 return_impl_trait_id: NodeId,
1775 pub fn is_async(self) -> bool {
1776 if let IsAsync::Async { .. } = self {
1783 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1784 pub fn opt_return_id(self) -> Option<NodeId> {
1787 return_impl_trait_id,
1789 } => Some(return_impl_trait_id),
1790 IsAsync::NotAsync => None,
1795 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1796 pub enum Constness {
1801 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1802 pub enum Defaultness {
1807 impl fmt::Display for Unsafety {
1808 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1811 Unsafety::Normal => "normal",
1812 Unsafety::Unsafe => "unsafe",
1819 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1820 pub enum ImplPolarity {
1821 /// `impl Trait for Type`
1823 /// `impl !Trait for Type`
1827 impl fmt::Debug for ImplPolarity {
1828 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1830 ImplPolarity::Positive => "positive".fmt(f),
1831 ImplPolarity::Negative => "negative".fmt(f),
1836 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1837 pub enum FunctionRetTy {
1838 /// Return type is not specified.
1840 /// Functions default to `()` and closures default to inference.
1841 /// Span points to where return type would be inserted.
1843 /// Everything else.
1847 impl FunctionRetTy {
1848 pub fn span(&self) -> Span {
1850 FunctionRetTy::Default(span) => span,
1851 FunctionRetTy::Ty(ref ty) => ty.span,
1856 /// Module declaration.
1858 /// E.g., `mod foo;` or `mod foo { .. }`.
1859 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1861 /// A span from the first token past `{` to the last token until `}`.
1862 /// For `mod foo;`, the inner span ranges from the first token
1863 /// to the last token in the external file.
1865 pub items: Vec<P<Item>>,
1866 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
1870 /// Foreign module declaration.
1872 /// E.g., `extern { .. }` or `extern C { .. }`.
1873 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1874 pub struct ForeignMod {
1876 pub items: Vec<ForeignItem>,
1879 /// Global inline assembly.
1881 /// Also known as "module-level assembly" or "file-scoped assembly".
1882 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1883 pub struct GlobalAsm {
1885 pub ctxt: SyntaxContext,
1888 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1889 pub struct EnumDef {
1890 pub variants: Vec<Variant>,
1893 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1894 pub struct Variant_ {
1896 pub attrs: Vec<Attribute>,
1897 pub data: VariantData,
1898 /// Explicit discriminant, e.g., `Foo = 1`.
1899 pub disr_expr: Option<AnonConst>,
1902 pub type Variant = Spanned<Variant_>;
1904 /// Part of `use` item to the right of its prefix.
1905 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1906 pub enum UseTreeKind {
1907 /// `use prefix` or `use prefix as rename`
1909 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1911 Simple(Option<Ident>, NodeId, NodeId),
1912 /// `use prefix::{...}`
1913 Nested(Vec<(UseTree, NodeId)>),
1918 /// A tree of paths sharing common prefixes.
1919 /// Used in `use` items both at top-level and inside of braces in import groups.
1920 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1921 pub struct UseTree {
1923 pub kind: UseTreeKind,
1928 pub fn ident(&self) -> Ident {
1930 UseTreeKind::Simple(Some(rename), ..) => rename,
1931 UseTreeKind::Simple(None, ..) => {
1935 .expect("empty prefix in a simple import")
1938 _ => panic!("`UseTree::ident` can only be used on a simple import"),
1943 /// Distinguishes between `Attribute`s that decorate items and Attributes that
1944 /// are contained as statements within items. These two cases need to be
1945 /// distinguished for pretty-printing.
1946 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1947 pub enum AttrStyle {
1953 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
1955 pub struct AttrId(pub usize);
1957 impl Idx for AttrId {
1958 fn new(idx: usize) -> Self {
1961 fn index(self) -> usize {
1966 /// Metadata associated with an item.
1967 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
1968 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1969 pub struct Attribute {
1971 pub style: AttrStyle,
1973 pub tokens: TokenStream,
1974 pub is_sugared_doc: bool,
1978 /// `TraitRef`s appear in impls.
1980 /// Resolve maps each `TraitRef`'s `ref_id` to its defining trait; that's all
1981 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
1982 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
1983 /// same as the impl's node-id).
1984 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1985 pub struct TraitRef {
1990 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1991 pub struct PolyTraitRef {
1992 /// The `'a` in `<'a> Foo<&'a T>`
1993 pub bound_generic_params: Vec<GenericParam>,
1995 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1996 pub trait_ref: TraitRef,
2002 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2004 bound_generic_params: generic_params,
2005 trait_ref: TraitRef {
2007 ref_id: DUMMY_NODE_ID,
2014 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2015 pub enum CrateSugar {
2016 /// Source is `pub(crate)`.
2019 /// Source is (just) `crate`.
2023 pub type Visibility = Spanned<VisibilityKind>;
2025 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2026 pub enum VisibilityKind {
2029 Restricted { path: P<Path>, id: NodeId },
2033 impl VisibilityKind {
2034 pub fn is_pub(&self) -> bool {
2035 if let VisibilityKind::Public = *self {
2043 /// Field of a struct.
2045 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2046 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2047 pub struct StructField {
2049 pub ident: Option<Ident>,
2050 pub vis: Visibility,
2053 pub attrs: Vec<Attribute>,
2056 /// Fields and Ids of enum variants and structs
2058 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2059 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2060 /// One shared Id can be successfully used for these two purposes.
2061 /// Id of the whole enum lives in `Item`.
2063 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2064 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2065 /// the variant itself" from enum variants.
2066 /// Id of the whole struct lives in `Item`.
2067 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2068 pub enum VariantData {
2071 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2072 Struct(Vec<StructField>, NodeId),
2075 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2076 Tuple(Vec<StructField>, NodeId),
2079 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2084 pub fn fields(&self) -> &[StructField] {
2086 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2090 pub fn id(&self) -> NodeId {
2092 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2095 pub fn is_struct(&self) -> bool {
2096 if let VariantData::Struct(..) = *self {
2102 pub fn is_tuple(&self) -> bool {
2103 if let VariantData::Tuple(..) = *self {
2109 pub fn is_unit(&self) -> bool {
2110 if let VariantData::Unit(..) = *self {
2120 /// The name might be a dummy name in case of anonymous items.
2121 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2124 pub attrs: Vec<Attribute>,
2127 pub vis: Visibility,
2130 /// Original tokens this item was parsed from. This isn't necessarily
2131 /// available for all items, although over time more and more items should
2132 /// have this be `Some`. Right now this is primarily used for procedural
2133 /// macros, notably custom attributes.
2135 /// Note that the tokens here do not include the outer attributes, but will
2136 /// include inner attributes.
2137 pub tokens: Option<TokenStream>,
2140 /// A function header.
2142 /// All the information between the visibility and the name of the function is
2143 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2144 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2145 pub struct FnHeader {
2146 pub unsafety: Unsafety,
2147 pub asyncness: IsAsync,
2148 pub constness: Spanned<Constness>,
2152 impl Default for FnHeader {
2153 fn default() -> FnHeader {
2155 unsafety: Unsafety::Normal,
2156 asyncness: IsAsync::NotAsync,
2157 constness: dummy_spanned(Constness::NotConst),
2163 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2165 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2167 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2168 ExternCrate(Option<Name>),
2169 /// A use declaration (`use` or `pub use`) item.
2171 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2173 /// A static item (`static` or `pub static`).
2175 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2176 Static(P<Ty>, Mutability, P<Expr>),
2177 /// A constant item (`const` or `pub const`).
2179 /// E.g., `const FOO: i32 = 42;`.
2180 Const(P<Ty>, P<Expr>),
2181 /// A function declaration (`fn` or `pub fn`).
2183 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2184 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2185 /// A module declaration (`mod` or `pub mod`).
2187 /// E.g., `mod foo;` or `mod foo { .. }`.
2189 /// An external module (`extern` or `pub extern`).
2191 /// E.g., `extern {}` or `extern "C" {}`.
2192 ForeignMod(ForeignMod),
2193 /// Module-level inline assembly (from `global_asm!()`).
2194 GlobalAsm(P<GlobalAsm>),
2195 /// A type alias (`type` or `pub type`).
2197 /// E.g., `type Foo = Bar<u8>;`.
2198 Ty(P<Ty>, Generics),
2199 /// An existential type declaration (`existential type`).
2201 /// E.g., `existential type Foo: Bar + Boo;`.
2202 Existential(GenericBounds, Generics),
2203 /// An enum definition (`enum` or `pub enum`).
2205 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2206 Enum(EnumDef, Generics),
2207 /// A struct definition (`struct` or `pub struct`).
2209 /// E.g., `struct Foo<A> { x: A }`.
2210 Struct(VariantData, Generics),
2211 /// A union definition (`union` or `pub union`).
2213 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2214 Union(VariantData, Generics),
2215 /// A Trait declaration (`trait` or `pub trait`).
2217 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2218 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2221 /// E.g., `trait Foo = Bar + Quux;`.
2222 TraitAlias(Generics, GenericBounds),
2223 /// An implementation.
2225 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2231 Option<TraitRef>, // (optional) trait this impl implements
2235 /// A macro invocation.
2237 /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2240 /// A macro definition.
2245 pub fn descriptive_variant(&self) -> &str {
2247 ItemKind::ExternCrate(..) => "extern crate",
2248 ItemKind::Use(..) => "use",
2249 ItemKind::Static(..) => "static item",
2250 ItemKind::Const(..) => "constant item",
2251 ItemKind::Fn(..) => "function",
2252 ItemKind::Mod(..) => "module",
2253 ItemKind::ForeignMod(..) => "foreign module",
2254 ItemKind::GlobalAsm(..) => "global asm",
2255 ItemKind::Ty(..) => "type alias",
2256 ItemKind::Existential(..) => "existential type",
2257 ItemKind::Enum(..) => "enum",
2258 ItemKind::Struct(..) => "struct",
2259 ItemKind::Union(..) => "union",
2260 ItemKind::Trait(..) => "trait",
2261 ItemKind::TraitAlias(..) => "trait alias",
2262 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2267 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2268 pub struct ForeignItem {
2270 pub attrs: Vec<Attribute>,
2271 pub node: ForeignItemKind,
2274 pub vis: Visibility,
2277 /// An item within an `extern` block.
2278 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2279 pub enum ForeignItemKind {
2280 /// A foreign function.
2281 Fn(P<FnDecl>, Generics),
2282 /// A foreign static item (`static ext: u8`), with optional mutability.
2283 /// (The boolean is `true` for mutable items).
2284 Static(P<Ty>, bool),
2287 /// A macro invocation.
2291 impl ForeignItemKind {
2292 pub fn descriptive_variant(&self) -> &str {
2294 ForeignItemKind::Fn(..) => "foreign function",
2295 ForeignItemKind::Static(..) => "foreign static item",
2296 ForeignItemKind::Ty => "foreign type",
2297 ForeignItemKind::Macro(..) => "macro in foreign module",
2307 // Are ASTs encodable?
2309 fn check_asts_encodable() {
2310 fn assert_encodable<T: serialize::Encodable>() {}
2311 assert_encodable::<Crate>();