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 /// 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 {
188 /// The arguments for this path segment.
189 pub args: Vec<GenericArg>,
190 /// Bindings (equality constraints) on associated types, if present.
192 /// E.g., `Foo<A=Bar>`.
193 pub bindings: Vec<TypeBinding>,
196 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
197 fn into(self) -> Option<P<GenericArgs>> {
198 Some(P(GenericArgs::AngleBracketed(self)))
202 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
203 fn into(self) -> Option<P<GenericArgs>> {
204 Some(P(GenericArgs::Parenthesized(self)))
208 /// A path like `Foo(A,B) -> C`
209 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
210 pub struct ParenthesizedArgs {
215 pub inputs: Vec<P<Ty>>,
218 pub output: Option<P<Ty>>,
221 impl ParenthesizedArgs {
222 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
225 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
231 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
233 use rustc_data_structures::indexed_vec::Idx;
234 use rustc_data_structures::newtype_index;
238 DEBUG_FORMAT = "NodeId({})"
243 pub use node_id_inner::NodeId;
246 pub fn placeholder_from_mark(mark: Mark) -> Self {
247 NodeId::from_u32(mark.as_u32())
250 pub fn placeholder_to_mark(self) -> Mark {
251 Mark::from_u32(self.as_u32())
255 impl fmt::Display for NodeId {
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 fmt::Display::fmt(&self.as_u32(), f)
261 impl serialize::UseSpecializedEncodable for NodeId {
262 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
263 s.emit_u32(self.as_u32())
267 impl serialize::UseSpecializedDecodable for NodeId {
268 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
269 d.read_u32().map(NodeId::from_u32)
273 /// Node id used to represent the root of the crate.
274 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
276 /// When parsing and doing expansions, we initially give all AST nodes this AST
277 /// node value. Then later, in the renumber pass, we renumber them to have
278 /// small, positive ids.
279 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
281 /// A modifier on a bound, currently this is only used for `?Sized`, where the
282 /// modifier is `Maybe`. Negative bounds should also be handled here.
283 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
284 pub enum TraitBoundModifier {
289 /// The AST represents all type param bounds as types.
290 /// `typeck::collect::compute_bounds` matches these against
291 /// the "special" built-in traits (see `middle::lang_items`) and
292 /// detects `Copy`, `Send` and `Sync`.
293 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
294 pub enum GenericBound {
295 Trait(PolyTraitRef, TraitBoundModifier),
300 pub fn span(&self) -> Span {
302 &GenericBound::Trait(ref t, ..) => t.span,
303 &GenericBound::Outlives(ref l) => l.ident.span,
308 pub type GenericBounds = Vec<GenericBound>;
310 /// Specifies the enforced ordering for generic parameters. In the future,
311 /// if we wanted to relax this order, we could override `PartialEq` and
312 /// `PartialOrd`, to allow the kinds to be unordered.
313 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
314 pub enum ParamKindOrd {
320 impl fmt::Display for ParamKindOrd {
321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 ParamKindOrd::Lifetime => "lifetime".fmt(f),
324 ParamKindOrd::Type => "type".fmt(f),
325 ParamKindOrd::Const => "const".fmt(f),
330 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
331 pub enum GenericParamKind {
332 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
334 Type { default: Option<P<Ty>> },
338 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
339 pub struct GenericParam {
342 pub attrs: ThinVec<Attribute>,
343 pub bounds: GenericBounds,
345 pub kind: GenericParamKind,
348 /// Represents lifetime, type and const parameters attached to a declaration of
349 /// a function, enum, trait, etc.
350 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
351 pub struct Generics {
352 pub params: Vec<GenericParam>,
353 pub where_clause: WhereClause,
357 impl Default for Generics {
358 /// Creates an instance of `Generics`.
359 fn default() -> Generics {
362 where_clause: WhereClause {
364 predicates: Vec::new(),
372 /// A `where` clause in a definition
373 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
374 pub struct WhereClause {
376 pub predicates: Vec<WherePredicate>,
380 /// A single predicate in a `where` clause
381 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
382 pub enum WherePredicate {
383 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
384 BoundPredicate(WhereBoundPredicate),
385 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
386 RegionPredicate(WhereRegionPredicate),
387 /// An equality predicate (unsupported).
388 EqPredicate(WhereEqPredicate),
391 impl WherePredicate {
392 pub fn span(&self) -> Span {
394 &WherePredicate::BoundPredicate(ref p) => p.span,
395 &WherePredicate::RegionPredicate(ref p) => p.span,
396 &WherePredicate::EqPredicate(ref p) => p.span,
403 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
404 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
405 pub struct WhereBoundPredicate {
407 /// Any generics from a `for` binding
408 pub bound_generic_params: Vec<GenericParam>,
409 /// The type being bounded
410 pub bounded_ty: P<Ty>,
411 /// Trait and lifetime bounds (`Clone+Send+'static`)
412 pub bounds: GenericBounds,
415 /// A lifetime predicate.
417 /// E.g., `'a: 'b + 'c`.
418 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
419 pub struct WhereRegionPredicate {
421 pub lifetime: Lifetime,
422 pub bounds: GenericBounds,
425 /// An equality predicate (unsupported).
428 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
429 pub struct WhereEqPredicate {
436 /// The set of `MetaItem`s that define the compilation environment of the crate,
437 /// used to drive conditional compilation.
438 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
440 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
443 pub attrs: Vec<Attribute>,
447 /// A spanned compile-time attribute list item.
448 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
450 /// Possible values inside of compile-time attribute lists.
452 /// E.g., the '..' in `#[name(..)]`.
453 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
454 pub enum NestedMetaItemKind {
455 /// A full MetaItem, for recursive meta items.
459 /// E.g., `"foo"`, `64`, `true`.
463 /// A spanned compile-time attribute item.
465 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
466 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
467 pub struct MetaItem {
469 pub node: MetaItemKind,
473 /// A compile-time attribute item.
475 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
476 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
477 pub enum MetaItemKind {
480 /// E.g., `test` as in `#[test]`.
484 /// E.g., `derive(..)` as in `#[derive(..)]`.
485 List(Vec<NestedMetaItem>),
486 /// Name value meta item.
488 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
492 /// A Block (`{ .. }`).
494 /// E.g., `{ .. }` as in `fn foo() { .. }`.
495 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
497 /// Statements in a block
498 pub stmts: Vec<Stmt>,
500 /// Distinguishes between `unsafe { ... }` and `{ ... }`
501 pub rules: BlockCheckMode,
505 #[derive(Clone, RustcEncodable, RustcDecodable)]
512 impl fmt::Debug for Pat {
513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
519 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
520 let node = match &self.node {
521 PatKind::Wild => TyKind::Infer,
522 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
523 TyKind::Path(None, Path::from_ident(*ident))
525 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
526 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
527 PatKind::Ref(pat, mutbl) => pat
529 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
530 PatKind::Slice(pats, None, _) if pats.len() == 1 => {
531 pats[0].to_ty().map(TyKind::Slice)?
533 PatKind::Tuple(pats, None) => {
534 let mut tys = Vec::with_capacity(pats.len());
535 // FIXME(#48994) - could just be collected into an Option<Vec>
537 tys.push(pat.to_ty()?);
551 pub fn walk<F>(&self, it: &mut F) -> bool
553 F: FnMut(&Pat) -> bool,
560 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
561 PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
562 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
563 s.iter().all(|p| p.walk(it))
565 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
566 PatKind::Slice(ref before, ref slice, ref after) => {
567 before.iter().all(|p| p.walk(it))
568 && slice.iter().all(|p| p.walk(it))
569 && after.iter().all(|p| p.walk(it))
576 | PatKind::Mac(_) => true,
581 /// A single field in a struct pattern
583 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
584 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
585 /// except is_shorthand is true
586 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
587 pub struct FieldPat {
588 /// The identifier for the field
590 /// The pattern the field is destructured to
592 pub is_shorthand: bool,
593 pub attrs: ThinVec<Attribute>,
596 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
597 pub enum BindingMode {
602 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
604 Included(RangeSyntax),
608 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
609 pub enum RangeSyntax {
614 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
616 /// Represents a wildcard pattern (`_`).
619 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
620 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
621 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
622 /// during name resolution.
623 Ident(BindingMode, Ident, Option<P<Pat>>),
625 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
626 /// The `bool` is `true` in the presence of a `..`.
627 Struct(Path, Vec<Spanned<FieldPat>>, bool),
629 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
630 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
631 /// `0 <= position <= subpats.len()`.
632 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
634 /// A possibly qualified path pattern.
635 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
636 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
637 /// only legally refer to associated constants.
638 Path(Option<QSelf>, Path),
640 /// A tuple pattern (`(a, b)`).
641 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
642 /// `0 <= position <= subpats.len()`.
643 Tuple(Vec<P<Pat>>, Option<usize>),
646 /// A reference pattern (e.g., `&mut (a, b)`).
647 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>),
652 /// `[a, b, ..i, y, z]` is represented as:
653 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
654 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
655 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
657 /// A macro pattern; pre-expansion.
662 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
664 pub enum Mutability {
669 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
671 /// The `+` operator (addition)
673 /// The `-` operator (subtraction)
675 /// The `*` operator (multiplication)
677 /// The `/` operator (division)
679 /// The `%` operator (modulus)
681 /// The `&&` operator (logical and)
683 /// The `||` operator (logical or)
685 /// The `^` operator (bitwise xor)
687 /// The `&` operator (bitwise and)
689 /// The `|` operator (bitwise or)
691 /// The `<<` operator (shift left)
693 /// The `>>` operator (shift right)
695 /// The `==` operator (equality)
697 /// The `<` operator (less than)
699 /// The `<=` operator (less than or equal to)
701 /// The `!=` operator (not equal to)
703 /// The `>=` operator (greater than or equal to)
705 /// The `>` operator (greater than)
710 pub fn to_string(&self) -> &'static str {
733 pub fn lazy(&self) -> bool {
735 BinOpKind::And | BinOpKind::Or => true,
740 pub fn is_shift(&self) -> bool {
742 BinOpKind::Shl | BinOpKind::Shr => true,
747 pub fn is_comparison(&self) -> bool {
750 Eq | Lt | Le | Ne | Gt | Ge => true,
751 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
755 /// Returns `true` if the binary operator takes its arguments by value
756 pub fn is_by_value(&self) -> bool {
757 !self.is_comparison()
761 pub type BinOp = Spanned<BinOpKind>;
763 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
765 /// The `*` operator for dereferencing
767 /// The `!` operator for logical inversion
769 /// The `-` operator for negation
774 /// Returns `true` if the unary operator takes its argument by value
775 pub fn is_by_value(u: UnOp) -> bool {
777 UnOp::Neg | UnOp::Not => true,
782 pub fn to_string(op: UnOp) -> &'static str {
792 #[derive(Clone, RustcEncodable, RustcDecodable)]
800 pub fn add_trailing_semicolon(mut self) -> Self {
801 self.node = match self.node {
802 StmtKind::Expr(expr) => StmtKind::Semi(expr),
803 StmtKind::Mac(mac) => {
804 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
811 pub fn is_item(&self) -> bool {
813 StmtKind::Item(_) => true,
818 pub fn is_expr(&self) -> bool {
820 StmtKind::Expr(_) => true,
826 impl fmt::Debug for Stmt {
827 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
832 pprust::stmt_to_string(self)
837 #[derive(Clone, RustcEncodable, RustcDecodable)]
839 /// A local (let) binding.
842 /// An item definition.
845 /// Expr without trailing semi-colon.
847 /// Expr with a trailing semi-colon.
850 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
853 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
854 pub enum MacStmtStyle {
855 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
856 /// `foo!(...);`, `foo![...];`).
858 /// The macro statement had braces (e.g., `foo! { ... }`).
860 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
861 /// `foo!(...)`). All of these will end up being converted into macro
866 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
867 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
870 pub ty: Option<P<Ty>>,
871 /// Initializer expression to set the value, if any.
872 pub init: Option<P<Expr>>,
875 pub attrs: ThinVec<Attribute>,
878 /// An arm of a 'match'.
880 /// E.g., `0..=10 => { println!("match!") }` as in
884 /// 0..=10 => { println!("match!") },
885 /// _ => { println!("no match!") },
888 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
890 pub attrs: Vec<Attribute>,
891 pub pats: Vec<P<Pat>>,
892 pub guard: Option<Guard>,
896 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
901 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
906 pub is_shorthand: bool,
907 pub attrs: ThinVec<Attribute>,
910 pub type SpannedIdent = Spanned<Ident>;
912 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
913 pub enum BlockCheckMode {
915 Unsafe(UnsafeSource),
918 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
919 pub enum UnsafeSource {
924 /// A constant (expression) that's not an item or associated item,
925 /// but needs its own `DefId` for type-checking, const-eval, etc.
926 /// These are usually found nested inside types (e.g., array lengths)
927 /// or expressions (e.g., repeat counts), and also used to define
928 /// explicit discriminant values for enum variants.
929 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
930 pub struct AnonConst {
936 #[derive(Clone, RustcEncodable, RustcDecodable)]
941 pub attrs: ThinVec<Attribute>,
944 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
945 #[cfg(target_arch = "x86_64")]
946 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 88);
949 /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
951 pub fn returns(&self) -> bool {
952 if let ExprKind::Block(ref block, _) = self.node {
953 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
955 Some(&StmtKind::Expr(_)) => true,
956 Some(&StmtKind::Semi(ref expr)) => {
957 if let ExprKind::Ret(_) = expr.node {
958 // last statement is explicit return
964 // This is a block that doesn't end in either an implicit or explicit return
968 // This is not a block, it is a value
973 fn to_bound(&self) -> Option<GenericBound> {
975 ExprKind::Path(None, path) => Some(GenericBound::Trait(
976 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
977 TraitBoundModifier::None,
983 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
984 let node = match &self.node {
985 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
986 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
987 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
988 ExprKind::AddrOf(mutbl, expr) => expr
990 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
991 ExprKind::Repeat(expr, expr_len) => {
992 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
994 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
995 ExprKind::Tup(exprs) => {
998 .map(|expr| expr.to_ty())
999 .collect::<Option<Vec<_>>>()?;
1002 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1003 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1004 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1019 pub fn precedence(&self) -> ExprPrecedence {
1021 ExprKind::Box(_) => ExprPrecedence::Box,
1022 ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
1023 ExprKind::Array(_) => ExprPrecedence::Array,
1024 ExprKind::Call(..) => ExprPrecedence::Call,
1025 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1026 ExprKind::Tup(_) => ExprPrecedence::Tup,
1027 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1028 ExprKind::Unary(..) => ExprPrecedence::Unary,
1029 ExprKind::Lit(_) => ExprPrecedence::Lit,
1030 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1031 ExprKind::If(..) => ExprPrecedence::If,
1032 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
1033 ExprKind::While(..) => ExprPrecedence::While,
1034 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
1035 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1036 ExprKind::Loop(..) => ExprPrecedence::Loop,
1037 ExprKind::Match(..) => ExprPrecedence::Match,
1038 ExprKind::Closure(..) => ExprPrecedence::Closure,
1039 ExprKind::Block(..) => ExprPrecedence::Block,
1040 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1041 ExprKind::Async(..) => ExprPrecedence::Async,
1042 ExprKind::Assign(..) => ExprPrecedence::Assign,
1043 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1044 ExprKind::Field(..) => ExprPrecedence::Field,
1045 ExprKind::Index(..) => ExprPrecedence::Index,
1046 ExprKind::Range(..) => ExprPrecedence::Range,
1047 ExprKind::Path(..) => ExprPrecedence::Path,
1048 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1049 ExprKind::Break(..) => ExprPrecedence::Break,
1050 ExprKind::Continue(..) => ExprPrecedence::Continue,
1051 ExprKind::Ret(..) => ExprPrecedence::Ret,
1052 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1053 ExprKind::Mac(..) => ExprPrecedence::Mac,
1054 ExprKind::Struct(..) => ExprPrecedence::Struct,
1055 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1056 ExprKind::Paren(..) => ExprPrecedence::Paren,
1057 ExprKind::Try(..) => ExprPrecedence::Try,
1058 ExprKind::Yield(..) => ExprPrecedence::Yield,
1059 ExprKind::Err => ExprPrecedence::Err,
1064 impl fmt::Debug for Expr {
1065 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1066 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1070 /// Limit types of a range (inclusive or exclusive)
1071 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1072 pub enum RangeLimits {
1073 /// Inclusive at the beginning, exclusive at the end
1075 /// Inclusive at the beginning and end
1079 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1081 /// A `box x` expression.
1083 /// First expr is the place; second expr is the value.
1084 ObsoleteInPlace(P<Expr>, P<Expr>),
1085 /// An array (`[a, b, c, d]`)
1086 Array(Vec<P<Expr>>),
1089 /// The first field resolves to the function itself,
1090 /// and the second field is the list of arguments.
1091 /// This also represents calling the constructor of
1092 /// tuple-like ADTs such as tuple structs and enum variants.
1093 Call(P<Expr>, Vec<P<Expr>>),
1094 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1096 /// The `PathSegment` represents the method name and its generic arguments
1097 /// (within the angle brackets).
1098 /// The first element of the vector of an `Expr` is the expression that evaluates
1099 /// to the object on which the method is being called on (the receiver),
1100 /// and the remaining elements are the rest of the arguments.
1101 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1102 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1103 MethodCall(PathSegment, Vec<P<Expr>>),
1104 /// A tuple (e.g., `(a, b, c, d)`).
1106 /// A binary operation (e.g., `a + b`, `a * b`).
1107 Binary(BinOp, P<Expr>, P<Expr>),
1108 /// A unary operation (e.g., `!x`, `*x`).
1109 Unary(UnOp, P<Expr>),
1110 /// A literal (e.g., `1`, `"foo"`).
1112 /// A cast (e.g., `foo as f64`).
1113 Cast(P<Expr>, P<Ty>),
1114 Type(P<Expr>, P<Ty>),
1115 /// An `if` block, with an optional `else` block.
1117 /// `if expr { block } else { expr }`
1118 If(P<Expr>, P<Block>, Option<P<Expr>>),
1119 /// An `if let` expression with an optional else block
1121 /// `if let pat = expr { block } else { expr }`
1123 /// This is desugared to a `match` expression.
1124 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1125 /// A while loop, with an optional label
1127 /// `'label: while expr { block }`
1128 While(P<Expr>, P<Block>, Option<Label>),
1129 /// A `while let` loop, with an optional label.
1131 /// `'label: while let pat = expr { block }`
1133 /// This is desugared to a combination of `loop` and `match` expressions.
1134 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1135 /// A `for` loop, with an optional label.
1137 /// `'label: for pat in expr { block }`
1139 /// This is desugared to a combination of `loop` and `match` expressions.
1140 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1141 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1143 /// `'label: loop { block }`
1144 Loop(P<Block>, Option<Label>),
1145 /// A `match` block.
1146 Match(P<Expr>, Vec<Arm>),
1147 /// A closure (e.g., `move |a, b, c| a + b + c`).
1149 /// The final span is the span of the argument block `|...|`.
1150 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1151 /// A block (`'label: { ... }`).
1152 Block(P<Block>, Option<Label>),
1153 /// An async block (`async move { ... }`).
1155 /// The `NodeId` is the `NodeId` for the closure that results from
1156 /// desugaring an async block, just like the NodeId field in the
1157 /// `IsAsync` enum. This is necessary in order to create a def for the
1158 /// closure which can be used as a parent of any child defs. Defs
1159 /// created during lowering cannot be made the parent of any other
1160 /// preexisting defs.
1161 Async(CaptureBy, NodeId, P<Block>),
1162 /// A try block (`try { ... }`).
1165 /// An assignment (`a = foo()`).
1166 Assign(P<Expr>, P<Expr>),
1167 /// An assignment with an operator.
1170 AssignOp(BinOp, P<Expr>, P<Expr>),
1171 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1172 Field(P<Expr>, Ident),
1173 /// An indexing operation (e.g., `foo[2]`).
1174 Index(P<Expr>, P<Expr>),
1175 /// A range (e.g., `1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`).
1176 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1178 /// Variable reference, possibly containing `::` and/or type
1179 /// parameters (e.g., `foo::bar::<baz>`).
1181 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1182 Path(Option<QSelf>, Path),
1184 /// A referencing operation (`&a` or `&mut a`).
1185 AddrOf(Mutability, P<Expr>),
1186 /// A `break`, with an optional label to break, and an optional expression.
1187 Break(Option<Label>, Option<P<Expr>>),
1188 /// A `continue`, with an optional label.
1189 Continue(Option<Label>),
1190 /// A `return`, with an optional value to be returned.
1191 Ret(Option<P<Expr>>),
1193 /// Output of the `asm!()` macro.
1194 InlineAsm(P<InlineAsm>),
1196 /// A macro invocation; pre-expansion.
1199 /// A struct literal expression.
1201 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1202 /// where `base` is the `Option<Expr>`.
1203 Struct(Path, Vec<Field>, Option<P<Expr>>),
1205 /// An array literal constructed from one repeated element.
1207 /// E.g., `[1; 5]`. The expression is the element to be
1208 /// repeated; the constant is the number of times to repeat it.
1209 Repeat(P<Expr>, AnonConst),
1211 /// No-op: used solely so we can pretty-print faithfully.
1214 /// A try expression (`expr?`).
1217 /// A `yield`, with an optional value to be yielded.
1218 Yield(Option<P<Expr>>),
1220 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1224 /// The explicit `Self` type in a "qualified path". The actual
1225 /// path, including the trait and the associated item, is stored
1226 /// separately. `position` represents the index of the associated
1227 /// item qualified with this `Self` type.
1229 /// ```ignore (only-for-syntax-highlight)
1230 /// <Vec<T> as a::b::Trait>::AssociatedItem
1231 /// ^~~~~ ~~~~~~~~~~~~~~^
1234 /// <Vec<T>>::AssociatedItem
1238 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1242 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1243 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1244 /// 0`, this is an empty span.
1245 pub path_span: Span,
1246 pub position: usize,
1249 /// A capture clause.
1250 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1251 pub enum CaptureBy {
1256 /// The movability of a generator / closure literal.
1257 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1258 pub enum Movability {
1263 pub type Mac = Spanned<Mac_>;
1265 /// Represents a macro invocation. The `Path` indicates which macro
1266 /// is being invoked, and the vector of token-trees contains the source
1267 /// of the macro invocation.
1269 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1270 /// stored in the enclosing item.
1271 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1274 pub delim: MacDelimiter,
1275 pub tts: TokenStream,
1278 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1279 pub enum MacDelimiter {
1286 pub fn stream(&self) -> TokenStream {
1291 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1292 pub struct MacroDef {
1293 pub tokens: TokenStream,
1298 pub fn stream(&self) -> TokenStream {
1299 self.tokens.clone().into()
1303 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1305 /// A regular string, like `"foo"`.
1307 /// A raw string, like `r##"foo"##`.
1309 /// The value is the number of `#` symbols used.
1314 pub type Lit = Spanned<LitKind>;
1316 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1317 pub enum LitIntType {
1325 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1326 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1328 /// A string literal (`"foo"`).
1329 Str(Symbol, StrStyle),
1330 /// A byte string (`b"foo"`).
1331 ByteStr(Lrc<Vec<u8>>),
1332 /// A byte char (`b'f'`).
1334 /// A character literal (`'a'`).
1336 /// An integer literal (`1`).
1337 Int(u128, LitIntType),
1338 /// A float literal (`1f64` or `1E10f64`).
1339 Float(Symbol, FloatTy),
1340 /// A float literal without a suffix (`1.0 or 1.0E10`).
1341 FloatUnsuffixed(Symbol),
1342 /// A boolean literal.
1344 /// A recovered character literal that contains mutliple `char`s, most likely a typo.
1349 /// Returns `true` if this literal is a string.
1350 pub fn is_str(&self) -> bool {
1352 LitKind::Str(..) => true,
1357 /// Returns `true` if this literal is byte literal string.
1358 pub fn is_bytestr(&self) -> bool {
1360 LitKind::ByteStr(_) => true,
1365 /// Returns `true` if this is a numeric literal.
1366 pub fn is_numeric(&self) -> bool {
1368 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1373 /// Returns `true` if this literal has no suffix.
1374 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1375 pub fn is_unsuffixed(&self) -> bool {
1377 // unsuffixed variants
1379 | LitKind::ByteStr(..)
1383 | LitKind::Int(_, LitIntType::Unsuffixed)
1384 | LitKind::FloatUnsuffixed(..)
1385 | LitKind::Bool(..) => true,
1386 // suffixed variants
1387 LitKind::Int(_, LitIntType::Signed(..))
1388 | LitKind::Int(_, LitIntType::Unsigned(..))
1389 | LitKind::Float(..) => false,
1393 /// Returns `true` if this literal has a suffix.
1394 pub fn is_suffixed(&self) -> bool {
1395 !self.is_unsuffixed()
1399 // N.B., If you change this, you'll probably want to change the corresponding
1400 // type structure in `middle/ty.rs` as well.
1401 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1404 pub mutbl: Mutability,
1407 /// Represents a method's signature in a trait declaration,
1408 /// or in an implementation.
1409 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1410 pub struct MethodSig {
1411 pub header: FnHeader,
1412 pub decl: P<FnDecl>,
1415 /// Represents an item declaration within a trait declaration,
1416 /// possibly including a default implementation. A trait item is
1417 /// either required (meaning it doesn't have an implementation, just a
1418 /// signature) or provided (meaning it has a default implementation).
1419 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1420 pub struct TraitItem {
1423 pub attrs: Vec<Attribute>,
1424 pub generics: Generics,
1425 pub node: TraitItemKind,
1427 /// See `Item::tokens` for what this is.
1428 pub tokens: Option<TokenStream>,
1431 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1432 pub enum TraitItemKind {
1433 Const(P<Ty>, Option<P<Expr>>),
1434 Method(MethodSig, Option<P<Block>>),
1435 Type(GenericBounds, Option<P<Ty>>),
1439 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1440 pub struct ImplItem {
1443 pub vis: Visibility,
1444 pub defaultness: Defaultness,
1445 pub attrs: Vec<Attribute>,
1446 pub generics: Generics,
1447 pub node: ImplItemKind,
1449 /// See `Item::tokens` for what this is.
1450 pub tokens: Option<TokenStream>,
1453 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1454 pub enum ImplItemKind {
1455 Const(P<Ty>, P<Expr>),
1456 Method(MethodSig, P<Block>),
1458 Existential(GenericBounds),
1462 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1472 impl fmt::Debug for IntTy {
1473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1474 fmt::Display::fmt(self, f)
1478 impl fmt::Display for IntTy {
1479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1480 write!(f, "{}", self.ty_to_string())
1485 pub fn ty_to_string(&self) -> &'static str {
1487 IntTy::Isize => "isize",
1489 IntTy::I16 => "i16",
1490 IntTy::I32 => "i32",
1491 IntTy::I64 => "i64",
1492 IntTy::I128 => "i128",
1496 pub fn val_to_string(&self, val: i128) -> String {
1497 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1498 // are parsed as `u128`, so we wouldn't want to print an extra negative
1500 format!("{}{}", val as u128, self.ty_to_string())
1503 pub fn bit_width(&self) -> Option<usize> {
1505 IntTy::Isize => return None,
1515 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1526 pub fn ty_to_string(&self) -> &'static str {
1528 UintTy::Usize => "usize",
1530 UintTy::U16 => "u16",
1531 UintTy::U32 => "u32",
1532 UintTy::U64 => "u64",
1533 UintTy::U128 => "u128",
1537 pub fn val_to_string(&self, val: u128) -> String {
1538 format!("{}{}", val, self.ty_to_string())
1541 pub fn bit_width(&self) -> Option<usize> {
1543 UintTy::Usize => return None,
1548 UintTy::U128 => 128,
1553 impl fmt::Debug for UintTy {
1554 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1555 fmt::Display::fmt(self, f)
1559 impl fmt::Display for UintTy {
1560 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1561 write!(f, "{}", self.ty_to_string())
1565 // Bind a type to an associated type: `A = Foo`.
1566 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1567 pub struct TypeBinding {
1574 #[derive(Clone, RustcEncodable, RustcDecodable)]
1581 impl fmt::Debug for Ty {
1582 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1583 write!(f, "type({})", pprust::ty_to_string(self))
1587 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1588 pub struct BareFnTy {
1589 pub unsafety: Unsafety,
1591 pub generic_params: Vec<GenericParam>,
1592 pub decl: P<FnDecl>,
1595 /// The different kinds of types recognized by the compiler.
1596 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1598 /// A variable-length slice (`[T]`).
1600 /// A fixed length array (`[T; n]`).
1601 Array(P<Ty>, AnonConst),
1602 /// A raw pointer (`*const T` or `*mut T`).
1604 /// A reference (`&'a T` or `&'a mut T`).
1605 Rptr(Option<Lifetime>, MutTy),
1606 /// A bare function (e.g., `fn(usize) -> bool`).
1607 BareFn(P<BareFnTy>),
1608 /// The never type (`!`).
1610 /// A tuple (`(A, B, C, D,...)`).
1612 /// A path (`module::module::...::Type`), optionally
1613 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1615 /// Type parameters are stored in the `Path` itself.
1616 Path(Option<QSelf>, Path),
1617 /// A trait object type `Bound1 + Bound2 + Bound3`
1618 /// where `Bound` is a trait or a lifetime.
1619 TraitObject(GenericBounds, TraitObjectSyntax),
1620 /// An `impl Bound1 + Bound2 + Bound3` type
1621 /// where `Bound` is a trait or a lifetime.
1623 /// The `NodeId` exists to prevent lowering from having to
1624 /// generate `NodeId`s on the fly, which would complicate
1625 /// the generation of `existential type` items significantly.
1626 ImplTrait(NodeId, GenericBounds),
1627 /// No-op; kept solely so that we can pretty-print faithfully.
1631 /// This means the type should be inferred instead of it having been
1632 /// specified. This can appear anywhere in a type.
1634 /// Inferred type of a `self` or `&self` argument in a method.
1636 /// A macro in the type position.
1638 /// Placeholder for a kind that has failed to be defined.
1643 pub fn is_implicit_self(&self) -> bool {
1644 if let TyKind::ImplicitSelf = *self {
1651 pub fn is_unit(&self) -> bool {
1652 if let TyKind::Tup(ref tys) = *self {
1660 /// Syntax used to declare a trait object.
1661 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1662 pub enum TraitObjectSyntax {
1667 /// Inline assembly dialect.
1669 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1670 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1671 pub enum AsmDialect {
1676 /// Inline assembly.
1678 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1679 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1680 pub struct InlineAsmOutput {
1681 pub constraint: Symbol,
1684 pub is_indirect: bool,
1687 /// Inline assembly.
1689 /// E.g., `asm!("NOP");`.
1690 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1691 pub struct InlineAsm {
1693 pub asm_str_style: StrStyle,
1694 pub outputs: Vec<InlineAsmOutput>,
1695 pub inputs: Vec<(Symbol, P<Expr>)>,
1696 pub clobbers: Vec<Symbol>,
1698 pub alignstack: bool,
1699 pub dialect: AsmDialect,
1700 pub ctxt: SyntaxContext,
1703 /// An argument in a function header.
1705 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1706 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1713 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1715 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1716 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1718 /// `self`, `mut self`
1720 /// `&'lt self`, `&'lt mut self`
1721 Region(Option<Lifetime>, Mutability),
1722 /// `self: TYPE`, `mut self: TYPE`
1723 Explicit(P<Ty>, Mutability),
1726 pub type ExplicitSelf = Spanned<SelfKind>;
1729 pub fn to_self(&self) -> Option<ExplicitSelf> {
1730 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1731 if ident.name == keywords::SelfLower.name() {
1732 return match self.ty.node {
1733 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1734 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1735 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1738 self.pat.span.to(self.ty.span),
1739 SelfKind::Explicit(self.ty.clone(), mutbl),
1747 pub fn is_self(&self) -> bool {
1748 if let PatKind::Ident(_, ident, _) = self.pat.node {
1749 ident.name == keywords::SelfLower.name()
1755 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1756 let span = eself.span.to(eself_ident.span);
1757 let infer_ty = P(Ty {
1759 node: TyKind::ImplicitSelf,
1762 let arg = |mutbl, ty| Arg {
1765 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1772 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1773 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1774 SelfKind::Region(lt, mutbl) => arg(
1775 Mutability::Immutable,
1792 /// Header (not the body) of a function declaration.
1794 /// E.g., `fn foo(bar: baz)`.
1795 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1797 pub inputs: Vec<Arg>,
1798 pub output: FunctionRetTy,
1803 pub fn get_self(&self) -> Option<ExplicitSelf> {
1804 self.inputs.get(0).and_then(Arg::to_self)
1806 pub fn has_self(&self) -> bool {
1807 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1811 /// Is the trait definition an auto trait?
1812 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1818 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1824 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1828 return_impl_trait_id: NodeId,
1834 pub fn is_async(self) -> bool {
1835 if let IsAsync::Async { .. } = self {
1842 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1843 pub fn opt_return_id(self) -> Option<NodeId> {
1846 return_impl_trait_id,
1848 } => Some(return_impl_trait_id),
1849 IsAsync::NotAsync => None,
1854 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1855 pub enum Constness {
1860 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1861 pub enum Defaultness {
1866 impl fmt::Display for Unsafety {
1867 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1870 Unsafety::Normal => "normal",
1871 Unsafety::Unsafe => "unsafe",
1878 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1879 pub enum ImplPolarity {
1880 /// `impl Trait for Type`
1882 /// `impl !Trait for Type`
1886 impl fmt::Debug for ImplPolarity {
1887 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1889 ImplPolarity::Positive => "positive".fmt(f),
1890 ImplPolarity::Negative => "negative".fmt(f),
1895 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1896 pub enum FunctionRetTy {
1897 /// Return type is not specified.
1899 /// Functions default to `()` and closures default to inference.
1900 /// Span points to where return type would be inserted.
1902 /// Everything else.
1906 impl FunctionRetTy {
1907 pub fn span(&self) -> Span {
1909 FunctionRetTy::Default(span) => span,
1910 FunctionRetTy::Ty(ref ty) => ty.span,
1915 /// Module declaration.
1917 /// E.g., `mod foo;` or `mod foo { .. }`.
1918 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1920 /// A span from the first token past `{` to the last token until `}`.
1921 /// For `mod foo;`, the inner span ranges from the first token
1922 /// to the last token in the external file.
1924 pub items: Vec<P<Item>>,
1925 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
1929 /// Foreign module declaration.
1931 /// E.g., `extern { .. }` or `extern C { .. }`.
1932 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1933 pub struct ForeignMod {
1935 pub items: Vec<ForeignItem>,
1938 /// Global inline assembly.
1940 /// Also known as "module-level assembly" or "file-scoped assembly".
1941 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1942 pub struct GlobalAsm {
1944 pub ctxt: SyntaxContext,
1947 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1948 pub struct EnumDef {
1949 pub variants: Vec<Variant>,
1952 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1953 pub struct Variant_ {
1955 pub attrs: Vec<Attribute>,
1956 pub data: VariantData,
1957 /// Explicit discriminant, e.g., `Foo = 1`.
1958 pub disr_expr: Option<AnonConst>,
1961 pub type Variant = Spanned<Variant_>;
1963 /// Part of `use` item to the right of its prefix.
1964 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1965 pub enum UseTreeKind {
1966 /// `use prefix` or `use prefix as rename`
1968 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1970 Simple(Option<Ident>, NodeId, NodeId),
1971 /// `use prefix::{...}`
1972 Nested(Vec<(UseTree, NodeId)>),
1977 /// A tree of paths sharing common prefixes.
1978 /// Used in `use` items both at top-level and inside of braces in import groups.
1979 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1980 pub struct UseTree {
1982 pub kind: UseTreeKind,
1987 pub fn ident(&self) -> Ident {
1989 UseTreeKind::Simple(Some(rename), ..) => rename,
1990 UseTreeKind::Simple(None, ..) => {
1994 .expect("empty prefix in a simple import")
1997 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2002 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2003 /// are contained as statements within items. These two cases need to be
2004 /// distinguished for pretty-printing.
2005 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
2006 pub enum AttrStyle {
2012 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
2014 pub struct AttrId(pub usize);
2016 impl Idx for AttrId {
2017 fn new(idx: usize) -> Self {
2020 fn index(self) -> usize {
2025 /// Metadata associated with an item.
2026 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
2027 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2028 pub struct Attribute {
2030 pub style: AttrStyle,
2032 pub tokens: TokenStream,
2033 pub is_sugared_doc: bool,
2037 /// `TraitRef`s appear in impls.
2039 /// Resolve maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2040 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2041 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2042 /// same as the impl's node-id).
2043 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2044 pub struct TraitRef {
2049 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2050 pub struct PolyTraitRef {
2051 /// The `'a` in `<'a> Foo<&'a T>`
2052 pub bound_generic_params: Vec<GenericParam>,
2054 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2055 pub trait_ref: TraitRef,
2061 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2063 bound_generic_params: generic_params,
2064 trait_ref: TraitRef {
2066 ref_id: DUMMY_NODE_ID,
2073 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2074 pub enum CrateSugar {
2075 /// Source is `pub(crate)`.
2078 /// Source is (just) `crate`.
2082 pub type Visibility = Spanned<VisibilityKind>;
2084 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2085 pub enum VisibilityKind {
2088 Restricted { path: P<Path>, id: NodeId },
2092 impl VisibilityKind {
2093 pub fn is_pub(&self) -> bool {
2094 if let VisibilityKind::Public = *self {
2102 /// Field of a struct.
2104 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2105 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2106 pub struct StructField {
2108 pub ident: Option<Ident>,
2109 pub vis: Visibility,
2112 pub attrs: Vec<Attribute>,
2115 /// Fields and Ids of enum variants and structs
2117 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2118 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2119 /// One shared Id can be successfully used for these two purposes.
2120 /// Id of the whole enum lives in `Item`.
2122 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2123 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2124 /// the variant itself" from enum variants.
2125 /// Id of the whole struct lives in `Item`.
2126 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2127 pub enum VariantData {
2130 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2131 Struct(Vec<StructField>, NodeId),
2134 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2135 Tuple(Vec<StructField>, NodeId),
2138 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2143 pub fn fields(&self) -> &[StructField] {
2145 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2149 pub fn id(&self) -> NodeId {
2151 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2154 pub fn is_struct(&self) -> bool {
2155 if let VariantData::Struct(..) = *self {
2161 pub fn is_tuple(&self) -> bool {
2162 if let VariantData::Tuple(..) = *self {
2168 pub fn is_unit(&self) -> bool {
2169 if let VariantData::Unit(..) = *self {
2179 /// The name might be a dummy name in case of anonymous items.
2180 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2183 pub attrs: Vec<Attribute>,
2186 pub vis: Visibility,
2189 /// Original tokens this item was parsed from. This isn't necessarily
2190 /// available for all items, although over time more and more items should
2191 /// have this be `Some`. Right now this is primarily used for procedural
2192 /// macros, notably custom attributes.
2194 /// Note that the tokens here do not include the outer attributes, but will
2195 /// include inner attributes.
2196 pub tokens: Option<TokenStream>,
2200 /// Return the span that encompasses the attributes.
2201 pub fn span_with_attributes(&self) -> Span {
2202 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span()))
2206 /// A function header.
2208 /// All the information between the visibility and the name of the function is
2209 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2210 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2211 pub struct FnHeader {
2212 pub unsafety: Unsafety,
2213 pub asyncness: IsAsync,
2214 pub constness: Spanned<Constness>,
2218 impl Default for FnHeader {
2219 fn default() -> FnHeader {
2221 unsafety: Unsafety::Normal,
2222 asyncness: IsAsync::NotAsync,
2223 constness: dummy_spanned(Constness::NotConst),
2229 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2231 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2233 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2234 ExternCrate(Option<Name>),
2235 /// A use declaration (`use` or `pub use`) item.
2237 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2239 /// A static item (`static` or `pub static`).
2241 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2242 Static(P<Ty>, Mutability, P<Expr>),
2243 /// A constant item (`const` or `pub const`).
2245 /// E.g., `const FOO: i32 = 42;`.
2246 Const(P<Ty>, P<Expr>),
2247 /// A function declaration (`fn` or `pub fn`).
2249 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2250 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2251 /// A module declaration (`mod` or `pub mod`).
2253 /// E.g., `mod foo;` or `mod foo { .. }`.
2255 /// An external module (`extern` or `pub extern`).
2257 /// E.g., `extern {}` or `extern "C" {}`.
2258 ForeignMod(ForeignMod),
2259 /// Module-level inline assembly (from `global_asm!()`).
2260 GlobalAsm(P<GlobalAsm>),
2261 /// A type alias (`type` or `pub type`).
2263 /// E.g., `type Foo = Bar<u8>;`.
2264 Ty(P<Ty>, Generics),
2265 /// An existential type declaration (`existential type`).
2267 /// E.g., `existential type Foo: Bar + Boo;`.
2268 Existential(GenericBounds, Generics),
2269 /// An enum definition (`enum` or `pub enum`).
2271 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2272 Enum(EnumDef, Generics),
2273 /// A struct definition (`struct` or `pub struct`).
2275 /// E.g., `struct Foo<A> { x: A }`.
2276 Struct(VariantData, Generics),
2277 /// A union definition (`union` or `pub union`).
2279 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2280 Union(VariantData, Generics),
2281 /// A Trait declaration (`trait` or `pub trait`).
2283 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2284 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2287 /// E.g., `trait Foo = Bar + Quux;`.
2288 TraitAlias(Generics, GenericBounds),
2289 /// An implementation.
2291 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2297 Option<TraitRef>, // (optional) trait this impl implements
2301 /// A macro invocation.
2303 /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2306 /// A macro definition.
2311 pub fn descriptive_variant(&self) -> &str {
2313 ItemKind::ExternCrate(..) => "extern crate",
2314 ItemKind::Use(..) => "use",
2315 ItemKind::Static(..) => "static item",
2316 ItemKind::Const(..) => "constant item",
2317 ItemKind::Fn(..) => "function",
2318 ItemKind::Mod(..) => "module",
2319 ItemKind::ForeignMod(..) => "foreign module",
2320 ItemKind::GlobalAsm(..) => "global asm",
2321 ItemKind::Ty(..) => "type alias",
2322 ItemKind::Existential(..) => "existential type",
2323 ItemKind::Enum(..) => "enum",
2324 ItemKind::Struct(..) => "struct",
2325 ItemKind::Union(..) => "union",
2326 ItemKind::Trait(..) => "trait",
2327 ItemKind::TraitAlias(..) => "trait alias",
2328 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2333 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2334 pub struct ForeignItem {
2336 pub attrs: Vec<Attribute>,
2337 pub node: ForeignItemKind,
2340 pub vis: Visibility,
2343 /// An item within an `extern` block.
2344 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2345 pub enum ForeignItemKind {
2346 /// A foreign function.
2347 Fn(P<FnDecl>, Generics),
2348 /// A foreign static item (`static ext: u8`), with optional mutability.
2349 /// (The boolean is `true` for mutable items).
2350 Static(P<Ty>, bool),
2353 /// A macro invocation.
2357 impl ForeignItemKind {
2358 pub fn descriptive_variant(&self) -> &str {
2360 ForeignItemKind::Fn(..) => "foreign function",
2361 ForeignItemKind::Static(..) => "foreign static item",
2362 ForeignItemKind::Ty => "foreign type",
2363 ForeignItemKind::Macro(..) => "macro in foreign module",
2373 // Are ASTs encodable?
2375 fn check_asts_encodable() {
2376 fn assert_encodable<T: serialize::Encodable>() {}
2377 assert_encodable::<Crate>();