1 // The Rust abstract syntax tree.
3 pub use GenericArgs::*;
4 pub use UnsafeSource::*;
5 pub use crate::symbol::{Ident, Symbol as Name};
6 pub use crate::util::parser::ExprPrecedence;
8 use crate::ext::hygiene::{Mark, SyntaxContext};
9 use crate::print::pprust;
11 use crate::source_map::{dummy_spanned, respan, Spanned};
12 use crate::symbol::{keywords, Symbol};
13 use crate::tokenstream::TokenStream;
16 use rustc_data_structures::indexed_vec::Idx;
17 #[cfg(target_arch = "x86_64")]
18 use rustc_data_structures::static_assert;
19 use rustc_target::spec::abi::Abi;
20 use syntax_pos::{Span, DUMMY_SP};
22 use rustc_data_structures::fx::FxHashSet;
23 use rustc_data_structures::sync::Lrc;
24 use serialize::{self, Decoder, Encoder};
27 pub use rustc_target::abi::FloatTy;
29 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
34 impl fmt::Debug for Label {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 write!(f, "label({:?})", self.ident)
40 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
46 impl fmt::Debug for Lifetime {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 pprust::lifetime_to_string(self)
57 /// A "Path" is essentially Rust's notion of a name.
59 /// It's represented as a sequence of identifiers,
60 /// along with a bunch of supporting information.
62 /// E.g., `std::cmp::PartialEq`.
63 #[derive(Clone, RustcEncodable, RustcDecodable)]
66 /// The segments in the path: the things separated by `::`.
67 /// Global paths begin with `keywords::PathRoot`.
68 pub segments: Vec<PathSegment>,
71 impl<'a> PartialEq<&'a str> for Path {
72 fn eq(&self, string: &&'a str) -> bool {
73 self.segments.len() == 1 && self.segments[0].ident.name == *string
77 impl fmt::Debug for Path {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 write!(f, "path({})", pprust::path_to_string(self))
83 impl fmt::Display for Path {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 write!(f, "{}", pprust::path_to_string(self))
90 // Convert a span and an identifier to the corresponding
92 pub fn from_ident(ident: Ident) -> Path {
94 segments: vec![PathSegment::from_ident(ident)],
99 pub fn is_global(&self) -> bool {
100 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
104 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
106 /// E.g., `std`, `String` or `Box<T>`.
107 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
108 pub struct PathSegment {
109 /// The identifier portion of this path segment.
114 /// Type/lifetime parameters attached to this path. They come in
115 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
116 /// `None` means that no parameter list is supplied (`Path`),
117 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
118 /// but it can be empty (`Path<>`).
119 /// `P` is used as a size optimization for the common case with no parameters.
120 pub args: Option<P<GenericArgs>>,
124 pub fn from_ident(ident: Ident) -> Self {
125 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
127 pub fn path_root(span: Span) -> Self {
128 PathSegment::from_ident(Ident::new(keywords::PathRoot.name(), span))
132 /// The arguments of a path segment.
134 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
135 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
136 pub enum GenericArgs {
137 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
138 AngleBracketed(AngleBracketedArgs),
139 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
140 Parenthesized(ParenthesizedArgs),
144 pub fn is_parenthesized(&self) -> bool {
146 Parenthesized(..) => true,
151 pub fn is_angle_bracketed(&self) -> bool {
153 AngleBracketed(..) => true,
158 pub fn span(&self) -> Span {
160 AngleBracketed(ref data) => data.span,
161 Parenthesized(ref data) => data.span,
166 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
167 pub enum GenericArg {
174 pub fn span(&self) -> Span {
176 GenericArg::Lifetime(lt) => lt.ident.span,
177 GenericArg::Type(ty) => ty.span,
178 GenericArg::Const(ct) => ct.value.span,
183 /// A path like `Foo<'a, T>`.
184 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
185 pub struct AngleBracketedArgs {
186 /// The overall span.
188 /// The arguments for this path segment.
189 pub args: Vec<GenericArg>,
190 /// Bindings (equality constraints) on associated types, if present.
191 /// E.g., `Foo<A = Bar>`.
192 pub bindings: Vec<TypeBinding>,
195 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
196 fn into(self) -> Option<P<GenericArgs>> {
197 Some(P(GenericArgs::AngleBracketed(self)))
201 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
202 fn into(self) -> Option<P<GenericArgs>> {
203 Some(P(GenericArgs::Parenthesized(self)))
207 /// A path like `Foo(A, B) -> C`.
208 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
209 pub struct ParenthesizedArgs {
214 pub inputs: Vec<P<Ty>>,
217 pub output: Option<P<Ty>>,
220 impl ParenthesizedArgs {
221 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
224 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
230 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
232 use rustc_data_structures::indexed_vec::Idx;
233 use rustc_data_structures::newtype_index;
237 DEBUG_FORMAT = "NodeId({})"
242 pub use node_id_inner::NodeId;
245 pub fn placeholder_from_mark(mark: Mark) -> Self {
246 NodeId::from_u32(mark.as_u32())
249 pub fn placeholder_to_mark(self) -> Mark {
250 Mark::from_u32(self.as_u32())
254 impl fmt::Display for NodeId {
255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256 fmt::Display::fmt(&self.as_u32(), f)
260 impl serialize::UseSpecializedEncodable for NodeId {
261 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
262 s.emit_u32(self.as_u32())
266 impl serialize::UseSpecializedDecodable for NodeId {
267 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
268 d.read_u32().map(NodeId::from_u32)
272 /// `NodeId` used to represent the root of the crate.
273 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
275 /// When parsing and doing expansions, we initially give all AST nodes this AST
276 /// node value. Then later, in the renumber pass, we renumber them to have
277 /// small, positive ids.
278 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
280 /// A modifier on a bound, currently this is only used for `?Sized`, where the
281 /// modifier is `Maybe`. Negative bounds should also be handled here.
282 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
283 pub enum TraitBoundModifier {
288 /// The AST represents all type param bounds as types.
289 /// `typeck::collect::compute_bounds` matches these against
290 /// the "special" built-in traits (see `middle::lang_items`) and
291 /// detects `Copy`, `Send` and `Sync`.
292 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
293 pub enum GenericBound {
294 Trait(PolyTraitRef, TraitBoundModifier),
299 pub fn span(&self) -> Span {
301 &GenericBound::Trait(ref t, ..) => t.span,
302 &GenericBound::Outlives(ref l) => l.ident.span,
307 pub type GenericBounds = Vec<GenericBound>;
309 /// Specifies the enforced ordering for generic parameters. In the future,
310 /// if we wanted to relax this order, we could override `PartialEq` and
311 /// `PartialOrd`, to allow the kinds to be unordered.
312 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
313 pub enum ParamKindOrd {
319 impl fmt::Display for ParamKindOrd {
320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 ParamKindOrd::Lifetime => "lifetime".fmt(f),
323 ParamKindOrd::Type => "type".fmt(f),
324 ParamKindOrd::Const => "const".fmt(f),
329 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
330 pub enum GenericParamKind {
331 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
333 Type { default: Option<P<Ty>> },
337 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
338 pub struct GenericParam {
341 pub attrs: ThinVec<Attribute>,
342 pub bounds: GenericBounds,
344 pub kind: GenericParamKind,
347 /// Represents lifetime, type and const parameters attached to a declaration of
348 /// a function, enum, trait, etc.
349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
350 pub struct Generics {
351 pub params: Vec<GenericParam>,
352 pub where_clause: WhereClause,
356 impl Default for Generics {
357 /// Creates an instance of `Generics`.
358 fn default() -> Generics {
361 where_clause: WhereClause {
363 predicates: Vec::new(),
371 /// A where-clause in a definition.
372 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
373 pub struct WhereClause {
375 pub predicates: Vec<WherePredicate>,
379 /// A single predicate in a where-clause.
380 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
381 pub enum WherePredicate {
382 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
383 BoundPredicate(WhereBoundPredicate),
384 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
385 RegionPredicate(WhereRegionPredicate),
386 /// An equality predicate (unsupported).
387 EqPredicate(WhereEqPredicate),
390 impl WherePredicate {
391 pub fn span(&self) -> Span {
393 &WherePredicate::BoundPredicate(ref p) => p.span,
394 &WherePredicate::RegionPredicate(ref p) => p.span,
395 &WherePredicate::EqPredicate(ref p) => p.span,
402 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
403 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
404 pub struct WhereBoundPredicate {
406 /// Any generics from a `for` binding
407 pub bound_generic_params: Vec<GenericParam>,
408 /// The type being bounded
409 pub bounded_ty: P<Ty>,
410 /// Trait and lifetime bounds (`Clone+Send+'static`)
411 pub bounds: GenericBounds,
414 /// A lifetime predicate.
416 /// E.g., `'a: 'b + 'c`.
417 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
418 pub struct WhereRegionPredicate {
420 pub lifetime: Lifetime,
421 pub bounds: GenericBounds,
424 /// An equality predicate (unsupported).
427 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
428 pub struct WhereEqPredicate {
435 /// The set of `MetaItem`s that define the compilation environment of the crate,
436 /// used to drive conditional compilation.
437 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
439 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
442 pub attrs: Vec<Attribute>,
446 /// Possible values inside of compile-time attribute lists.
448 /// E.g., the '..' in `#[name(..)]`.
449 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
450 pub enum NestedMetaItem {
451 /// A full MetaItem, for recursive meta items.
455 /// E.g., `"foo"`, `64`, `true`.
459 /// A spanned compile-time attribute item.
461 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
462 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
463 pub struct MetaItem {
465 pub node: MetaItemKind,
469 /// A compile-time attribute item.
471 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
472 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
473 pub enum MetaItemKind {
476 /// E.g., `test` as in `#[test]`.
480 /// E.g., `derive(..)` as in `#[derive(..)]`.
481 List(Vec<NestedMetaItem>),
482 /// Name value meta item.
484 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
488 /// A Block (`{ .. }`).
490 /// E.g., `{ .. }` as in `fn foo() { .. }`.
491 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
493 /// Statements in a block
494 pub stmts: Vec<Stmt>,
496 /// Distinguishes between `unsafe { ... }` and `{ ... }`
497 pub rules: BlockCheckMode,
501 #[derive(Clone, RustcEncodable, RustcDecodable)]
508 impl fmt::Debug for Pat {
509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
515 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
516 let node = match &self.node {
517 PatKind::Wild => TyKind::Infer,
518 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
519 TyKind::Path(None, Path::from_ident(*ident))
521 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
522 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
523 PatKind::Ref(pat, mutbl) => pat
525 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
526 PatKind::Slice(pats, None, _) if pats.len() == 1 => {
527 pats[0].to_ty().map(TyKind::Slice)?
529 PatKind::Tuple(pats, None) => {
530 let mut tys = Vec::with_capacity(pats.len());
531 // FIXME(#48994) - could just be collected into an Option<Vec>
533 tys.push(pat.to_ty()?);
547 pub fn walk<F>(&self, it: &mut F) -> bool
549 F: FnMut(&Pat) -> bool,
556 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
557 PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
558 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
559 s.iter().all(|p| p.walk(it))
561 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
562 PatKind::Slice(ref before, ref slice, ref after) => {
563 before.iter().all(|p| p.walk(it))
564 && slice.iter().all(|p| p.walk(it))
565 && after.iter().all(|p| p.walk(it))
572 | PatKind::Mac(_) => true,
577 /// A single field in a struct pattern
579 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
580 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
581 /// except is_shorthand is true
582 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
583 pub struct FieldPat {
584 /// The identifier for the field
586 /// The pattern the field is destructured to
588 pub is_shorthand: bool,
589 pub attrs: ThinVec<Attribute>,
592 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
593 pub enum BindingMode {
598 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
600 Included(RangeSyntax),
604 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
605 pub enum RangeSyntax {
610 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
612 /// Represents a wildcard pattern (`_`).
615 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
616 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
617 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
618 /// during name resolution.
619 Ident(BindingMode, Ident, Option<P<Pat>>),
621 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
622 /// The `bool` is `true` in the presence of a `..`.
623 Struct(Path, Vec<Spanned<FieldPat>>, /* recovered */ bool),
625 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
626 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
627 /// `0 <= position <= subpats.len()`.
628 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
630 /// A possibly qualified path pattern.
631 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
632 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
633 /// only legally refer to associated constants.
634 Path(Option<QSelf>, Path),
636 /// A tuple pattern (`(a, b)`).
637 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
638 /// `0 <= position <= subpats.len()`.
639 Tuple(Vec<P<Pat>>, Option<usize>),
644 /// A reference pattern (e.g., `&mut (a, b)`).
645 Ref(P<Pat>, Mutability),
650 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
651 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
653 /// `[a, b, ..i, y, z]` is represented as:
654 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
655 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
657 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
660 /// A macro pattern; pre-expansion.
665 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
667 pub enum Mutability {
672 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
674 /// The `+` operator (addition)
676 /// The `-` operator (subtraction)
678 /// The `*` operator (multiplication)
680 /// The `/` operator (division)
682 /// The `%` operator (modulus)
684 /// The `&&` operator (logical and)
686 /// The `||` operator (logical or)
688 /// The `^` operator (bitwise xor)
690 /// The `&` operator (bitwise and)
692 /// The `|` operator (bitwise or)
694 /// The `<<` operator (shift left)
696 /// The `>>` operator (shift right)
698 /// The `==` operator (equality)
700 /// The `<` operator (less than)
702 /// The `<=` operator (less than or equal to)
704 /// The `!=` operator (not equal to)
706 /// The `>=` operator (greater than or equal to)
708 /// The `>` operator (greater than)
713 pub fn to_string(&self) -> &'static str {
736 pub fn lazy(&self) -> bool {
738 BinOpKind::And | BinOpKind::Or => true,
743 pub fn is_shift(&self) -> bool {
745 BinOpKind::Shl | BinOpKind::Shr => true,
750 pub fn is_comparison(&self) -> bool {
753 Eq | Lt | Le | Ne | Gt | Ge => true,
754 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
758 /// Returns `true` if the binary operator takes its arguments by value
759 pub fn is_by_value(&self) -> bool {
760 !self.is_comparison()
764 pub type BinOp = Spanned<BinOpKind>;
766 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
768 /// The `*` operator for dereferencing
770 /// The `!` operator for logical inversion
772 /// The `-` operator for negation
777 /// Returns `true` if the unary operator takes its argument by value
778 pub fn is_by_value(u: UnOp) -> bool {
780 UnOp::Neg | UnOp::Not => true,
785 pub fn to_string(op: UnOp) -> &'static str {
795 #[derive(Clone, RustcEncodable, RustcDecodable)]
803 pub fn add_trailing_semicolon(mut self) -> Self {
804 self.node = match self.node {
805 StmtKind::Expr(expr) => StmtKind::Semi(expr),
806 StmtKind::Mac(mac) => {
807 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
814 pub fn is_item(&self) -> bool {
816 StmtKind::Item(_) => true,
821 pub fn is_expr(&self) -> bool {
823 StmtKind::Expr(_) => true,
829 impl fmt::Debug for Stmt {
830 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
835 pprust::stmt_to_string(self)
840 #[derive(Clone, RustcEncodable, RustcDecodable)]
842 /// A local (let) binding.
845 /// An item definition.
848 /// Expr without trailing semi-colon.
850 /// Expr with a trailing semi-colon.
853 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
856 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
857 pub enum MacStmtStyle {
858 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
859 /// `foo!(...);`, `foo![...];`).
861 /// The macro statement had braces (e.g., `foo! { ... }`).
863 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
864 /// `foo!(...)`). All of these will end up being converted into macro
869 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
870 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
873 pub ty: Option<P<Ty>>,
874 /// Initializer expression to set the value, if any.
875 pub init: Option<P<Expr>>,
878 pub attrs: ThinVec<Attribute>,
881 /// An arm of a 'match'.
883 /// E.g., `0..=10 => { println!("match!") }` as in
887 /// 0..=10 => { println!("match!") },
888 /// _ => { println!("no match!") },
891 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
893 pub attrs: Vec<Attribute>,
894 pub pats: Vec<P<Pat>>,
895 pub guard: Option<Guard>,
899 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
904 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
909 pub is_shorthand: bool,
910 pub attrs: ThinVec<Attribute>,
913 pub type SpannedIdent = Spanned<Ident>;
915 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
916 pub enum BlockCheckMode {
918 Unsafe(UnsafeSource),
921 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
922 pub enum UnsafeSource {
927 /// A constant (expression) that's not an item or associated item,
928 /// but needs its own `DefId` for type-checking, const-eval, etc.
929 /// These are usually found nested inside types (e.g., array lengths)
930 /// or expressions (e.g., repeat counts), and also used to define
931 /// explicit discriminant values for enum variants.
932 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
933 pub struct AnonConst {
939 #[derive(Clone, RustcEncodable, RustcDecodable)]
944 pub attrs: ThinVec<Attribute>,
947 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
948 #[cfg(target_arch = "x86_64")]
949 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 88);
952 /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
954 pub fn returns(&self) -> bool {
955 if let ExprKind::Block(ref block, _) = self.node {
956 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
958 Some(&StmtKind::Expr(_)) => true,
959 Some(&StmtKind::Semi(ref expr)) => {
960 if let ExprKind::Ret(_) = expr.node {
961 // last statement is explicit return
967 // This is a block that doesn't end in either an implicit or explicit return
971 // This is not a block, it is a value
976 fn to_bound(&self) -> Option<GenericBound> {
978 ExprKind::Path(None, path) => Some(GenericBound::Trait(
979 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
980 TraitBoundModifier::None,
986 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
987 let node = match &self.node {
988 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
989 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
990 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
991 ExprKind::AddrOf(mutbl, expr) => expr
993 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
994 ExprKind::Repeat(expr, expr_len) => {
995 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
997 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
998 ExprKind::Tup(exprs) => {
1001 .map(|expr| expr.to_ty())
1002 .collect::<Option<Vec<_>>>()?;
1005 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1006 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1007 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1022 pub fn precedence(&self) -> ExprPrecedence {
1024 ExprKind::Box(_) => ExprPrecedence::Box,
1025 ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
1026 ExprKind::Array(_) => ExprPrecedence::Array,
1027 ExprKind::Call(..) => ExprPrecedence::Call,
1028 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1029 ExprKind::Tup(_) => ExprPrecedence::Tup,
1030 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1031 ExprKind::Unary(..) => ExprPrecedence::Unary,
1032 ExprKind::Lit(_) => ExprPrecedence::Lit,
1033 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1034 ExprKind::If(..) => ExprPrecedence::If,
1035 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
1036 ExprKind::While(..) => ExprPrecedence::While,
1037 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
1038 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1039 ExprKind::Loop(..) => ExprPrecedence::Loop,
1040 ExprKind::Match(..) => ExprPrecedence::Match,
1041 ExprKind::Closure(..) => ExprPrecedence::Closure,
1042 ExprKind::Block(..) => ExprPrecedence::Block,
1043 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1044 ExprKind::Async(..) => ExprPrecedence::Async,
1045 ExprKind::Assign(..) => ExprPrecedence::Assign,
1046 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1047 ExprKind::Field(..) => ExprPrecedence::Field,
1048 ExprKind::Index(..) => ExprPrecedence::Index,
1049 ExprKind::Range(..) => ExprPrecedence::Range,
1050 ExprKind::Path(..) => ExprPrecedence::Path,
1051 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1052 ExprKind::Break(..) => ExprPrecedence::Break,
1053 ExprKind::Continue(..) => ExprPrecedence::Continue,
1054 ExprKind::Ret(..) => ExprPrecedence::Ret,
1055 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1056 ExprKind::Mac(..) => ExprPrecedence::Mac,
1057 ExprKind::Struct(..) => ExprPrecedence::Struct,
1058 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1059 ExprKind::Paren(..) => ExprPrecedence::Paren,
1060 ExprKind::Try(..) => ExprPrecedence::Try,
1061 ExprKind::Yield(..) => ExprPrecedence::Yield,
1062 ExprKind::Err => ExprPrecedence::Err,
1067 impl fmt::Debug for Expr {
1068 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1069 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1073 /// Limit types of a range (inclusive or exclusive)
1074 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1075 pub enum RangeLimits {
1076 /// Inclusive at the beginning, exclusive at the end
1078 /// Inclusive at the beginning and end
1082 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1084 /// A `box x` expression.
1086 /// First expr is the place; second expr is the value.
1087 ObsoleteInPlace(P<Expr>, P<Expr>),
1088 /// An array (`[a, b, c, d]`)
1089 Array(Vec<P<Expr>>),
1092 /// The first field resolves to the function itself,
1093 /// and the second field is the list of arguments.
1094 /// This also represents calling the constructor of
1095 /// tuple-like ADTs such as tuple structs and enum variants.
1096 Call(P<Expr>, Vec<P<Expr>>),
1097 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1099 /// The `PathSegment` represents the method name and its generic arguments
1100 /// (within the angle brackets).
1101 /// The first element of the vector of an `Expr` is the expression that evaluates
1102 /// to the object on which the method is being called on (the receiver),
1103 /// and the remaining elements are the rest of the arguments.
1104 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1105 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1106 MethodCall(PathSegment, Vec<P<Expr>>),
1107 /// A tuple (e.g., `(a, b, c, d)`).
1109 /// A binary operation (e.g., `a + b`, `a * b`).
1110 Binary(BinOp, P<Expr>, P<Expr>),
1111 /// A unary operation (e.g., `!x`, `*x`).
1112 Unary(UnOp, P<Expr>),
1113 /// A literal (e.g., `1`, `"foo"`).
1115 /// A cast (e.g., `foo as f64`).
1116 Cast(P<Expr>, P<Ty>),
1117 Type(P<Expr>, P<Ty>),
1118 /// An `if` block, with an optional `else` block.
1120 /// `if expr { block } else { expr }`
1121 If(P<Expr>, P<Block>, Option<P<Expr>>),
1122 /// An `if let` expression with an optional else block
1124 /// `if let pat = expr { block } else { expr }`
1126 /// This is desugared to a `match` expression.
1127 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1128 /// A while loop, with an optional label
1130 /// `'label: while expr { block }`
1131 While(P<Expr>, P<Block>, Option<Label>),
1132 /// A `while let` loop, with an optional label.
1134 /// `'label: while let pat = expr { block }`
1136 /// This is desugared to a combination of `loop` and `match` expressions.
1137 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1138 /// A `for` loop, with an optional label.
1140 /// `'label: for pat in expr { block }`
1142 /// This is desugared to a combination of `loop` and `match` expressions.
1143 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1144 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1146 /// `'label: loop { block }`
1147 Loop(P<Block>, Option<Label>),
1148 /// A `match` block.
1149 Match(P<Expr>, Vec<Arm>),
1150 /// A closure (e.g., `move |a, b, c| a + b + c`).
1152 /// The final span is the span of the argument block `|...|`.
1153 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1154 /// A block (`'label: { ... }`).
1155 Block(P<Block>, Option<Label>),
1156 /// An async block (`async move { ... }`).
1158 /// The `NodeId` is the `NodeId` for the closure that results from
1159 /// desugaring an async block, just like the NodeId field in the
1160 /// `IsAsync` enum. This is necessary in order to create a def for the
1161 /// closure which can be used as a parent of any child defs. Defs
1162 /// created during lowering cannot be made the parent of any other
1163 /// preexisting defs.
1164 Async(CaptureBy, NodeId, P<Block>),
1165 /// A try block (`try { ... }`).
1168 /// An assignment (`a = foo()`).
1169 Assign(P<Expr>, P<Expr>),
1170 /// An assignment with an operator.
1173 AssignOp(BinOp, P<Expr>, P<Expr>),
1174 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1175 Field(P<Expr>, Ident),
1176 /// An indexing operation (e.g., `foo[2]`).
1177 Index(P<Expr>, P<Expr>),
1178 /// A range (e.g., `1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`).
1179 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1181 /// Variable reference, possibly containing `::` and/or type
1182 /// parameters (e.g., `foo::bar::<baz>`).
1184 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1185 Path(Option<QSelf>, Path),
1187 /// A referencing operation (`&a` or `&mut a`).
1188 AddrOf(Mutability, P<Expr>),
1189 /// A `break`, with an optional label to break, and an optional expression.
1190 Break(Option<Label>, Option<P<Expr>>),
1191 /// A `continue`, with an optional label.
1192 Continue(Option<Label>),
1193 /// A `return`, with an optional value to be returned.
1194 Ret(Option<P<Expr>>),
1196 /// Output of the `asm!()` macro.
1197 InlineAsm(P<InlineAsm>),
1199 /// A macro invocation; pre-expansion.
1202 /// A struct literal expression.
1204 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1205 /// where `base` is the `Option<Expr>`.
1206 Struct(Path, Vec<Field>, Option<P<Expr>>),
1208 /// An array literal constructed from one repeated element.
1210 /// E.g., `[1; 5]`. The expression is the element to be
1211 /// repeated; the constant is the number of times to repeat it.
1212 Repeat(P<Expr>, AnonConst),
1214 /// No-op: used solely so we can pretty-print faithfully.
1217 /// A try expression (`expr?`).
1220 /// A `yield`, with an optional value to be yielded.
1221 Yield(Option<P<Expr>>),
1223 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1227 /// The explicit `Self` type in a "qualified path". The actual
1228 /// path, including the trait and the associated item, is stored
1229 /// separately. `position` represents the index of the associated
1230 /// item qualified with this `Self` type.
1232 /// ```ignore (only-for-syntax-highlight)
1233 /// <Vec<T> as a::b::Trait>::AssociatedItem
1234 /// ^~~~~ ~~~~~~~~~~~~~~^
1237 /// <Vec<T>>::AssociatedItem
1241 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1245 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1246 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1247 /// 0`, this is an empty span.
1248 pub path_span: Span,
1249 pub position: usize,
1252 /// A capture clause.
1253 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1254 pub enum CaptureBy {
1259 /// The movability of a generator / closure literal.
1260 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1261 pub enum Movability {
1266 pub type Mac = Spanned<Mac_>;
1268 /// Represents a macro invocation. The `Path` indicates which macro
1269 /// is being invoked, and the vector of token-trees contains the source
1270 /// of the macro invocation.
1272 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1273 /// stored in the enclosing item.
1274 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1277 pub delim: MacDelimiter,
1278 pub tts: TokenStream,
1281 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1282 pub enum MacDelimiter {
1289 pub fn stream(&self) -> TokenStream {
1294 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1295 pub struct MacroDef {
1296 pub tokens: TokenStream,
1301 pub fn stream(&self) -> TokenStream {
1302 self.tokens.clone().into()
1306 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1308 /// A regular string, like `"foo"`.
1310 /// A raw string, like `r##"foo"##`.
1312 /// The value is the number of `#` symbols used.
1317 pub type Lit = Spanned<LitKind>;
1319 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1320 pub enum LitIntType {
1328 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1329 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1331 /// A string literal (`"foo"`).
1332 Str(Symbol, StrStyle),
1333 /// A byte string (`b"foo"`).
1334 ByteStr(Lrc<Vec<u8>>),
1335 /// A byte char (`b'f'`).
1337 /// A character literal (`'a'`).
1339 /// An integer literal (`1`).
1340 Int(u128, LitIntType),
1341 /// A float literal (`1f64` or `1E10f64`).
1342 Float(Symbol, FloatTy),
1343 /// A float literal without a suffix (`1.0 or 1.0E10`).
1344 FloatUnsuffixed(Symbol),
1345 /// A boolean literal.
1347 /// A recovered character literal that contains mutliple `char`s, most likely a typo.
1352 /// Returns `true` if this literal is a string.
1353 pub fn is_str(&self) -> bool {
1355 LitKind::Str(..) => true,
1360 /// Returns `true` if this literal is byte literal string.
1361 pub fn is_bytestr(&self) -> bool {
1363 LitKind::ByteStr(_) => true,
1368 /// Returns `true` if this is a numeric literal.
1369 pub fn is_numeric(&self) -> bool {
1371 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1376 /// Returns `true` if this literal has no suffix.
1377 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1378 pub fn is_unsuffixed(&self) -> bool {
1380 // unsuffixed variants
1382 | LitKind::ByteStr(..)
1386 | LitKind::Int(_, LitIntType::Unsuffixed)
1387 | LitKind::FloatUnsuffixed(..)
1388 | LitKind::Bool(..) => true,
1389 // suffixed variants
1390 LitKind::Int(_, LitIntType::Signed(..))
1391 | LitKind::Int(_, LitIntType::Unsigned(..))
1392 | LitKind::Float(..) => false,
1396 /// Returns `true` if this literal has a suffix.
1397 pub fn is_suffixed(&self) -> bool {
1398 !self.is_unsuffixed()
1402 // N.B., If you change this, you'll probably want to change the corresponding
1403 // type structure in `middle/ty.rs` as well.
1404 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1407 pub mutbl: Mutability,
1410 /// Represents a method's signature in a trait declaration,
1411 /// or in an implementation.
1412 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1413 pub struct MethodSig {
1414 pub header: FnHeader,
1415 pub decl: P<FnDecl>,
1418 /// Represents an item declaration within a trait declaration,
1419 /// possibly including a default implementation. A trait item is
1420 /// either required (meaning it doesn't have an implementation, just a
1421 /// signature) or provided (meaning it has a default implementation).
1422 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1423 pub struct TraitItem {
1426 pub attrs: Vec<Attribute>,
1427 pub generics: Generics,
1428 pub node: TraitItemKind,
1430 /// See `Item::tokens` for what this is.
1431 pub tokens: Option<TokenStream>,
1434 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1435 pub enum TraitItemKind {
1436 Const(P<Ty>, Option<P<Expr>>),
1437 Method(MethodSig, Option<P<Block>>),
1438 Type(GenericBounds, Option<P<Ty>>),
1442 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1443 pub struct ImplItem {
1446 pub vis: Visibility,
1447 pub defaultness: Defaultness,
1448 pub attrs: Vec<Attribute>,
1449 pub generics: Generics,
1450 pub node: ImplItemKind,
1452 /// See `Item::tokens` for what this is.
1453 pub tokens: Option<TokenStream>,
1456 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1457 pub enum ImplItemKind {
1458 Const(P<Ty>, P<Expr>),
1459 Method(MethodSig, P<Block>),
1461 Existential(GenericBounds),
1465 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1475 impl fmt::Debug for IntTy {
1476 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1477 fmt::Display::fmt(self, f)
1481 impl fmt::Display for IntTy {
1482 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1483 write!(f, "{}", self.ty_to_string())
1488 pub fn ty_to_string(&self) -> &'static str {
1490 IntTy::Isize => "isize",
1492 IntTy::I16 => "i16",
1493 IntTy::I32 => "i32",
1494 IntTy::I64 => "i64",
1495 IntTy::I128 => "i128",
1499 pub fn val_to_string(&self, val: i128) -> String {
1500 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1501 // are parsed as `u128`, so we wouldn't want to print an extra negative
1503 format!("{}{}", val as u128, self.ty_to_string())
1506 pub fn bit_width(&self) -> Option<usize> {
1508 IntTy::Isize => return None,
1518 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1529 pub fn ty_to_string(&self) -> &'static str {
1531 UintTy::Usize => "usize",
1533 UintTy::U16 => "u16",
1534 UintTy::U32 => "u32",
1535 UintTy::U64 => "u64",
1536 UintTy::U128 => "u128",
1540 pub fn val_to_string(&self, val: u128) -> String {
1541 format!("{}{}", val, self.ty_to_string())
1544 pub fn bit_width(&self) -> Option<usize> {
1546 UintTy::Usize => return None,
1551 UintTy::U128 => 128,
1556 impl fmt::Debug for UintTy {
1557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1558 fmt::Display::fmt(self, f)
1562 impl fmt::Display for UintTy {
1563 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1564 write!(f, "{}", self.ty_to_string())
1568 // Bind a type to an associated type: `A = Foo`.
1569 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1570 pub struct TypeBinding {
1577 #[derive(Clone, RustcEncodable, RustcDecodable)]
1584 impl fmt::Debug for Ty {
1585 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1586 write!(f, "type({})", pprust::ty_to_string(self))
1590 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1591 pub struct BareFnTy {
1592 pub unsafety: Unsafety,
1594 pub generic_params: Vec<GenericParam>,
1595 pub decl: P<FnDecl>,
1598 /// The various kinds of type recognized by the compiler.
1599 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1601 /// A variable-length slice (`[T]`).
1603 /// A fixed length array (`[T; n]`).
1604 Array(P<Ty>, AnonConst),
1605 /// A raw pointer (`*const T` or `*mut T`).
1607 /// A reference (`&'a T` or `&'a mut T`).
1608 Rptr(Option<Lifetime>, MutTy),
1609 /// A bare function (e.g., `fn(usize) -> bool`).
1610 BareFn(P<BareFnTy>),
1611 /// The never type (`!`).
1613 /// A tuple (`(A, B, C, D,...)`).
1615 /// A path (`module::module::...::Type`), optionally
1616 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1618 /// Type parameters are stored in the `Path` itself.
1619 Path(Option<QSelf>, Path),
1620 /// A trait object type `Bound1 + Bound2 + Bound3`
1621 /// where `Bound` is a trait or a lifetime.
1622 TraitObject(GenericBounds, TraitObjectSyntax),
1623 /// An `impl Bound1 + Bound2 + Bound3` type
1624 /// where `Bound` is a trait or a lifetime.
1626 /// The `NodeId` exists to prevent lowering from having to
1627 /// generate `NodeId`s on the fly, which would complicate
1628 /// the generation of `existential type` items significantly.
1629 ImplTrait(NodeId, GenericBounds),
1630 /// No-op; kept solely so that we can pretty-print faithfully.
1634 /// This means the type should be inferred instead of it having been
1635 /// specified. This can appear anywhere in a type.
1637 /// Inferred type of a `self` or `&self` argument in a method.
1639 /// A macro in the type position.
1641 /// Placeholder for a kind that has failed to be defined.
1643 /// Placeholder for a `va_list`.
1648 pub fn is_implicit_self(&self) -> bool {
1649 if let TyKind::ImplicitSelf = *self {
1656 pub fn is_unit(&self) -> bool {
1657 if let TyKind::Tup(ref tys) = *self {
1665 /// Syntax used to declare a trait object.
1666 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1667 pub enum TraitObjectSyntax {
1672 /// Inline assembly dialect.
1674 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1675 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1676 pub enum AsmDialect {
1681 /// Inline assembly.
1683 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1684 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1685 pub struct InlineAsmOutput {
1686 pub constraint: Symbol,
1689 pub is_indirect: bool,
1692 /// Inline assembly.
1694 /// E.g., `asm!("NOP");`.
1695 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1696 pub struct InlineAsm {
1698 pub asm_str_style: StrStyle,
1699 pub outputs: Vec<InlineAsmOutput>,
1700 pub inputs: Vec<(Symbol, P<Expr>)>,
1701 pub clobbers: Vec<Symbol>,
1703 pub alignstack: bool,
1704 pub dialect: AsmDialect,
1705 pub ctxt: SyntaxContext,
1708 /// An argument in a function header.
1710 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1711 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1718 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1720 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1721 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1723 /// `self`, `mut self`
1725 /// `&'lt self`, `&'lt mut self`
1726 Region(Option<Lifetime>, Mutability),
1727 /// `self: TYPE`, `mut self: TYPE`
1728 Explicit(P<Ty>, Mutability),
1731 pub type ExplicitSelf = Spanned<SelfKind>;
1734 pub fn to_self(&self) -> Option<ExplicitSelf> {
1735 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1736 if ident.name == keywords::SelfLower.name() {
1737 return match self.ty.node {
1738 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1739 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1740 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1743 self.pat.span.to(self.ty.span),
1744 SelfKind::Explicit(self.ty.clone(), mutbl),
1752 pub fn is_self(&self) -> bool {
1753 if let PatKind::Ident(_, ident, _) = self.pat.node {
1754 ident.name == keywords::SelfLower.name()
1760 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1761 let span = eself.span.to(eself_ident.span);
1762 let infer_ty = P(Ty {
1764 node: TyKind::ImplicitSelf,
1767 let arg = |mutbl, ty| Arg {
1770 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1777 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1778 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1779 SelfKind::Region(lt, mutbl) => arg(
1780 Mutability::Immutable,
1797 /// Header (not the body) of a function declaration.
1799 /// E.g., `fn foo(bar: baz)`.
1800 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1802 pub inputs: Vec<Arg>,
1803 pub output: FunctionRetTy,
1804 pub c_variadic: bool,
1808 pub fn get_self(&self) -> Option<ExplicitSelf> {
1809 self.inputs.get(0).and_then(Arg::to_self)
1811 pub fn has_self(&self) -> bool {
1812 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1816 /// Is the trait definition an auto trait?
1817 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1823 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1829 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1833 return_impl_trait_id: NodeId,
1839 pub fn is_async(self) -> bool {
1840 if let IsAsync::Async { .. } = self {
1847 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1848 pub fn opt_return_id(self) -> Option<NodeId> {
1851 return_impl_trait_id,
1853 } => Some(return_impl_trait_id),
1854 IsAsync::NotAsync => None,
1859 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1860 pub enum Constness {
1865 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1866 pub enum Defaultness {
1871 impl fmt::Display for Unsafety {
1872 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1875 Unsafety::Normal => "normal",
1876 Unsafety::Unsafe => "unsafe",
1883 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1884 pub enum ImplPolarity {
1885 /// `impl Trait for Type`
1887 /// `impl !Trait for Type`
1891 impl fmt::Debug for ImplPolarity {
1892 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1894 ImplPolarity::Positive => "positive".fmt(f),
1895 ImplPolarity::Negative => "negative".fmt(f),
1900 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1901 pub enum FunctionRetTy {
1902 /// Returns type is not specified.
1904 /// Functions default to `()` and closures default to inference.
1905 /// Span points to where return type would be inserted.
1907 /// Everything else.
1911 impl FunctionRetTy {
1912 pub fn span(&self) -> Span {
1914 FunctionRetTy::Default(span) => span,
1915 FunctionRetTy::Ty(ref ty) => ty.span,
1920 /// Module declaration.
1922 /// E.g., `mod foo;` or `mod foo { .. }`.
1923 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1925 /// A span from the first token past `{` to the last token until `}`.
1926 /// For `mod foo;`, the inner span ranges from the first token
1927 /// to the last token in the external file.
1929 pub items: Vec<P<Item>>,
1930 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
1934 /// Foreign module declaration.
1936 /// E.g., `extern { .. }` or `extern C { .. }`.
1937 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1938 pub struct ForeignMod {
1940 pub items: Vec<ForeignItem>,
1943 /// Global inline assembly.
1945 /// Also known as "module-level assembly" or "file-scoped assembly".
1946 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1947 pub struct GlobalAsm {
1949 pub ctxt: SyntaxContext,
1952 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1953 pub struct EnumDef {
1954 pub variants: Vec<Variant>,
1957 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1958 pub struct Variant_ {
1960 pub attrs: Vec<Attribute>,
1961 pub data: VariantData,
1962 /// Explicit discriminant, e.g., `Foo = 1`.
1963 pub disr_expr: Option<AnonConst>,
1966 pub type Variant = Spanned<Variant_>;
1968 /// Part of `use` item to the right of its prefix.
1969 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1970 pub enum UseTreeKind {
1971 /// `use prefix` or `use prefix as rename`
1973 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1975 Simple(Option<Ident>, NodeId, NodeId),
1976 /// `use prefix::{...}`
1977 Nested(Vec<(UseTree, NodeId)>),
1982 /// A tree of paths sharing common prefixes.
1983 /// Used in `use` items both at top-level and inside of braces in import groups.
1984 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1985 pub struct UseTree {
1987 pub kind: UseTreeKind,
1992 pub fn ident(&self) -> Ident {
1994 UseTreeKind::Simple(Some(rename), ..) => rename,
1995 UseTreeKind::Simple(None, ..) => {
1999 .expect("empty prefix in a simple import")
2002 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2007 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2008 /// are contained as statements within items. These two cases need to be
2009 /// distinguished for pretty-printing.
2010 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
2011 pub enum AttrStyle {
2017 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
2019 pub struct AttrId(pub usize);
2021 impl Idx for AttrId {
2022 fn new(idx: usize) -> Self {
2025 fn index(self) -> usize {
2030 /// Metadata associated with an item.
2031 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
2032 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2033 pub struct Attribute {
2035 pub style: AttrStyle,
2037 pub tokens: TokenStream,
2038 pub is_sugared_doc: bool,
2042 /// `TraitRef`s appear in impls.
2044 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2045 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2046 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2047 /// same as the impl's `NodeId`).
2048 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2049 pub struct TraitRef {
2054 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2055 pub struct PolyTraitRef {
2056 /// The `'a` in `<'a> Foo<&'a T>`
2057 pub bound_generic_params: Vec<GenericParam>,
2059 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2060 pub trait_ref: TraitRef,
2066 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2068 bound_generic_params: generic_params,
2069 trait_ref: TraitRef {
2071 ref_id: DUMMY_NODE_ID,
2078 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2079 pub enum CrateSugar {
2080 /// Source is `pub(crate)`.
2083 /// Source is (just) `crate`.
2087 pub type Visibility = Spanned<VisibilityKind>;
2089 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2090 pub enum VisibilityKind {
2093 Restricted { path: P<Path>, id: NodeId },
2097 impl VisibilityKind {
2098 pub fn is_pub(&self) -> bool {
2099 if let VisibilityKind::Public = *self {
2107 /// Field of a struct.
2109 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2110 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2111 pub struct StructField {
2113 pub ident: Option<Ident>,
2114 pub vis: Visibility,
2117 pub attrs: Vec<Attribute>,
2120 /// Fields and Ids of enum variants and structs
2122 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2123 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2124 /// One shared Id can be successfully used for these two purposes.
2125 /// Id of the whole enum lives in `Item`.
2127 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2128 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2129 /// the variant itself" from enum variants.
2130 /// Id of the whole struct lives in `Item`.
2131 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2132 pub enum VariantData {
2135 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2136 Struct(Vec<StructField>, NodeId, bool),
2139 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2140 Tuple(Vec<StructField>, NodeId),
2143 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2148 pub fn fields(&self) -> &[StructField] {
2150 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2154 pub fn id(&self) -> NodeId {
2156 VariantData::Struct(_, id, _) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2159 pub fn is_struct(&self) -> bool {
2160 if let VariantData::Struct(..) = *self {
2166 pub fn is_tuple(&self) -> bool {
2167 if let VariantData::Tuple(..) = *self {
2173 pub fn is_unit(&self) -> bool {
2174 if let VariantData::Unit(..) = *self {
2184 /// The name might be a dummy name in case of anonymous items.
2185 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2188 pub attrs: Vec<Attribute>,
2191 pub vis: Visibility,
2194 /// Original tokens this item was parsed from. This isn't necessarily
2195 /// available for all items, although over time more and more items should
2196 /// have this be `Some`. Right now this is primarily used for procedural
2197 /// macros, notably custom attributes.
2199 /// Note that the tokens here do not include the outer attributes, but will
2200 /// include inner attributes.
2201 pub tokens: Option<TokenStream>,
2205 /// Return the span that encompasses the attributes.
2206 pub fn span_with_attributes(&self) -> Span {
2207 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2211 /// A function header.
2213 /// All the information between the visibility and the name of the function is
2214 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2215 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2216 pub struct FnHeader {
2217 pub unsafety: Unsafety,
2218 pub asyncness: Spanned<IsAsync>,
2219 pub constness: Spanned<Constness>,
2223 impl Default for FnHeader {
2224 fn default() -> FnHeader {
2226 unsafety: Unsafety::Normal,
2227 asyncness: dummy_spanned(IsAsync::NotAsync),
2228 constness: dummy_spanned(Constness::NotConst),
2234 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2236 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2238 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2239 ExternCrate(Option<Name>),
2240 /// A use declaration (`use` or `pub use`) item.
2242 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2244 /// A static item (`static` or `pub static`).
2246 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2247 Static(P<Ty>, Mutability, P<Expr>),
2248 /// A constant item (`const` or `pub const`).
2250 /// E.g., `const FOO: i32 = 42;`.
2251 Const(P<Ty>, P<Expr>),
2252 /// A function declaration (`fn` or `pub fn`).
2254 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2255 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2256 /// A module declaration (`mod` or `pub mod`).
2258 /// E.g., `mod foo;` or `mod foo { .. }`.
2260 /// An external module (`extern` or `pub extern`).
2262 /// E.g., `extern {}` or `extern "C" {}`.
2263 ForeignMod(ForeignMod),
2264 /// Module-level inline assembly (from `global_asm!()`).
2265 GlobalAsm(P<GlobalAsm>),
2266 /// A type alias (`type` or `pub type`).
2268 /// E.g., `type Foo = Bar<u8>;`.
2269 Ty(P<Ty>, Generics),
2270 /// An existential type declaration (`existential type`).
2272 /// E.g., `existential type Foo: Bar + Boo;`.
2273 Existential(GenericBounds, Generics),
2274 /// An enum definition (`enum` or `pub enum`).
2276 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2277 Enum(EnumDef, Generics),
2278 /// A struct definition (`struct` or `pub struct`).
2280 /// E.g., `struct Foo<A> { x: A }`.
2281 Struct(VariantData, Generics),
2282 /// A union definition (`union` or `pub union`).
2284 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2285 Union(VariantData, Generics),
2286 /// A Trait declaration (`trait` or `pub trait`).
2288 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2289 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2292 /// E.g., `trait Foo = Bar + Quux;`.
2293 TraitAlias(Generics, GenericBounds),
2294 /// An implementation.
2296 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2302 Option<TraitRef>, // (optional) trait this impl implements
2306 /// A macro invocation.
2308 /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2311 /// A macro definition.
2316 pub fn descriptive_variant(&self) -> &str {
2318 ItemKind::ExternCrate(..) => "extern crate",
2319 ItemKind::Use(..) => "use",
2320 ItemKind::Static(..) => "static item",
2321 ItemKind::Const(..) => "constant item",
2322 ItemKind::Fn(..) => "function",
2323 ItemKind::Mod(..) => "module",
2324 ItemKind::ForeignMod(..) => "foreign module",
2325 ItemKind::GlobalAsm(..) => "global asm",
2326 ItemKind::Ty(..) => "type alias",
2327 ItemKind::Existential(..) => "existential type",
2328 ItemKind::Enum(..) => "enum",
2329 ItemKind::Struct(..) => "struct",
2330 ItemKind::Union(..) => "union",
2331 ItemKind::Trait(..) => "trait",
2332 ItemKind::TraitAlias(..) => "trait alias",
2333 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2338 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2339 pub struct ForeignItem {
2341 pub attrs: Vec<Attribute>,
2342 pub node: ForeignItemKind,
2345 pub vis: Visibility,
2348 /// An item within an `extern` block.
2349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2350 pub enum ForeignItemKind {
2351 /// A foreign function.
2352 Fn(P<FnDecl>, Generics),
2353 /// A foreign static item (`static ext: u8`), with optional mutability.
2354 /// (The boolean is `true` for mutable items).
2355 Static(P<Ty>, bool),
2358 /// A macro invocation.
2362 impl ForeignItemKind {
2363 pub fn descriptive_variant(&self) -> &str {
2365 ForeignItemKind::Fn(..) => "foreign function",
2366 ForeignItemKind::Static(..) => "foreign static item",
2367 ForeignItemKind::Ty => "foreign type",
2368 ForeignItemKind::Macro(..) => "macro in foreign module",
2378 // Are ASTs encodable?
2380 fn check_asts_encodable() {
2381 fn assert_encodable<T: serialize::Encodable>() {}
2382 assert_encodable::<Crate>();