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::TyParamBound::*;
14 pub use self::UnsafeSource::*;
15 pub use self::PathParameters::*;
16 pub use symbol::{Ident, Symbol as Name};
17 pub use util::ThinVec;
18 pub use util::parser::ExprPrecedence;
20 use syntax_pos::{Span, DUMMY_SP};
21 use codemap::{respan, Spanned};
22 use rustc_target::spec::abi::Abi;
23 use ext::hygiene::{Mark, SyntaxContext};
26 use rustc_data_structures::indexed_vec;
27 use symbol::{Symbol, keywords};
28 use tokenstream::{ThinTokenStream, TokenStream};
30 use serialize::{self, Encoder, Decoder};
31 use std::collections::HashSet;
33 use rustc_data_structures::sync::Lrc;
36 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
41 impl fmt::Debug for Label {
42 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43 write!(f, "label({:?})", self.ident)
47 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
53 impl fmt::Debug for Lifetime {
54 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
59 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
60 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
61 pub struct LifetimeDef {
62 pub attrs: ThinVec<Attribute>,
63 pub lifetime: Lifetime,
64 pub bounds: Vec<Lifetime>
67 /// A "Path" is essentially Rust's notion of a name.
69 /// It's represented as a sequence of identifiers,
70 /// along with a bunch of supporting information.
72 /// E.g. `std::cmp::PartialEq`
73 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
76 /// The segments in the path: the things separated by `::`.
77 /// Global paths begin with `keywords::CrateRoot`.
78 pub segments: Vec<PathSegment>,
81 impl<'a> PartialEq<&'a str> for Path {
82 fn eq(&self, string: &&'a str) -> bool {
83 self.segments.len() == 1 && self.segments[0].ident.name == *string
87 impl fmt::Debug for Path {
88 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89 write!(f, "path({})", pprust::path_to_string(self))
93 impl fmt::Display for Path {
94 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
95 write!(f, "{}", pprust::path_to_string(self))
100 // convert a span and an identifier to the corresponding
102 pub fn from_ident(ident: Ident) -> Path {
103 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span }
106 // Make a "crate root" segment for this path unless it already has it
107 // or starts with something like `self`/`super`/`$crate`/etc.
108 pub fn make_root(&self) -> Option<PathSegment> {
109 if let Some(ident) = self.segments.get(0).map(|seg| seg.ident) {
110 if ::parse::token::is_path_segment_keyword(ident) &&
111 ident.name != keywords::Crate.name() {
115 Some(PathSegment::crate_root(self.span.shrink_to_lo()))
118 pub fn is_global(&self) -> bool {
119 !self.segments.is_empty() && self.segments[0].ident.name == keywords::CrateRoot.name()
123 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
125 /// E.g. `std`, `String` or `Box<T>`
126 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
127 pub struct PathSegment {
128 /// The identifier portion of this path segment.
131 /// Type/lifetime parameters attached to this path. They come in
132 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
133 /// `None` means that no parameter list is supplied (`Path`),
134 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
135 /// but it can be empty (`Path<>`).
136 /// `P` is used as a size optimization for the common case with no parameters.
137 pub parameters: Option<P<PathParameters>>,
141 pub fn from_ident(ident: Ident) -> Self {
142 PathSegment { ident, parameters: None }
144 pub fn crate_root(span: Span) -> Self {
145 PathSegment::from_ident(Ident::new(keywords::CrateRoot.name(), span))
149 /// Parameters of a path segment.
151 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
152 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
153 pub enum PathParameters {
154 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
155 AngleBracketed(AngleBracketedParameterData),
156 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
157 Parenthesized(ParenthesizedParameterData),
160 impl PathParameters {
161 pub fn span(&self) -> Span {
163 AngleBracketed(ref data) => data.span,
164 Parenthesized(ref data) => data.span,
169 /// A path like `Foo<'a, T>`
170 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
171 pub struct AngleBracketedParameterData {
174 /// The lifetime parameters for this path segment.
175 pub lifetimes: Vec<Lifetime>,
176 /// The type parameters for this path segment, if present.
177 pub types: Vec<P<Ty>>,
178 /// Bindings (equality constraints) on associated types, if present.
180 /// E.g., `Foo<A=Bar>`.
181 pub bindings: Vec<TypeBinding>,
184 impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
185 fn into(self) -> Option<P<PathParameters>> {
186 Some(P(PathParameters::AngleBracketed(self)))
190 impl Into<Option<P<PathParameters>>> for ParenthesizedParameterData {
191 fn into(self) -> Option<P<PathParameters>> {
192 Some(P(PathParameters::Parenthesized(self)))
196 /// A path like `Foo(A,B) -> C`
197 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
198 pub struct ParenthesizedParameterData {
203 pub inputs: Vec<P<Ty>>,
206 pub output: Option<P<Ty>>,
209 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
210 pub struct NodeId(u32);
213 pub fn new(x: usize) -> NodeId {
214 assert!(x < (u32::MAX as usize));
218 pub fn from_u32(x: u32) -> NodeId {
222 pub fn as_usize(&self) -> usize {
226 pub fn as_u32(&self) -> u32 {
230 pub fn placeholder_from_mark(mark: Mark) -> Self {
231 NodeId(mark.as_u32())
234 pub fn placeholder_to_mark(self) -> Mark {
235 Mark::from_u32(self.0)
239 impl fmt::Display for NodeId {
240 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
241 fmt::Display::fmt(&self.0, f)
245 impl serialize::UseSpecializedEncodable for NodeId {
246 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
251 impl serialize::UseSpecializedDecodable for NodeId {
252 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
253 d.read_u32().map(NodeId)
257 impl indexed_vec::Idx for NodeId {
258 fn new(idx: usize) -> Self {
262 fn index(self) -> usize {
267 /// Node id used to represent the root of the crate.
268 pub const CRATE_NODE_ID: NodeId = NodeId(0);
270 /// When parsing and doing expansions, we initially give all AST nodes this AST
271 /// node value. Then later, in the renumber pass, we renumber them to have
272 /// small, positive ids.
273 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
275 /// The AST represents all type param bounds as types.
276 /// typeck::collect::compute_bounds matches these against
277 /// the "special" built-in traits (see middle::lang_items) and
278 /// detects Copy, Send and Sync.
279 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
280 pub enum TyParamBound {
281 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
282 RegionTyParamBound(Lifetime)
286 pub fn span(&self) -> Span {
288 &TraitTyParamBound(ref t, ..) => t.span,
289 &RegionTyParamBound(ref l) => l.ident.span,
294 /// A modifier on a bound, currently this is only used for `?Sized`, where the
295 /// modifier is `Maybe`. Negative bounds should also be handled here.
296 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
297 pub enum TraitBoundModifier {
302 pub type TyParamBounds = Vec<TyParamBound>;
304 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
306 pub attrs: ThinVec<Attribute>,
309 pub bounds: TyParamBounds,
310 pub default: Option<P<Ty>>,
313 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
314 pub enum GenericParam {
315 Lifetime(LifetimeDef),
320 pub fn is_lifetime_param(&self) -> bool {
322 GenericParam::Lifetime(_) => true,
327 pub fn is_type_param(&self) -> bool {
329 GenericParam::Type(_) => true,
335 /// Represents lifetime, type and const parameters attached to a declaration of
336 /// a function, enum, trait, etc.
337 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
338 pub struct Generics {
339 pub params: Vec<GenericParam>,
340 pub where_clause: WhereClause,
345 pub fn is_lt_parameterized(&self) -> bool {
346 self.params.iter().any(|param| param.is_lifetime_param())
349 pub fn is_type_parameterized(&self) -> bool {
350 self.params.iter().any(|param| param.is_type_param())
353 pub fn is_parameterized(&self) -> bool {
354 !self.params.is_empty()
357 pub fn span_for_name(&self, name: &str) -> Option<Span> {
358 for param in &self.params {
359 if let GenericParam::Type(ref t) = *param {
360 if t.ident.name == name {
361 return Some(t.ident.span);
369 impl Default for Generics {
370 /// Creates an instance of `Generics`.
371 fn default() -> Generics {
374 where_clause: WhereClause {
376 predicates: Vec::new(),
384 /// A `where` clause in a definition
385 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
386 pub struct WhereClause {
388 pub predicates: Vec<WherePredicate>,
392 /// A single predicate in a `where` clause
393 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
394 pub enum WherePredicate {
395 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
396 BoundPredicate(WhereBoundPredicate),
397 /// A lifetime predicate, e.g. `'a: 'b+'c`
398 RegionPredicate(WhereRegionPredicate),
399 /// An equality predicate (unsupported)
400 EqPredicate(WhereEqPredicate),
403 impl WherePredicate {
404 pub fn span(&self) -> Span {
406 &WherePredicate::BoundPredicate(ref p) => p.span,
407 &WherePredicate::RegionPredicate(ref p) => p.span,
408 &WherePredicate::EqPredicate(ref p) => p.span,
415 /// E.g. `for<'c> Foo: Send+Clone+'c`
416 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
417 pub struct WhereBoundPredicate {
419 /// Any generics from a `for` binding
420 pub bound_generic_params: Vec<GenericParam>,
421 /// The type being bounded
422 pub bounded_ty: P<Ty>,
423 /// Trait and lifetime bounds (`Clone+Send+'static`)
424 pub bounds: TyParamBounds,
427 /// A lifetime predicate.
430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
431 pub struct WhereRegionPredicate {
433 pub lifetime: Lifetime,
434 pub bounds: Vec<Lifetime>,
437 /// An equality predicate (unsupported).
440 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
441 pub struct WhereEqPredicate {
448 /// The set of MetaItems that define the compilation environment of the crate,
449 /// used to drive conditional compilation
450 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
452 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
455 pub attrs: Vec<Attribute>,
459 /// A spanned compile-time attribute list item.
460 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
462 /// Possible values inside of compile-time attribute lists.
464 /// E.g. the '..' in `#[name(..)]`.
465 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
466 pub enum NestedMetaItemKind {
467 /// A full MetaItem, for recursive meta items.
471 /// E.g. "foo", 64, true
475 /// A spanned compile-time attribute item.
477 /// E.g. `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`
478 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
479 pub struct MetaItem {
481 pub node: MetaItemKind,
485 /// A compile-time attribute item.
487 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
488 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
489 pub enum MetaItemKind {
492 /// E.g. `test` as in `#[test]`
496 /// E.g. `derive(..)` as in `#[derive(..)]`
497 List(Vec<NestedMetaItem>),
498 /// Name value meta item.
500 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
504 /// A Block (`{ .. }`).
506 /// E.g. `{ .. }` as in `fn foo() { .. }`
507 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
509 /// Statements in a block
510 pub stmts: Vec<Stmt>,
512 /// Distinguishes between `unsafe { ... }` and `{ ... }`
513 pub rules: BlockCheckMode,
518 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
525 impl fmt::Debug for Pat {
526 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
527 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
532 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
533 let node = match &self.node {
534 PatKind::Wild => TyKind::Infer,
535 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) =>
536 TyKind::Path(None, Path::from_ident(*ident)),
537 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
538 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
539 PatKind::Ref(pat, mutbl) =>
540 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
541 PatKind::Slice(pats, None, _) if pats.len() == 1 =>
542 pats[0].to_ty().map(TyKind::Slice)?,
543 PatKind::Tuple(pats, None) => {
544 let mut tys = Vec::new();
546 tys.push(pat.to_ty()?);
553 Some(P(Ty { node, id: self.id, span: self.span }))
556 pub fn walk<F>(&self, it: &mut F) -> bool
557 where F: FnMut(&Pat) -> bool
564 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
565 PatKind::Struct(_, ref fields, _) => {
566 fields.iter().all(|field| field.node.pat.walk(it))
568 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
569 s.iter().all(|p| p.walk(it))
571 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => {
574 PatKind::Slice(ref before, ref slice, ref after) => {
575 before.iter().all(|p| p.walk(it)) &&
576 slice.iter().all(|p| p.walk(it)) &&
577 after.iter().all(|p| p.walk(it))
591 /// A single field in a struct pattern
593 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
594 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
595 /// except is_shorthand is true
596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
597 pub struct FieldPat {
598 /// The identifier for the field
600 /// The pattern the field is destructured to
602 pub is_shorthand: bool,
603 pub attrs: ThinVec<Attribute>,
606 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
607 pub enum BindingMode {
612 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
614 Included(RangeSyntax),
618 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
619 pub enum RangeSyntax {
624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
626 /// Represents a wildcard pattern (`_`)
629 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
630 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
631 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
632 /// during name resolution.
633 Ident(BindingMode, Ident, Option<P<Pat>>),
635 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
636 /// The `bool` is `true` in the presence of a `..`.
637 Struct(Path, Vec<Spanned<FieldPat>>, bool),
639 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
640 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
641 /// 0 <= position <= subpats.len()
642 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
644 /// A possibly qualified path pattern.
645 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
646 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
647 /// only legally refer to associated constants.
648 Path(Option<QSelf>, Path),
650 /// A tuple pattern `(a, b)`.
651 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
652 /// 0 <= position <= subpats.len()
653 Tuple(Vec<P<Pat>>, Option<usize>),
656 /// A reference pattern, e.g. `&mut (a, b)`
657 Ref(P<Pat>, Mutability),
660 /// A range pattern, e.g. `1...2`, `1..=2` or `1..2`
661 Range(P<Expr>, P<Expr>, RangeEnd),
662 /// `[a, b, ..i, y, z]` is represented as:
663 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
664 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
665 /// Parentheses in patters used for grouping, i.e. `(PAT)`.
667 /// A macro pattern; pre-expansion
671 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
672 pub enum Mutability {
677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
679 /// The `+` operator (addition)
681 /// The `-` operator (subtraction)
683 /// The `*` operator (multiplication)
685 /// The `/` operator (division)
687 /// The `%` operator (modulus)
689 /// The `&&` operator (logical and)
691 /// The `||` operator (logical or)
693 /// The `^` operator (bitwise xor)
695 /// The `&` operator (bitwise and)
697 /// The `|` operator (bitwise or)
699 /// The `<<` operator (shift left)
701 /// The `>>` operator (shift right)
703 /// The `==` operator (equality)
705 /// The `<` operator (less than)
707 /// The `<=` operator (less than or equal to)
709 /// The `!=` operator (not equal to)
711 /// The `>=` operator (greater than or equal to)
713 /// The `>` operator (greater than)
718 pub fn to_string(&self) -> &'static str {
719 use self::BinOpKind::*;
741 pub fn lazy(&self) -> bool {
743 BinOpKind::And | BinOpKind::Or => true,
748 pub fn is_shift(&self) -> bool {
750 BinOpKind::Shl | BinOpKind::Shr => true,
755 pub fn is_comparison(&self) -> bool {
756 use self::BinOpKind::*;
758 Eq | Lt | Le | Ne | Gt | Ge =>
760 And | Or | Add | Sub | Mul | Div | Rem |
761 BitXor | BitAnd | BitOr | Shl | Shr =>
766 /// Returns `true` if the binary operator takes its arguments by value
767 pub fn is_by_value(&self) -> bool {
768 !self.is_comparison()
772 pub type BinOp = Spanned<BinOpKind>;
774 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
776 /// The `*` operator for dereferencing
778 /// The `!` operator for logical inversion
780 /// The `-` operator for negation
785 /// Returns `true` if the unary operator takes its argument by value
786 pub fn is_by_value(u: UnOp) -> bool {
788 UnOp::Neg | UnOp::Not => true,
793 pub fn to_string(op: UnOp) -> &'static str {
803 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
811 pub fn add_trailing_semicolon(mut self) -> Self {
812 self.node = match self.node {
813 StmtKind::Expr(expr) => StmtKind::Semi(expr),
814 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
815 (mac, MacStmtStyle::Semicolon, attrs)
822 pub fn is_item(&self) -> bool {
824 StmtKind::Item(_) => true,
829 pub fn is_expr(&self) -> bool {
831 StmtKind::Expr(_) => true,
837 impl fmt::Debug for Stmt {
838 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
839 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
844 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
846 /// A local (let) binding.
849 /// An item definition.
852 /// Expr without trailing semi-colon.
854 /// Expr with a trailing semi-colon.
857 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
860 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
861 pub enum MacStmtStyle {
862 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
863 /// `foo!(...);`, `foo![...];`
865 /// The macro statement had braces; e.g. foo! { ... }
867 /// The macro statement had parentheses or brackets and no semicolon; e.g.
868 /// `foo!(...)`. All of these will end up being converted into macro
873 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
874 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
877 pub ty: Option<P<Ty>>,
878 /// Initializer expression to set the value, if any
879 pub init: Option<P<Expr>>,
882 pub attrs: ThinVec<Attribute>,
885 /// An arm of a 'match'.
887 /// E.g. `0...10 => { println!("match!") }` as in
891 /// 0...10 => { println!("match!") },
892 /// _ => { println!("no match!") },
895 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
897 pub attrs: Vec<Attribute>,
898 pub pats: Vec<P<Pat>>,
899 pub guard: Option<P<Expr>>,
903 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
908 pub is_shorthand: bool,
909 pub attrs: ThinVec<Attribute>,
912 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
913 pub enum BlockCheckMode {
915 Unsafe(UnsafeSource),
918 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
919 pub enum UnsafeSource {
925 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
930 pub attrs: ThinVec<Attribute>
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<TyParamBound> {
960 ExprKind::Path(None, path) =>
961 Some(TraitTyParamBound(PolyTraitRef::new(Vec::new(), path.clone(), self.span),
962 TraitBoundModifier::None)),
967 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
968 let node = match &self.node {
969 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
970 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
971 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
972 ExprKind::AddrOf(mutbl, expr) =>
973 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
974 ExprKind::Repeat(expr, expr_len) =>
975 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?,
976 ExprKind::Array(exprs) if exprs.len() == 1 =>
977 exprs[0].to_ty().map(TyKind::Slice)?,
978 ExprKind::Tup(exprs) => {
979 let mut tys = Vec::new();
981 tys.push(expr.to_ty()?);
985 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add =>
986 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
987 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
994 Some(P(Ty { node, id: self.id, span: self.span }))
997 pub fn precedence(&self) -> ExprPrecedence {
999 ExprKind::Box(_) => ExprPrecedence::Box,
1000 ExprKind::Array(_) => ExprPrecedence::Array,
1001 ExprKind::Call(..) => ExprPrecedence::Call,
1002 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1003 ExprKind::Tup(_) => ExprPrecedence::Tup,
1004 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1005 ExprKind::Unary(..) => ExprPrecedence::Unary,
1006 ExprKind::Lit(_) => ExprPrecedence::Lit,
1007 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1008 ExprKind::If(..) => ExprPrecedence::If,
1009 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
1010 ExprKind::While(..) => ExprPrecedence::While,
1011 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
1012 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1013 ExprKind::Loop(..) => ExprPrecedence::Loop,
1014 ExprKind::Match(..) => ExprPrecedence::Match,
1015 ExprKind::Closure(..) => ExprPrecedence::Closure,
1016 ExprKind::Block(..) => ExprPrecedence::Block,
1017 ExprKind::Catch(..) => ExprPrecedence::Catch,
1018 ExprKind::Assign(..) => ExprPrecedence::Assign,
1019 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1020 ExprKind::Field(..) => ExprPrecedence::Field,
1021 ExprKind::Index(..) => ExprPrecedence::Index,
1022 ExprKind::Range(..) => ExprPrecedence::Range,
1023 ExprKind::Path(..) => ExprPrecedence::Path,
1024 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1025 ExprKind::Break(..) => ExprPrecedence::Break,
1026 ExprKind::Continue(..) => ExprPrecedence::Continue,
1027 ExprKind::Ret(..) => ExprPrecedence::Ret,
1028 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1029 ExprKind::Mac(..) => ExprPrecedence::Mac,
1030 ExprKind::Struct(..) => ExprPrecedence::Struct,
1031 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1032 ExprKind::Paren(..) => ExprPrecedence::Paren,
1033 ExprKind::Try(..) => ExprPrecedence::Try,
1034 ExprKind::Yield(..) => ExprPrecedence::Yield,
1039 impl fmt::Debug for Expr {
1040 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1041 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1045 /// Limit types of a range (inclusive or exclusive)
1046 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1047 pub enum RangeLimits {
1048 /// Inclusive at the beginning, exclusive at the end
1050 /// Inclusive at the beginning and end
1054 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1056 /// A `box x` expression.
1058 /// An array (`[a, b, c, d]`)
1059 Array(Vec<P<Expr>>),
1062 /// The first field resolves to the function itself,
1063 /// and the second field is the list of arguments.
1064 /// This also represents calling the constructor of
1065 /// tuple-like ADTs such as tuple structs and enum variants.
1066 Call(P<Expr>, Vec<P<Expr>>),
1067 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1069 /// The `PathSegment` represents the method name and its generic arguments
1070 /// (within the angle brackets).
1071 /// The first element of the vector of `Expr`s is the expression that evaluates
1072 /// to the object on which the method is being called on (the receiver),
1073 /// and the remaining elements are the rest of the arguments.
1074 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1075 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1076 MethodCall(PathSegment, Vec<P<Expr>>),
1077 /// A tuple (`(a, b, c ,d)`)
1079 /// A binary operation (For example: `a + b`, `a * b`)
1080 Binary(BinOp, P<Expr>, P<Expr>),
1081 /// A unary operation (For example: `!x`, `*x`)
1082 Unary(UnOp, P<Expr>),
1083 /// A literal (For example: `1`, `"foo"`)
1085 /// A cast (`foo as f64`)
1086 Cast(P<Expr>, P<Ty>),
1087 Type(P<Expr>, P<Ty>),
1088 /// An `if` block, with an optional else block
1090 /// `if expr { block } else { expr }`
1091 If(P<Expr>, P<Block>, Option<P<Expr>>),
1092 /// An `if let` expression with an optional else block
1094 /// `if let pat = expr { block } else { expr }`
1096 /// This is desugared to a `match` expression.
1097 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1098 /// A while loop, with an optional label
1100 /// `'label: while expr { block }`
1101 While(P<Expr>, P<Block>, Option<Label>),
1102 /// A while-let loop, with an optional label
1104 /// `'label: while let pat = expr { block }`
1106 /// This is desugared to a combination of `loop` and `match` expressions.
1107 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1108 /// A for loop, with an optional label
1110 /// `'label: for pat in expr { block }`
1112 /// This is desugared to a combination of `loop` and `match` expressions.
1113 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1114 /// Conditionless loop (can be exited with break, continue, or return)
1116 /// `'label: loop { block }`
1117 Loop(P<Block>, Option<Label>),
1118 /// A `match` block.
1119 Match(P<Expr>, Vec<Arm>),
1120 /// A closure (for example, `move |a, b, c| a + b + c`)
1122 /// The final span is the span of the argument block `|...|`
1123 Closure(CaptureBy, Movability, P<FnDecl>, P<Expr>, Span),
1124 /// A block (`{ ... }`)
1126 /// A catch block (`catch { ... }`)
1129 /// An assignment (`a = foo()`)
1130 Assign(P<Expr>, P<Expr>),
1131 /// An assignment with an operator
1133 /// For example, `a += 1`.
1134 AssignOp(BinOp, P<Expr>, P<Expr>),
1135 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct field
1136 Field(P<Expr>, Ident),
1137 /// An indexing operation (`foo[2]`)
1138 Index(P<Expr>, P<Expr>),
1139 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
1140 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1142 /// Variable reference, possibly containing `::` and/or type
1143 /// parameters, e.g. foo::bar::<baz>.
1145 /// Optionally "qualified",
1146 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
1147 Path(Option<QSelf>, Path),
1149 /// A referencing operation (`&a` or `&mut a`)
1150 AddrOf(Mutability, P<Expr>),
1151 /// A `break`, with an optional label to break, and an optional expression
1152 Break(Option<Label>, Option<P<Expr>>),
1153 /// A `continue`, with an optional label
1154 Continue(Option<Label>),
1155 /// A `return`, with an optional value to be returned
1156 Ret(Option<P<Expr>>),
1158 /// Output of the `asm!()` macro
1159 InlineAsm(P<InlineAsm>),
1161 /// A macro invocation; pre-expansion
1164 /// A struct literal expression.
1166 /// For example, `Foo {x: 1, y: 2}`, or
1167 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1168 Struct(Path, Vec<Field>, Option<P<Expr>>),
1170 /// An array literal constructed from one repeated element.
1172 /// For example, `[1; 5]`. The first expression is the element
1173 /// to be repeated; the second is the number of times to repeat it.
1174 Repeat(P<Expr>, P<Expr>),
1176 /// No-op: used solely so we can pretty-print faithfully
1182 /// A `yield`, with an optional value to be yielded
1183 Yield(Option<P<Expr>>),
1186 /// The explicit Self type in a "qualified path". The actual
1187 /// path, including the trait and the associated item, is stored
1188 /// separately. `position` represents the index of the associated
1189 /// item qualified with this Self type.
1191 /// ```ignore (only-for-syntax-highlight)
1192 /// <Vec<T> as a::b::Trait>::AssociatedItem
1193 /// ^~~~~ ~~~~~~~~~~~~~~^
1196 /// <Vec<T>>::AssociatedItem
1200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1206 /// A capture clause
1207 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1208 pub enum CaptureBy {
1213 /// The movability of a generator / closure literal
1214 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1215 pub enum Movability {
1220 pub type Mac = Spanned<Mac_>;
1222 /// Represents a macro invocation. The Path indicates which macro
1223 /// is being invoked, and the vector of token-trees contains the source
1224 /// of the macro invocation.
1226 /// NB: the additional ident for a macro_rules-style macro is actually
1227 /// stored in the enclosing item. Oog.
1228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1231 pub tts: ThinTokenStream,
1235 pub fn stream(&self) -> TokenStream {
1236 self.tts.clone().into()
1240 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1241 pub struct MacroDef {
1242 pub tokens: ThinTokenStream,
1247 pub fn stream(&self) -> TokenStream {
1248 self.tokens.clone().into()
1252 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1254 /// A regular string, like `"foo"`
1256 /// A raw string, like `r##"foo"##`
1258 /// The value is the number of `#` symbols used.
1263 pub type Lit = Spanned<LitKind>;
1265 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1266 pub enum LitIntType {
1274 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1275 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1277 /// A string literal (`"foo"`)
1278 Str(Symbol, StrStyle),
1279 /// A byte string (`b"foo"`)
1280 ByteStr(Lrc<Vec<u8>>),
1281 /// A byte char (`b'f'`)
1283 /// A character literal (`'a'`)
1285 /// An integer literal (`1`)
1286 Int(u128, LitIntType),
1287 /// A float literal (`1f64` or `1E10f64`)
1288 Float(Symbol, FloatTy),
1289 /// A float literal without a suffix (`1.0 or 1.0E10`)
1290 FloatUnsuffixed(Symbol),
1291 /// A boolean literal
1296 /// Returns true if this literal is a string and false otherwise.
1297 pub fn is_str(&self) -> bool {
1299 LitKind::Str(..) => true,
1304 /// Returns true if this literal has no suffix. Note: this will return true
1305 /// for literals with prefixes such as raw strings and byte strings.
1306 pub fn is_unsuffixed(&self) -> bool {
1308 // unsuffixed variants
1310 LitKind::ByteStr(..) |
1313 LitKind::Int(_, LitIntType::Unsuffixed) |
1314 LitKind::FloatUnsuffixed(..) |
1315 LitKind::Bool(..) => true,
1316 // suffixed variants
1317 LitKind::Int(_, LitIntType::Signed(..)) |
1318 LitKind::Int(_, LitIntType::Unsigned(..)) |
1319 LitKind::Float(..) => false,
1323 /// Returns true if this literal has a suffix.
1324 pub fn is_suffixed(&self) -> bool {
1325 !self.is_unsuffixed()
1329 // NB: If you change this, you'll probably want to change the corresponding
1330 // type structure in middle/ty.rs as well.
1331 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1334 pub mutbl: Mutability,
1337 /// Represents a method's signature in a trait declaration,
1338 /// or in an implementation.
1339 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1340 pub struct MethodSig {
1341 pub unsafety: Unsafety,
1342 pub constness: Spanned<Constness>,
1344 pub decl: P<FnDecl>,
1347 /// Represents an item declaration within a trait declaration,
1348 /// possibly including a default implementation. A trait item is
1349 /// either required (meaning it doesn't have an implementation, just a
1350 /// signature) or provided (meaning it has a default implementation).
1351 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1352 pub struct TraitItem {
1355 pub attrs: Vec<Attribute>,
1356 pub generics: Generics,
1357 pub node: TraitItemKind,
1359 /// See `Item::tokens` for what this is
1360 pub tokens: Option<TokenStream>,
1363 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1364 pub enum TraitItemKind {
1365 Const(P<Ty>, Option<P<Expr>>),
1366 Method(MethodSig, Option<P<Block>>),
1367 Type(TyParamBounds, Option<P<Ty>>),
1371 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1372 pub struct ImplItem {
1375 pub vis: Visibility,
1376 pub defaultness: Defaultness,
1377 pub attrs: Vec<Attribute>,
1378 pub generics: Generics,
1379 pub node: ImplItemKind,
1381 /// See `Item::tokens` for what this is
1382 pub tokens: Option<TokenStream>,
1385 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1386 pub enum ImplItemKind {
1387 Const(P<Ty>, P<Expr>),
1388 Method(MethodSig, P<Block>),
1393 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1404 impl fmt::Debug for IntTy {
1405 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1406 fmt::Display::fmt(self, f)
1410 impl fmt::Display for IntTy {
1411 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1412 write!(f, "{}", self.ty_to_string())
1417 pub fn ty_to_string(&self) -> &'static str {
1419 IntTy::Isize => "isize",
1421 IntTy::I16 => "i16",
1422 IntTy::I32 => "i32",
1423 IntTy::I64 => "i64",
1424 IntTy::I128 => "i128",
1428 pub fn val_to_string(&self, val: i128) -> String {
1429 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1430 // are parsed as u128, so we wouldn't want to print an extra negative
1432 format!("{}{}", val as u128, self.ty_to_string())
1435 pub fn bit_width(&self) -> Option<usize> {
1437 IntTy::Isize => return None,
1447 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1459 pub fn ty_to_string(&self) -> &'static str {
1461 UintTy::Usize => "usize",
1463 UintTy::U16 => "u16",
1464 UintTy::U32 => "u32",
1465 UintTy::U64 => "u64",
1466 UintTy::U128 => "u128",
1470 pub fn val_to_string(&self, val: u128) -> String {
1471 format!("{}{}", val, self.ty_to_string())
1474 pub fn bit_width(&self) -> Option<usize> {
1476 UintTy::Usize => return None,
1481 UintTy::U128 => 128,
1486 impl fmt::Debug for UintTy {
1487 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1488 fmt::Display::fmt(self, f)
1492 impl fmt::Display for UintTy {
1493 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1494 write!(f, "{}", self.ty_to_string())
1498 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1505 impl fmt::Debug for FloatTy {
1506 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1507 fmt::Display::fmt(self, f)
1511 impl fmt::Display for FloatTy {
1512 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1513 write!(f, "{}", self.ty_to_string())
1518 pub fn ty_to_string(&self) -> &'static str {
1520 FloatTy::F32 => "f32",
1521 FloatTy::F64 => "f64",
1525 pub fn bit_width(&self) -> usize {
1533 // Bind a type to an associated type: `A=Foo`.
1534 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1535 pub struct TypeBinding {
1542 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1549 impl fmt::Debug for Ty {
1550 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1551 write!(f, "type({})", pprust::ty_to_string(self))
1555 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1556 pub struct BareFnTy {
1557 pub unsafety: Unsafety,
1559 pub generic_params: Vec<GenericParam>,
1563 /// The different kinds of types recognized by the compiler
1564 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1566 /// A variable-length slice (`[T]`)
1568 /// A fixed length array (`[T; n]`)
1569 Array(P<Ty>, P<Expr>),
1570 /// A raw pointer (`*const T` or `*mut T`)
1572 /// A reference (`&'a T` or `&'a mut T`)
1573 Rptr(Option<Lifetime>, MutTy),
1574 /// A bare function (e.g. `fn(usize) -> bool`)
1575 BareFn(P<BareFnTy>),
1576 /// The never type (`!`)
1578 /// A tuple (`(A, B, C, D,...)`)
1580 /// A path (`module::module::...::Type`), optionally
1581 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1583 /// Type parameters are stored in the Path itself
1584 Path(Option<QSelf>, Path),
1585 /// A trait object type `Bound1 + Bound2 + Bound3`
1586 /// where `Bound` is a trait or a lifetime.
1587 TraitObject(TyParamBounds, TraitObjectSyntax),
1588 /// An `impl Bound1 + Bound2 + Bound3` type
1589 /// where `Bound` is a trait or a lifetime.
1590 ImplTrait(TyParamBounds),
1591 /// No-op; kept solely so that we can pretty-print faithfully
1595 /// TyKind::Infer means the type should be inferred instead of it having been
1596 /// specified. This can appear anywhere in a type.
1598 /// Inferred type of a `self` or `&self` argument in a method.
1600 // A macro in the type position.
1602 /// Placeholder for a kind that has failed to be defined.
1606 /// Syntax used to declare a trait object.
1607 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1608 pub enum TraitObjectSyntax {
1613 /// Inline assembly dialect.
1615 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1617 pub enum AsmDialect {
1622 /// Inline assembly.
1624 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1626 pub struct InlineAsmOutput {
1627 pub constraint: Symbol,
1630 pub is_indirect: bool,
1633 /// Inline assembly.
1635 /// E.g. `asm!("NOP");`
1636 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1637 pub struct InlineAsm {
1639 pub asm_str_style: StrStyle,
1640 pub outputs: Vec<InlineAsmOutput>,
1641 pub inputs: Vec<(Symbol, P<Expr>)>,
1642 pub clobbers: Vec<Symbol>,
1644 pub alignstack: bool,
1645 pub dialect: AsmDialect,
1646 pub ctxt: SyntaxContext,
1649 /// An argument in a function header.
1651 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1652 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1659 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1661 /// E.g. `&mut self` as in `fn foo(&mut self)`
1662 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1664 /// `self`, `mut self`
1666 /// `&'lt self`, `&'lt mut self`
1667 Region(Option<Lifetime>, Mutability),
1668 /// `self: TYPE`, `mut self: TYPE`
1669 Explicit(P<Ty>, Mutability),
1672 pub type ExplicitSelf = Spanned<SelfKind>;
1675 pub fn to_self(&self) -> Option<ExplicitSelf> {
1676 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1677 if ident.name == keywords::SelfValue.name() {
1678 return match self.ty.node {
1679 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1680 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1681 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1683 _ => Some(respan(self.pat.span.to(self.ty.span),
1684 SelfKind::Explicit(self.ty.clone(), mutbl))),
1691 pub fn is_self(&self) -> bool {
1692 if let PatKind::Ident(_, ident, _) = self.pat.node {
1693 ident.name == keywords::SelfValue.name()
1699 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1700 let span = eself.span.to(eself_ident.span);
1701 let infer_ty = P(Ty {
1703 node: TyKind::ImplicitSelf,
1706 let arg = |mutbl, ty| Arg {
1709 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1716 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1717 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1718 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1720 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1727 /// Header (not the body) of a function declaration.
1729 /// E.g. `fn foo(bar: baz)`
1730 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1732 pub inputs: Vec<Arg>,
1733 pub output: FunctionRetTy,
1738 pub fn get_self(&self) -> Option<ExplicitSelf> {
1739 self.inputs.get(0).and_then(Arg::to_self)
1741 pub fn has_self(&self) -> bool {
1742 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1746 /// Is the trait definition an auto trait?
1747 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1753 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1759 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1760 pub enum Constness {
1765 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1766 pub enum Defaultness {
1771 impl fmt::Display for Unsafety {
1772 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1773 fmt::Display::fmt(match *self {
1774 Unsafety::Normal => "normal",
1775 Unsafety::Unsafe => "unsafe",
1780 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1781 pub enum ImplPolarity {
1782 /// `impl Trait for Type`
1784 /// `impl !Trait for Type`
1788 impl fmt::Debug for ImplPolarity {
1789 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1791 ImplPolarity::Positive => "positive".fmt(f),
1792 ImplPolarity::Negative => "negative".fmt(f),
1798 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1799 pub enum FunctionRetTy {
1800 /// Return type is not specified.
1802 /// Functions default to `()` and
1803 /// closures default to inference. Span points to where return
1804 /// type would be inserted.
1810 impl FunctionRetTy {
1811 pub fn span(&self) -> Span {
1813 FunctionRetTy::Default(span) => span,
1814 FunctionRetTy::Ty(ref ty) => ty.span,
1819 /// Module declaration.
1821 /// E.g. `mod foo;` or `mod foo { .. }`
1822 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1824 /// A span from the first token past `{` to the last token until `}`.
1825 /// For `mod foo;`, the inner span ranges from the first token
1826 /// to the last token in the external file.
1828 pub items: Vec<P<Item>>,
1831 /// Foreign module declaration.
1833 /// E.g. `extern { .. }` or `extern C { .. }`
1834 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1835 pub struct ForeignMod {
1837 pub items: Vec<ForeignItem>,
1840 /// Global inline assembly
1842 /// aka module-level assembly or file-scoped assembly
1843 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1844 pub struct GlobalAsm {
1846 pub ctxt: SyntaxContext,
1849 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1850 pub struct EnumDef {
1851 pub variants: Vec<Variant>,
1854 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1855 pub struct Variant_ {
1857 pub attrs: Vec<Attribute>,
1858 pub data: VariantData,
1859 /// Explicit discriminant, e.g. `Foo = 1`
1860 pub disr_expr: Option<P<Expr>>,
1863 pub type Variant = Spanned<Variant_>;
1865 /// Part of `use` item to the right of its prefix.
1866 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1867 pub enum UseTreeKind {
1868 /// `use prefix` or `use prefix as rename`
1869 Simple(Option<Ident>),
1870 /// `use prefix::{...}`
1871 Nested(Vec<(UseTree, NodeId)>),
1876 /// A tree of paths sharing common prefixes.
1877 /// Used in `use` items both at top-level and inside of braces in import groups.
1878 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1879 pub struct UseTree {
1881 pub kind: UseTreeKind,
1886 pub fn ident(&self) -> Ident {
1888 UseTreeKind::Simple(Some(rename)) => rename,
1889 UseTreeKind::Simple(None) =>
1890 self.prefix.segments.last().expect("empty prefix in a simple import").ident,
1891 _ => panic!("`UseTree::ident` can only be used on a simple import"),
1896 /// Distinguishes between Attributes that decorate items and Attributes that
1897 /// are contained as statements within items. These two cases need to be
1898 /// distinguished for pretty-printing.
1899 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1900 pub enum AttrStyle {
1905 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1906 pub struct AttrId(pub usize);
1908 /// Meta-data associated with an item
1909 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1910 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1911 pub struct Attribute {
1913 pub style: AttrStyle,
1915 pub tokens: TokenStream,
1916 pub is_sugared_doc: bool,
1920 /// TraitRef's appear in impls.
1922 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1923 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1924 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1925 /// same as the impl's node id).
1926 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1927 pub struct TraitRef {
1932 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1933 pub struct PolyTraitRef {
1934 /// The `'a` in `<'a> Foo<&'a T>`
1935 pub bound_generic_params: Vec<GenericParam>,
1937 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1938 pub trait_ref: TraitRef,
1944 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
1946 bound_generic_params: generic_params,
1947 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1953 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1954 pub enum CrateSugar {
1955 /// Source is `pub(crate)`
1958 /// Source is (just) `crate`
1962 pub type Visibility = Spanned<VisibilityKind>;
1964 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1965 pub enum VisibilityKind {
1968 Restricted { path: P<Path>, id: NodeId },
1972 /// Field of a struct.
1974 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1975 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1976 pub struct StructField {
1978 pub ident: Option<Ident>,
1979 pub vis: Visibility,
1982 pub attrs: Vec<Attribute>,
1985 /// Fields and Ids of enum variants and structs
1987 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1988 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1989 /// One shared Id can be successfully used for these two purposes.
1990 /// Id of the whole enum lives in `Item`.
1992 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1993 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1994 /// the variant itself" from enum variants.
1995 /// Id of the whole struct lives in `Item`.
1996 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1997 pub enum VariantData {
2000 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
2001 Struct(Vec<StructField>, NodeId),
2004 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
2005 Tuple(Vec<StructField>, NodeId),
2008 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
2013 pub fn fields(&self) -> &[StructField] {
2015 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2019 pub fn id(&self) -> NodeId {
2021 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
2024 pub fn is_struct(&self) -> bool {
2025 if let VariantData::Struct(..) = *self { true } else { false }
2027 pub fn is_tuple(&self) -> bool {
2028 if let VariantData::Tuple(..) = *self { true } else { false }
2030 pub fn is_unit(&self) -> bool {
2031 if let VariantData::Unit(..) = *self { true } else { false }
2037 /// The name might be a dummy name in case of anonymous items
2038 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2041 pub attrs: Vec<Attribute>,
2044 pub vis: Visibility,
2047 /// Original tokens this item was parsed from. This isn't necessarily
2048 /// available for all items, although over time more and more items should
2049 /// have this be `Some`. Right now this is primarily used for procedural
2050 /// macros, notably custom attributes.
2052 /// Note that the tokens here do not include the outer attributes, but will
2053 /// include inner attributes.
2054 pub tokens: Option<TokenStream>,
2057 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2059 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2061 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2062 ExternCrate(Option<Name>),
2063 /// A use declaration (`use` or `pub use`) item.
2065 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
2067 /// A static item (`static` or `pub static`).
2069 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
2070 Static(P<Ty>, Mutability, P<Expr>),
2071 /// A constant item (`const` or `pub const`).
2073 /// E.g. `const FOO: i32 = 42;`
2074 Const(P<Ty>, P<Expr>),
2075 /// A function declaration (`fn` or `pub fn`).
2077 /// E.g. `fn foo(bar: usize) -> usize { .. }`
2078 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
2079 /// A module declaration (`mod` or `pub mod`).
2081 /// E.g. `mod foo;` or `mod foo { .. }`
2083 /// An external module (`extern` or `pub extern`).
2085 /// E.g. `extern {}` or `extern "C" {}`
2086 ForeignMod(ForeignMod),
2087 /// Module-level inline assembly (from `global_asm!()`)
2088 GlobalAsm(P<GlobalAsm>),
2089 /// A type alias (`type` or `pub type`).
2091 /// E.g. `type Foo = Bar<u8>;`
2092 Ty(P<Ty>, Generics),
2093 /// An enum definition (`enum` or `pub enum`).
2095 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
2096 Enum(EnumDef, Generics),
2097 /// A struct definition (`struct` or `pub struct`).
2099 /// E.g. `struct Foo<A> { x: A }`
2100 Struct(VariantData, Generics),
2101 /// A union definition (`union` or `pub union`).
2103 /// E.g. `union Foo<A, B> { x: A, y: B }`
2104 Union(VariantData, Generics),
2105 /// A Trait declaration (`trait` or `pub trait`).
2107 /// E.g. `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`
2108 Trait(IsAuto, Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
2111 /// E.g. `trait Foo = Bar + Quux;`
2112 TraitAlias(Generics, TyParamBounds),
2113 /// An implementation.
2115 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
2120 Option<TraitRef>, // (optional) trait this impl implements
2123 /// A macro invocation.
2125 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
2128 /// A macro definition.
2133 pub fn descriptive_variant(&self) -> &str {
2135 ItemKind::ExternCrate(..) => "extern crate",
2136 ItemKind::Use(..) => "use",
2137 ItemKind::Static(..) => "static item",
2138 ItemKind::Const(..) => "constant item",
2139 ItemKind::Fn(..) => "function",
2140 ItemKind::Mod(..) => "module",
2141 ItemKind::ForeignMod(..) => "foreign module",
2142 ItemKind::GlobalAsm(..) => "global asm",
2143 ItemKind::Ty(..) => "type alias",
2144 ItemKind::Enum(..) => "enum",
2145 ItemKind::Struct(..) => "struct",
2146 ItemKind::Union(..) => "union",
2147 ItemKind::Trait(..) => "trait",
2148 ItemKind::TraitAlias(..) => "trait alias",
2150 ItemKind::MacroDef(..) |
2151 ItemKind::Impl(..) => "item"
2156 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2157 pub struct ForeignItem {
2159 pub attrs: Vec<Attribute>,
2160 pub node: ForeignItemKind,
2163 pub vis: Visibility,
2166 /// An item within an `extern` block
2167 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2168 pub enum ForeignItemKind {
2169 /// A foreign function
2170 Fn(P<FnDecl>, Generics),
2171 /// A foreign static item (`static ext: u8`), with optional mutability
2172 /// (the boolean is true when mutable)
2173 Static(P<Ty>, bool),
2176 /// A macro invocation
2180 impl ForeignItemKind {
2181 pub fn descriptive_variant(&self) -> &str {
2183 ForeignItemKind::Fn(..) => "foreign function",
2184 ForeignItemKind::Static(..) => "foreign static item",
2185 ForeignItemKind::Ty => "foreign type",
2186 ForeignItemKind::Macro(..) => "macro in foreign module",
2196 // are ASTs encodable?
2198 fn check_asts_encodable() {
2199 fn assert_encodable<T: serialize::Encodable>() {}
2200 assert_encodable::<Crate>();