1 // The Rust abstract syntax tree.
3 pub use GenericArgs::*;
4 pub use UnsafeSource::*;
5 pub use crate::util::parser::ExprPrecedence;
7 use crate::parse::token::{self, DelimToken};
9 use crate::source_map::{dummy_spanned, respan, Spanned};
10 use crate::tokenstream::TokenStream;
12 use rustc_target::spec::abi::Abi;
13 pub use rustc_target::abi::FloatTy;
15 use syntax_pos::{Span, DUMMY_SP, ExpnId};
16 use syntax_pos::symbol::{kw, sym, Symbol};
17 pub use syntax_pos::symbol::{Ident, Symbol as Name};
19 use rustc_index::vec::Idx;
20 #[cfg(target_arch = "x86_64")]
21 use rustc_data_structures::static_assert_size;
22 use rustc_data_structures::fx::FxHashSet;
23 use rustc_data_structures::sync::Lrc;
24 use rustc_data_structures::thin_vec::ThinVec;
25 use rustc_serialize::{self, Decoder, Encoder};
31 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
36 impl fmt::Debug for Label {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 write!(f, "label({:?})", self.ident)
42 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
48 impl fmt::Debug for Lifetime {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 impl fmt::Display for Lifetime {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 write!(f, "{}", self.ident.name.as_str())
65 /// A "Path" is essentially Rust's notion of a name.
67 /// It's represented as a sequence of identifiers,
68 /// along with a bunch of supporting information.
70 /// E.g., `std::cmp::PartialEq`.
71 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
74 /// The segments in the path: the things separated by `::`.
75 /// Global paths begin with `kw::PathRoot`.
76 pub segments: Vec<PathSegment>,
79 impl PartialEq<Symbol> for Path {
80 fn eq(&self, symbol: &Symbol) -> bool {
81 self.segments.len() == 1 && {
82 self.segments[0].ident.name == *symbol
88 // Convert a span and an identifier to the corresponding
90 pub fn from_ident(ident: Ident) -> Path {
92 segments: vec![PathSegment::from_ident(ident)],
97 pub fn is_global(&self) -> bool {
98 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
102 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
104 /// E.g., `std`, `String` or `Box<T>`.
105 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
106 pub struct PathSegment {
107 /// The identifier portion of this path segment.
112 /// Type/lifetime parameters attached to this path. They come in
113 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
114 /// `None` means that no parameter list is supplied (`Path`),
115 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
116 /// but it can be empty (`Path<>`).
117 /// `P` is used as a size optimization for the common case with no parameters.
118 pub args: Option<P<GenericArgs>>,
122 pub fn from_ident(ident: Ident) -> Self {
123 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
125 pub fn path_root(span: Span) -> Self {
126 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
130 /// The arguments of a path segment.
132 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
133 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
134 pub enum GenericArgs {
135 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
136 AngleBracketed(AngleBracketedArgs),
137 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
138 Parenthesized(ParenthesizedArgs),
142 pub fn is_parenthesized(&self) -> bool {
144 Parenthesized(..) => true,
149 pub fn is_angle_bracketed(&self) -> bool {
151 AngleBracketed(..) => true,
156 pub fn span(&self) -> Span {
158 AngleBracketed(ref data) => data.span,
159 Parenthesized(ref data) => data.span,
164 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
165 pub enum GenericArg {
172 pub fn span(&self) -> Span {
174 GenericArg::Lifetime(lt) => lt.ident.span,
175 GenericArg::Type(ty) => ty.span,
176 GenericArg::Const(ct) => ct.value.span,
181 /// A path like `Foo<'a, T>`.
182 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
183 pub struct AngleBracketedArgs {
184 /// The overall span.
186 /// The arguments for this path segment.
187 pub args: Vec<GenericArg>,
188 /// Constraints on associated types, if any.
189 /// E.g., `Foo<A = Bar, B: Baz>`.
190 pub constraints: Vec<AssocTyConstraint>,
193 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
194 fn into(self) -> Option<P<GenericArgs>> {
195 Some(P(GenericArgs::AngleBracketed(self)))
199 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
200 fn into(self) -> Option<P<GenericArgs>> {
201 Some(P(GenericArgs::Parenthesized(self)))
205 /// A path like `Foo(A, B) -> C`.
206 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
207 pub struct ParenthesizedArgs {
212 pub inputs: Vec<P<Ty>>,
215 pub output: Option<P<Ty>>,
218 impl ParenthesizedArgs {
219 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
222 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
228 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
230 use rustc_index::vec::Idx;
231 rustc_index::newtype_index! {
234 DEBUG_FORMAT = "NodeId({})"
239 pub use node_id_inner::NodeId;
242 pub fn placeholder_from_expn_id(expn_id: ExpnId) -> Self {
243 NodeId::from_u32(expn_id.as_u32())
246 pub fn placeholder_to_expn_id(self) -> ExpnId {
247 ExpnId::from_u32(self.as_u32())
251 impl fmt::Display for NodeId {
252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253 fmt::Display::fmt(&self.as_u32(), f)
257 impl rustc_serialize::UseSpecializedEncodable for NodeId {
258 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
259 s.emit_u32(self.as_u32())
263 impl rustc_serialize::UseSpecializedDecodable for NodeId {
264 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
265 d.read_u32().map(NodeId::from_u32)
269 /// `NodeId` used to represent the root of the crate.
270 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
272 /// When parsing and doing expansions, we initially give all AST nodes this AST
273 /// node value. Then later, in the renumber pass, we renumber them to have
274 /// small, positive ids.
275 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
277 /// A modifier on a bound, currently this is only used for `?Sized`, where the
278 /// modifier is `Maybe`. Negative bounds should also be handled here.
279 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
280 pub enum TraitBoundModifier {
285 /// The AST represents all type param bounds as types.
286 /// `typeck::collect::compute_bounds` matches these against
287 /// the "special" built-in traits (see `middle::lang_items`) and
288 /// detects `Copy`, `Send` and `Sync`.
289 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
290 pub enum GenericBound {
291 Trait(PolyTraitRef, TraitBoundModifier),
296 pub fn span(&self) -> Span {
298 &GenericBound::Trait(ref t, ..) => t.span,
299 &GenericBound::Outlives(ref l) => l.ident.span,
304 pub type GenericBounds = Vec<GenericBound>;
306 /// Specifies the enforced ordering for generic parameters. In the future,
307 /// if we wanted to relax this order, we could override `PartialEq` and
308 /// `PartialOrd`, to allow the kinds to be unordered.
309 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
310 pub enum ParamKindOrd {
316 impl fmt::Display for ParamKindOrd {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319 ParamKindOrd::Lifetime => "lifetime".fmt(f),
320 ParamKindOrd::Type => "type".fmt(f),
321 ParamKindOrd::Const => "const".fmt(f),
326 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
327 pub enum GenericParamKind {
328 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
330 Type { default: Option<P<Ty>> },
334 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
335 pub struct GenericParam {
338 pub attrs: ThinVec<Attribute>,
339 pub bounds: GenericBounds,
340 pub is_placeholder: bool,
341 pub kind: GenericParamKind,
344 /// Represents lifetime, type and const parameters attached to a declaration of
345 /// a function, enum, trait, etc.
346 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
347 pub struct Generics {
348 pub params: Vec<GenericParam>,
349 pub where_clause: WhereClause,
353 impl Default for Generics {
354 /// Creates an instance of `Generics`.
355 fn default() -> Generics {
358 where_clause: WhereClause {
359 predicates: Vec::new(),
367 /// A where-clause in a definition.
368 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
369 pub struct WhereClause {
370 pub predicates: Vec<WherePredicate>,
374 /// A single predicate in a where-clause.
375 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
376 pub enum WherePredicate {
377 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
378 BoundPredicate(WhereBoundPredicate),
379 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
380 RegionPredicate(WhereRegionPredicate),
381 /// An equality predicate (unsupported).
382 EqPredicate(WhereEqPredicate),
385 impl WherePredicate {
386 pub fn span(&self) -> Span {
388 &WherePredicate::BoundPredicate(ref p) => p.span,
389 &WherePredicate::RegionPredicate(ref p) => p.span,
390 &WherePredicate::EqPredicate(ref p) => p.span,
397 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
398 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
399 pub struct WhereBoundPredicate {
401 /// Any generics from a `for` binding.
402 pub bound_generic_params: Vec<GenericParam>,
403 /// The type being bounded.
404 pub bounded_ty: P<Ty>,
405 /// Trait and lifetime bounds (`Clone + Send + 'static`).
406 pub bounds: GenericBounds,
409 /// A lifetime predicate.
411 /// E.g., `'a: 'b + 'c`.
412 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
413 pub struct WhereRegionPredicate {
415 pub lifetime: Lifetime,
416 pub bounds: GenericBounds,
419 /// An equality predicate (unsupported).
422 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
423 pub struct WhereEqPredicate {
430 /// The set of `MetaItem`s that define the compilation environment of the crate,
431 /// used to drive conditional compilation.
432 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
434 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
437 pub attrs: Vec<Attribute>,
441 /// Possible values inside of compile-time attribute lists.
443 /// E.g., the '..' in `#[name(..)]`.
444 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
445 pub enum NestedMetaItem {
446 /// A full MetaItem, for recursive meta items.
450 /// E.g., `"foo"`, `64`, `true`.
454 /// A spanned compile-time attribute item.
456 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
457 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
458 pub struct MetaItem {
460 pub kind: MetaItemKind,
464 /// A compile-time attribute item.
466 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
467 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
468 pub enum MetaItemKind {
471 /// E.g., `test` as in `#[test]`.
475 /// E.g., `derive(..)` as in `#[derive(..)]`.
476 List(Vec<NestedMetaItem>),
477 /// Name value meta item.
479 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
483 /// A block (`{ .. }`).
485 /// E.g., `{ .. }` as in `fn foo() { .. }`.
486 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
488 /// The statements in the block.
489 pub stmts: Vec<Stmt>,
491 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
492 pub rules: BlockCheckMode,
496 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
504 /// Attempt reparsing the pattern as a type.
505 /// This is intended for use by diagnostics.
506 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
507 let kind = match &self.kind {
508 // In a type expression `_` is an inference variable.
509 PatKind::Wild => TyKind::Infer,
510 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
511 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
512 TyKind::Path(None, Path::from_ident(*ident))
514 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
515 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
516 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
517 PatKind::Ref(pat, mutbl) => pat
519 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
520 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
521 // when `P` can be reparsed as a type `T`.
522 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
523 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
524 // assuming `T0` to `Tn` are all syntactically valid as types.
525 PatKind::Tuple(pats) => {
526 let mut tys = Vec::with_capacity(pats.len());
527 // FIXME(#48994) - could just be collected into an Option<Vec>
529 tys.push(pat.to_ty()?);
543 /// Walk top-down and call `it` in each place where a pattern occurs
544 /// starting with the root pattern `walk` is called on. If `it` returns
545 /// false then we will descend no further but siblings will be processed.
546 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
552 PatKind::Ident(_, _, Some(p)) => p.walk(it),
553 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
554 PatKind::TupleStruct(_, s)
557 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
560 | PatKind::Paren(s) => s.walk(it),
567 | PatKind::Mac(_) => {},
571 /// Is this a `..` pattern?
572 pub fn is_rest(&self) -> bool {
574 PatKind::Rest => true,
580 /// A single field in a struct pattern
582 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
583 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
584 /// except is_shorthand is true
585 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
586 pub struct FieldPat {
587 /// The identifier for the field
589 /// The pattern the field is destructured to
591 pub is_shorthand: bool,
592 pub attrs: ThinVec<Attribute>,
595 pub is_placeholder: bool,
598 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
599 pub enum BindingMode {
604 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
606 Included(RangeSyntax),
610 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
611 pub enum RangeSyntax {
616 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
618 /// Represents a wildcard pattern (`_`).
621 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
622 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
623 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
624 /// during name resolution.
625 Ident(BindingMode, Ident, Option<P<Pat>>),
627 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
628 /// The `bool` is `true` in the presence of a `..`.
629 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
631 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
632 TupleStruct(Path, Vec<P<Pat>>),
634 /// An or-pattern `A | B | C`.
635 /// Invariant: `pats.len() >= 2`.
638 /// A possibly qualified path pattern.
639 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
640 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
641 /// only legally refer to associated constants.
642 Path(Option<QSelf>, Path),
644 /// A tuple pattern (`(a, b)`).
650 /// A reference pattern (e.g., `&mut (a, b)`).
651 Ref(P<Pat>, Mutability),
656 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
657 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
659 /// A slice pattern `[a, b, c]`.
662 /// A rest pattern `..`.
664 /// Syntactically it is valid anywhere.
666 /// Semantically however, it only has meaning immediately inside:
667 /// - a slice pattern: `[a, .., b]`,
668 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
669 /// - a tuple pattern: `(a, .., b)`,
670 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
672 /// In all of these cases, an additional restriction applies,
673 /// only one rest pattern may occur in the pattern sequences.
676 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
679 /// A macro pattern; pre-expansion.
684 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
686 pub enum Mutability {
691 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
693 /// The `+` operator (addition)
695 /// The `-` operator (subtraction)
697 /// The `*` operator (multiplication)
699 /// The `/` operator (division)
701 /// The `%` operator (modulus)
703 /// The `&&` operator (logical and)
705 /// The `||` operator (logical or)
707 /// The `^` operator (bitwise xor)
709 /// The `&` operator (bitwise and)
711 /// The `|` operator (bitwise or)
713 /// The `<<` operator (shift left)
715 /// The `>>` operator (shift right)
717 /// The `==` operator (equality)
719 /// The `<` operator (less than)
721 /// The `<=` operator (less than or equal to)
723 /// The `!=` operator (not equal to)
725 /// The `>=` operator (greater than or equal to)
727 /// The `>` operator (greater than)
732 pub fn to_string(&self) -> &'static str {
755 pub fn lazy(&self) -> bool {
757 BinOpKind::And | BinOpKind::Or => true,
762 pub fn is_shift(&self) -> bool {
764 BinOpKind::Shl | BinOpKind::Shr => true,
769 pub fn is_comparison(&self) -> bool {
772 Eq | Lt | Le | Ne | Gt | Ge => true,
773 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
777 /// Returns `true` if the binary operator takes its arguments by value
778 pub fn is_by_value(&self) -> bool {
779 !self.is_comparison()
783 pub type BinOp = Spanned<BinOpKind>;
785 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
787 /// The `*` operator for dereferencing
789 /// The `!` operator for logical inversion
791 /// The `-` operator for negation
796 /// Returns `true` if the unary operator takes its argument by value
797 pub fn is_by_value(u: UnOp) -> bool {
799 UnOp::Neg | UnOp::Not => true,
804 pub fn to_string(op: UnOp) -> &'static str {
814 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
822 pub fn add_trailing_semicolon(mut self) -> Self {
823 self.kind = match self.kind {
824 StmtKind::Expr(expr) => StmtKind::Semi(expr),
825 StmtKind::Mac(mac) => {
826 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
833 pub fn is_item(&self) -> bool {
835 StmtKind::Item(_) => true,
840 pub fn is_expr(&self) -> bool {
842 StmtKind::Expr(_) => true,
848 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
850 /// A local (let) binding.
853 /// An item definition.
856 /// Expr without trailing semi-colon.
858 /// Expr with a trailing semi-colon.
861 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
864 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
865 pub enum MacStmtStyle {
866 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
867 /// `foo!(...);`, `foo![...];`).
869 /// The macro statement had braces (e.g., `foo! { ... }`).
871 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
872 /// `foo!(...)`). All of these will end up being converted into macro
877 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
878 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
882 pub ty: Option<P<Ty>>,
883 /// Initializer expression to set the value, if any.
884 pub init: Option<P<Expr>>,
886 pub attrs: ThinVec<Attribute>,
889 /// An arm of a 'match'.
891 /// E.g., `0..=10 => { println!("match!") }` as in
895 /// 0..=10 => { println!("match!") },
896 /// _ => { println!("no match!") },
899 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
901 pub attrs: Vec<Attribute>,
903 pub guard: Option<P<Expr>>,
907 pub is_placeholder: bool,
910 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
915 pub is_shorthand: bool,
916 pub attrs: ThinVec<Attribute>,
918 pub is_placeholder: bool,
921 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
922 pub enum BlockCheckMode {
924 Unsafe(UnsafeSource),
927 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
928 pub enum UnsafeSource {
933 /// A constant (expression) that's not an item or associated item,
934 /// but needs its own `DefId` for type-checking, const-eval, etc.
935 /// These are usually found nested inside types (e.g., array lengths)
936 /// or expressions (e.g., repeat counts), and also used to define
937 /// explicit discriminant values for enum variants.
938 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
939 pub struct AnonConst {
945 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
950 pub attrs: ThinVec<Attribute>,
953 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
954 #[cfg(target_arch = "x86_64")]
955 static_assert_size!(Expr, 96);
958 /// Returns `true` if this expression would be valid somewhere that expects a value;
959 /// for example, an `if` condition.
960 pub fn returns(&self) -> bool {
961 if let ExprKind::Block(ref block, _) = self.kind {
962 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
964 Some(&StmtKind::Expr(_)) => true,
965 Some(&StmtKind::Semi(ref expr)) => {
966 if let ExprKind::Ret(_) = expr.kind {
967 // Last statement is explicit return.
973 // This is a block that doesn't end in either an implicit or explicit return.
977 // This is not a block, it is a value.
982 fn to_bound(&self) -> Option<GenericBound> {
984 ExprKind::Path(None, path) => Some(GenericBound::Trait(
985 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
986 TraitBoundModifier::None,
992 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
993 let kind = match &self.kind {
994 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
995 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
996 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
997 ExprKind::AddrOf(mutbl, expr) => expr
999 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
1000 ExprKind::Repeat(expr, expr_len) => {
1001 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1003 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1004 ExprKind::Tup(exprs) => {
1007 .map(|expr| expr.to_ty())
1008 .collect::<Option<Vec<_>>>()?;
1011 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1012 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1013 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1028 pub fn precedence(&self) -> ExprPrecedence {
1030 ExprKind::Box(_) => ExprPrecedence::Box,
1031 ExprKind::Array(_) => ExprPrecedence::Array,
1032 ExprKind::Call(..) => ExprPrecedence::Call,
1033 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1034 ExprKind::Tup(_) => ExprPrecedence::Tup,
1035 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1036 ExprKind::Unary(..) => ExprPrecedence::Unary,
1037 ExprKind::Lit(_) => ExprPrecedence::Lit,
1038 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1039 ExprKind::Let(..) => ExprPrecedence::Let,
1040 ExprKind::If(..) => ExprPrecedence::If,
1041 ExprKind::While(..) => ExprPrecedence::While,
1042 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1043 ExprKind::Loop(..) => ExprPrecedence::Loop,
1044 ExprKind::Match(..) => ExprPrecedence::Match,
1045 ExprKind::Closure(..) => ExprPrecedence::Closure,
1046 ExprKind::Block(..) => ExprPrecedence::Block,
1047 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1048 ExprKind::Async(..) => ExprPrecedence::Async,
1049 ExprKind::Await(..) => ExprPrecedence::Await,
1050 ExprKind::Assign(..) => ExprPrecedence::Assign,
1051 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1052 ExprKind::Field(..) => ExprPrecedence::Field,
1053 ExprKind::Index(..) => ExprPrecedence::Index,
1054 ExprKind::Range(..) => ExprPrecedence::Range,
1055 ExprKind::Path(..) => ExprPrecedence::Path,
1056 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1057 ExprKind::Break(..) => ExprPrecedence::Break,
1058 ExprKind::Continue(..) => ExprPrecedence::Continue,
1059 ExprKind::Ret(..) => ExprPrecedence::Ret,
1060 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1061 ExprKind::Mac(..) => ExprPrecedence::Mac,
1062 ExprKind::Struct(..) => ExprPrecedence::Struct,
1063 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1064 ExprKind::Paren(..) => ExprPrecedence::Paren,
1065 ExprKind::Try(..) => ExprPrecedence::Try,
1066 ExprKind::Yield(..) => ExprPrecedence::Yield,
1067 ExprKind::Err => ExprPrecedence::Err,
1072 /// Limit types of a range (inclusive or exclusive)
1073 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1074 pub enum RangeLimits {
1075 /// Inclusive at the beginning, exclusive at the end
1077 /// Inclusive at the beginning and end
1081 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1083 /// A `box x` expression.
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 /// A type ascription (e.g., `42: usize`).
1115 Type(P<Expr>, P<Ty>),
1116 /// A `let pat = expr` expression that is only semantically allowed in the condition
1117 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1118 Let(P<Pat>, P<Expr>),
1119 /// An `if` block, with an optional `else` block.
1121 /// `if expr { block } else { expr }`
1122 If(P<Expr>, P<Block>, Option<P<Expr>>),
1123 /// A while loop, with an optional label.
1125 /// `'label: while expr { block }`
1126 While(P<Expr>, P<Block>, Option<Label>),
1127 /// A `for` loop, with an optional label.
1129 /// `'label: for pat in expr { block }`
1131 /// This is desugared to a combination of `loop` and `match` expressions.
1132 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1133 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1135 /// `'label: loop { block }`
1136 Loop(P<Block>, Option<Label>),
1137 /// A `match` block.
1138 Match(P<Expr>, Vec<Arm>),
1139 /// A closure (e.g., `move |a, b, c| a + b + c`).
1141 /// The final span is the span of the argument block `|...|`.
1142 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1143 /// A block (`'label: { ... }`).
1144 Block(P<Block>, Option<Label>),
1145 /// An async block (`async move { ... }`).
1147 /// The `NodeId` is the `NodeId` for the closure that results from
1148 /// desugaring an async block, just like the NodeId field in the
1149 /// `IsAsync` enum. This is necessary in order to create a def for the
1150 /// closure which can be used as a parent of any child defs. Defs
1151 /// created during lowering cannot be made the parent of any other
1152 /// preexisting defs.
1153 Async(CaptureBy, NodeId, P<Block>),
1154 /// An await expression (`my_future.await`).
1157 /// A try block (`try { ... }`).
1160 /// An assignment (`a = foo()`).
1161 Assign(P<Expr>, P<Expr>),
1162 /// An assignment with an operator.
1165 AssignOp(BinOp, P<Expr>, P<Expr>),
1166 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1167 Field(P<Expr>, Ident),
1168 /// An indexing operation (e.g., `foo[2]`).
1169 Index(P<Expr>, P<Expr>),
1170 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1171 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1173 /// Variable reference, possibly containing `::` and/or type
1174 /// parameters (e.g., `foo::bar::<baz>`).
1176 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1177 Path(Option<QSelf>, Path),
1179 /// A referencing operation (`&a` or `&mut a`).
1180 AddrOf(Mutability, P<Expr>),
1181 /// A `break`, with an optional label to break, and an optional expression.
1182 Break(Option<Label>, Option<P<Expr>>),
1183 /// A `continue`, with an optional label.
1184 Continue(Option<Label>),
1185 /// A `return`, with an optional value to be returned.
1186 Ret(Option<P<Expr>>),
1188 /// Output of the `asm!()` macro.
1189 InlineAsm(P<InlineAsm>),
1191 /// A macro invocation; pre-expansion.
1194 /// A struct literal expression.
1196 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1197 /// where `base` is the `Option<Expr>`.
1198 Struct(Path, Vec<Field>, Option<P<Expr>>),
1200 /// An array literal constructed from one repeated element.
1202 /// E.g., `[1; 5]`. The expression is the element to be
1203 /// repeated; the constant is the number of times to repeat it.
1204 Repeat(P<Expr>, AnonConst),
1206 /// No-op: used solely so we can pretty-print faithfully.
1209 /// A try expression (`expr?`).
1212 /// A `yield`, with an optional value to be yielded.
1213 Yield(Option<P<Expr>>),
1215 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1219 /// The explicit `Self` type in a "qualified path". The actual
1220 /// path, including the trait and the associated item, is stored
1221 /// separately. `position` represents the index of the associated
1222 /// item qualified with this `Self` type.
1224 /// ```ignore (only-for-syntax-highlight)
1225 /// <Vec<T> as a::b::Trait>::AssociatedItem
1226 /// ^~~~~ ~~~~~~~~~~~~~~^
1229 /// <Vec<T>>::AssociatedItem
1233 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1237 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1238 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1239 /// 0`, this is an empty span.
1240 pub path_span: Span,
1241 pub position: usize,
1244 /// A capture clause.
1245 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1246 pub enum CaptureBy {
1251 /// The movability of a generator / closure literal.
1252 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1253 pub enum Movability {
1258 /// Represents a macro invocation. The `Path` indicates which macro
1259 /// is being invoked, and the vector of token-trees contains the source
1260 /// of the macro invocation.
1262 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1263 /// stored in the enclosing item.
1264 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1267 pub delim: MacDelimiter,
1268 pub tts: TokenStream,
1270 pub prior_type_ascription: Option<(Span, bool)>,
1273 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1274 pub enum MacDelimiter {
1281 pub fn stream(&self) -> TokenStream {
1287 crate fn to_token(self) -> DelimToken {
1289 MacDelimiter::Parenthesis => DelimToken::Paren,
1290 MacDelimiter::Bracket => DelimToken::Bracket,
1291 MacDelimiter::Brace => DelimToken::Brace,
1296 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1297 pub struct MacroDef {
1298 pub tokens: TokenStream,
1303 pub fn stream(&self) -> TokenStream {
1304 self.tokens.clone().into()
1308 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1310 /// A regular string, like `"foo"`.
1312 /// A raw string, like `r##"foo"##`.
1314 /// The value is the number of `#` symbols used.
1319 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1321 /// The original literal token as written in source code.
1322 pub token: token::Lit,
1323 /// The "semantic" representation of the literal lowered from the original tokens.
1324 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1325 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1330 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1331 pub enum LitIntType {
1339 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1340 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1342 /// A string literal (`"foo"`).
1343 Str(Symbol, StrStyle),
1344 /// A byte string (`b"foo"`).
1345 ByteStr(Lrc<Vec<u8>>),
1346 /// A byte char (`b'f'`).
1348 /// A character literal (`'a'`).
1350 /// An integer literal (`1`).
1351 Int(u128, LitIntType),
1352 /// A float literal (`1f64` or `1E10f64`).
1353 Float(Symbol, FloatTy),
1354 /// A float literal without a suffix (`1.0 or 1.0E10`).
1355 FloatUnsuffixed(Symbol),
1356 /// A boolean literal.
1358 /// Placeholder for a literal that wasn't well-formed in some way.
1363 /// Returns `true` if this literal is a string.
1364 pub fn is_str(&self) -> bool {
1366 LitKind::Str(..) => true,
1371 /// Returns `true` if this literal is byte literal string.
1372 pub fn is_bytestr(&self) -> bool {
1374 LitKind::ByteStr(_) => true,
1379 /// Returns `true` if this is a numeric literal.
1380 pub fn is_numeric(&self) -> bool {
1382 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1387 /// Returns `true` if this literal has no suffix.
1388 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1389 pub fn is_unsuffixed(&self) -> bool {
1391 // unsuffixed variants
1393 | LitKind::ByteStr(..)
1396 | LitKind::Int(_, LitIntType::Unsuffixed)
1397 | LitKind::FloatUnsuffixed(..)
1399 | LitKind::Err(..) => true,
1400 // suffixed variants
1401 LitKind::Int(_, LitIntType::Signed(..))
1402 | LitKind::Int(_, LitIntType::Unsigned(..))
1403 | LitKind::Float(..) => false,
1407 /// Returns `true` if this literal has a suffix.
1408 pub fn is_suffixed(&self) -> bool {
1409 !self.is_unsuffixed()
1413 // N.B., If you change this, you'll probably want to change the corresponding
1414 // type structure in `middle/ty.rs` as well.
1415 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1418 pub mutbl: Mutability,
1421 /// Represents a method's signature in a trait declaration,
1422 /// or in an implementation.
1423 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1424 pub struct MethodSig {
1425 pub header: FnHeader,
1426 pub decl: P<FnDecl>,
1429 /// Represents an item declaration within a trait declaration,
1430 /// possibly including a default implementation. A trait item is
1431 /// either required (meaning it doesn't have an implementation, just a
1432 /// signature) or provided (meaning it has a default implementation).
1433 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1434 pub struct TraitItem {
1437 pub attrs: Vec<Attribute>,
1438 pub generics: Generics,
1439 pub kind: TraitItemKind,
1441 /// See `Item::tokens` for what this is.
1442 pub tokens: Option<TokenStream>,
1445 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1446 pub enum TraitItemKind {
1447 Const(P<Ty>, Option<P<Expr>>),
1448 Method(MethodSig, Option<P<Block>>),
1449 Type(GenericBounds, Option<P<Ty>>),
1453 /// Represents anything within an `impl` block.
1454 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1455 pub struct ImplItem {
1458 pub vis: Visibility,
1459 pub defaultness: Defaultness,
1460 pub attrs: Vec<Attribute>,
1461 pub generics: Generics,
1462 pub kind: ImplItemKind,
1464 /// See `Item::tokens` for what this is.
1465 pub tokens: Option<TokenStream>,
1468 /// Represents various kinds of content within an `impl`.
1469 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1470 pub enum ImplItemKind {
1471 Const(P<Ty>, P<Expr>),
1472 Method(MethodSig, P<Block>),
1474 OpaqueTy(GenericBounds),
1478 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1488 impl fmt::Debug for IntTy {
1489 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1490 fmt::Display::fmt(self, f)
1494 impl fmt::Display for IntTy {
1495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1496 write!(f, "{}", self.ty_to_string())
1501 pub fn ty_to_string(&self) -> &'static str {
1503 IntTy::Isize => "isize",
1505 IntTy::I16 => "i16",
1506 IntTy::I32 => "i32",
1507 IntTy::I64 => "i64",
1508 IntTy::I128 => "i128",
1512 pub fn to_symbol(&self) -> Symbol {
1514 IntTy::Isize => sym::isize,
1515 IntTy::I8 => sym::i8,
1516 IntTy::I16 => sym::i16,
1517 IntTy::I32 => sym::i32,
1518 IntTy::I64 => sym::i64,
1519 IntTy::I128 => sym::i128,
1523 pub fn val_to_string(&self, val: i128) -> String {
1524 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1525 // are parsed as `u128`, so we wouldn't want to print an extra negative
1527 format!("{}{}", val as u128, self.ty_to_string())
1530 pub fn bit_width(&self) -> Option<usize> {
1532 IntTy::Isize => return None,
1542 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1553 pub fn ty_to_string(&self) -> &'static str {
1555 UintTy::Usize => "usize",
1557 UintTy::U16 => "u16",
1558 UintTy::U32 => "u32",
1559 UintTy::U64 => "u64",
1560 UintTy::U128 => "u128",
1564 pub fn to_symbol(&self) -> Symbol {
1566 UintTy::Usize => sym::usize,
1567 UintTy::U8 => sym::u8,
1568 UintTy::U16 => sym::u16,
1569 UintTy::U32 => sym::u32,
1570 UintTy::U64 => sym::u64,
1571 UintTy::U128 => sym::u128,
1575 pub fn val_to_string(&self, val: u128) -> String {
1576 format!("{}{}", val, self.ty_to_string())
1579 pub fn bit_width(&self) -> Option<usize> {
1581 UintTy::Usize => return None,
1586 UintTy::U128 => 128,
1591 impl fmt::Debug for UintTy {
1592 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1593 fmt::Display::fmt(self, f)
1597 impl fmt::Display for UintTy {
1598 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1599 write!(f, "{}", self.ty_to_string())
1603 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1604 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1605 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1606 pub struct AssocTyConstraint {
1609 pub kind: AssocTyConstraintKind,
1613 /// The kinds of an `AssocTyConstraint`.
1614 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1615 pub enum AssocTyConstraintKind {
1616 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1620 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1622 bounds: GenericBounds,
1626 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1633 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1634 pub struct BareFnTy {
1635 pub unsafety: Unsafety,
1637 pub generic_params: Vec<GenericParam>,
1638 pub decl: P<FnDecl>,
1641 /// The various kinds of type recognized by the compiler.
1642 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1644 /// A variable-length slice (`[T]`).
1646 /// A fixed length array (`[T; n]`).
1647 Array(P<Ty>, AnonConst),
1648 /// A raw pointer (`*const T` or `*mut T`).
1650 /// A reference (`&'a T` or `&'a mut T`).
1651 Rptr(Option<Lifetime>, MutTy),
1652 /// A bare function (e.g., `fn(usize) -> bool`).
1653 BareFn(P<BareFnTy>),
1654 /// The never type (`!`).
1656 /// A tuple (`(A, B, C, D,...)`).
1658 /// A path (`module::module::...::Type`), optionally
1659 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1661 /// Type parameters are stored in the `Path` itself.
1662 Path(Option<QSelf>, Path),
1663 /// A trait object type `Bound1 + Bound2 + Bound3`
1664 /// where `Bound` is a trait or a lifetime.
1665 TraitObject(GenericBounds, TraitObjectSyntax),
1666 /// An `impl Bound1 + Bound2 + Bound3` type
1667 /// where `Bound` is a trait or a lifetime.
1669 /// The `NodeId` exists to prevent lowering from having to
1670 /// generate `NodeId`s on the fly, which would complicate
1671 /// the generation of opaque `type Foo = impl Trait` items significantly.
1672 ImplTrait(NodeId, GenericBounds),
1673 /// No-op; kept solely so that we can pretty-print faithfully.
1677 /// This means the type should be inferred instead of it having been
1678 /// specified. This can appear anywhere in a type.
1680 /// Inferred type of a `self` or `&self` argument in a method.
1682 /// A macro in the type position.
1684 /// Placeholder for a kind that has failed to be defined.
1686 /// Placeholder for a `va_list`.
1691 pub fn is_implicit_self(&self) -> bool {
1692 if let TyKind::ImplicitSelf = *self {
1699 pub fn is_unit(&self) -> bool {
1700 if let TyKind::Tup(ref tys) = *self {
1708 /// Syntax used to declare a trait object.
1709 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1710 pub enum TraitObjectSyntax {
1715 /// Inline assembly dialect.
1717 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1718 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1719 pub enum AsmDialect {
1724 /// Inline assembly.
1726 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1727 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1728 pub struct InlineAsmOutput {
1729 pub constraint: Symbol,
1732 pub is_indirect: bool,
1735 /// Inline assembly.
1737 /// E.g., `asm!("NOP");`.
1738 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1739 pub struct InlineAsm {
1741 pub asm_str_style: StrStyle,
1742 pub outputs: Vec<InlineAsmOutput>,
1743 pub inputs: Vec<(Symbol, P<Expr>)>,
1744 pub clobbers: Vec<Symbol>,
1746 pub alignstack: bool,
1747 pub dialect: AsmDialect,
1750 /// A parameter in a function header.
1752 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1753 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1755 pub attrs: ThinVec<Attribute>,
1760 pub is_placeholder: bool,
1763 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1765 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1766 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1768 /// `self`, `mut self`
1770 /// `&'lt self`, `&'lt mut self`
1771 Region(Option<Lifetime>, Mutability),
1772 /// `self: TYPE`, `mut self: TYPE`
1773 Explicit(P<Ty>, Mutability),
1776 pub type ExplicitSelf = Spanned<SelfKind>;
1779 pub fn to_self(&self) -> Option<ExplicitSelf> {
1780 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
1781 if ident.name == kw::SelfLower {
1782 return match self.ty.kind {
1783 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1784 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
1785 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1788 self.pat.span.to(self.ty.span),
1789 SelfKind::Explicit(self.ty.clone(), mutbl),
1797 pub fn is_self(&self) -> bool {
1798 if let PatKind::Ident(_, ident, _) = self.pat.kind {
1799 ident.name == kw::SelfLower
1805 pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param {
1806 let span = eself.span.to(eself_ident.span);
1807 let infer_ty = P(Ty {
1809 kind: TyKind::ImplicitSelf,
1812 let param = |mutbl, ty| Param {
1816 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1822 is_placeholder: false
1825 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
1826 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
1827 SelfKind::Region(lt, mutbl) => param(
1828 Mutability::Immutable,
1845 /// A header (not the body) of a function declaration.
1847 /// E.g., `fn foo(bar: baz)`.
1848 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1850 pub inputs: Vec<Param>,
1851 pub output: FunctionRetTy,
1855 pub fn get_self(&self) -> Option<ExplicitSelf> {
1856 self.inputs.get(0).and_then(Param::to_self)
1858 pub fn has_self(&self) -> bool {
1859 self.inputs.get(0).map(Param::is_self).unwrap_or(false)
1861 pub fn c_variadic(&self) -> bool {
1862 self.inputs.last().map(|arg| match arg.ty.kind {
1863 TyKind::CVarArgs => true,
1869 /// Is the trait definition an auto trait?
1870 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1876 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1882 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1886 return_impl_trait_id: NodeId,
1892 pub fn is_async(self) -> bool {
1893 if let IsAsync::Async { .. } = self {
1900 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1901 pub fn opt_return_id(self) -> Option<NodeId> {
1904 return_impl_trait_id,
1906 } => Some(return_impl_trait_id),
1907 IsAsync::NotAsync => None,
1912 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1913 pub enum Constness {
1918 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1919 pub enum Defaultness {
1924 impl fmt::Display for Unsafety {
1925 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1928 Unsafety::Normal => "normal",
1929 Unsafety::Unsafe => "unsafe",
1936 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1937 pub enum ImplPolarity {
1938 /// `impl Trait for Type`
1940 /// `impl !Trait for Type`
1944 impl fmt::Debug for ImplPolarity {
1945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1947 ImplPolarity::Positive => "positive".fmt(f),
1948 ImplPolarity::Negative => "negative".fmt(f),
1953 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1954 pub enum FunctionRetTy {
1955 /// Returns type is not specified.
1957 /// Functions default to `()` and closures default to inference.
1958 /// Span points to where return type would be inserted.
1960 /// Everything else.
1964 impl FunctionRetTy {
1965 pub fn span(&self) -> Span {
1967 FunctionRetTy::Default(span) => span,
1968 FunctionRetTy::Ty(ref ty) => ty.span,
1973 /// Module declaration.
1975 /// E.g., `mod foo;` or `mod foo { .. }`.
1976 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1978 /// A span from the first token past `{` to the last token until `}`.
1979 /// For `mod foo;`, the inner span ranges from the first token
1980 /// to the last token in the external file.
1982 pub items: Vec<P<Item>>,
1983 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
1987 /// Foreign module declaration.
1989 /// E.g., `extern { .. }` or `extern C { .. }`.
1990 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1991 pub struct ForeignMod {
1993 pub items: Vec<ForeignItem>,
1996 /// Global inline assembly.
1998 /// Also known as "module-level assembly" or "file-scoped assembly".
1999 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2000 pub struct GlobalAsm {
2004 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2005 pub struct EnumDef {
2006 pub variants: Vec<Variant>,
2009 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2010 pub struct Variant {
2011 /// Name of the variant.
2013 /// Attributes of the variant.
2014 pub attrs: Vec<Attribute>,
2015 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2017 /// Fields and constructor id of the variant.
2018 pub data: VariantData,
2019 /// Explicit discriminant, e.g., `Foo = 1`.
2020 pub disr_expr: Option<AnonConst>,
2023 /// Is a macro placeholder
2024 pub is_placeholder: bool,
2027 /// Part of `use` item to the right of its prefix.
2028 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2029 pub enum UseTreeKind {
2030 /// `use prefix` or `use prefix as rename`
2032 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2034 Simple(Option<Ident>, NodeId, NodeId),
2035 /// `use prefix::{...}`
2036 Nested(Vec<(UseTree, NodeId)>),
2041 /// A tree of paths sharing common prefixes.
2042 /// Used in `use` items both at top-level and inside of braces in import groups.
2043 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2044 pub struct UseTree {
2046 pub kind: UseTreeKind,
2051 pub fn ident(&self) -> Ident {
2053 UseTreeKind::Simple(Some(rename), ..) => rename,
2054 UseTreeKind::Simple(None, ..) => {
2058 .expect("empty prefix in a simple import")
2061 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2066 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2067 /// are contained as statements within items. These two cases need to be
2068 /// distinguished for pretty-printing.
2069 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
2070 pub enum AttrStyle {
2075 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2076 pub struct AttrId(pub usize);
2078 impl Idx for AttrId {
2079 fn new(idx: usize) -> Self {
2082 fn index(self) -> usize {
2087 impl rustc_serialize::Encodable for AttrId {
2088 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2093 impl rustc_serialize::Decodable for AttrId {
2094 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2095 d.read_nil().map(|_| crate::attr::mk_attr_id())
2099 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2100 pub struct AttrItem {
2102 pub tokens: TokenStream,
2105 /// Metadata associated with an item.
2106 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
2107 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2108 pub struct Attribute {
2111 pub style: AttrStyle,
2112 pub is_sugared_doc: bool,
2116 // Compatibility impl to avoid churn, consider removing.
2117 impl std::ops::Deref for Attribute {
2118 type Target = AttrItem;
2119 fn deref(&self) -> &Self::Target { &self.item }
2122 /// `TraitRef`s appear in impls.
2124 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2125 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2126 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2127 /// same as the impl's `NodeId`).
2128 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2129 pub struct TraitRef {
2134 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2135 pub struct PolyTraitRef {
2136 /// The `'a` in `<'a> Foo<&'a T>`.
2137 pub bound_generic_params: Vec<GenericParam>,
2139 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2140 pub trait_ref: TraitRef,
2146 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2148 bound_generic_params: generic_params,
2149 trait_ref: TraitRef {
2151 ref_id: DUMMY_NODE_ID,
2158 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2159 pub enum CrateSugar {
2160 /// Source is `pub(crate)`.
2163 /// Source is (just) `crate`.
2167 pub type Visibility = Spanned<VisibilityKind>;
2169 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2170 pub enum VisibilityKind {
2173 Restricted { path: P<Path>, id: NodeId },
2177 impl VisibilityKind {
2178 pub fn is_pub(&self) -> bool {
2179 if let VisibilityKind::Public = *self {
2187 /// Field of a struct.
2189 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2190 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2191 pub struct StructField {
2193 pub ident: Option<Ident>,
2194 pub vis: Visibility,
2197 pub attrs: Vec<Attribute>,
2198 pub is_placeholder: bool,
2201 /// Fields and constructor ids of enum variants and structs.
2202 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2203 pub enum VariantData {
2206 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2207 Struct(Vec<StructField>, bool),
2210 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2211 Tuple(Vec<StructField>, NodeId),
2214 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2219 /// Return the fields of this variant.
2220 pub fn fields(&self) -> &[StructField] {
2222 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2227 /// Return the `NodeId` of this variant's constructor, if it has one.
2228 pub fn ctor_id(&self) -> Option<NodeId> {
2230 VariantData::Struct(..) => None,
2231 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2238 /// The name might be a dummy name in case of anonymous items.
2239 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2242 pub attrs: Vec<Attribute>,
2245 pub vis: Visibility,
2248 /// Original tokens this item was parsed from. This isn't necessarily
2249 /// available for all items, although over time more and more items should
2250 /// have this be `Some`. Right now this is primarily used for procedural
2251 /// macros, notably custom attributes.
2253 /// Note that the tokens here do not include the outer attributes, but will
2254 /// include inner attributes.
2255 pub tokens: Option<TokenStream>,
2259 /// Return the span that encompasses the attributes.
2260 pub fn span_with_attributes(&self) -> Span {
2261 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2265 /// A function header.
2267 /// All the information between the visibility and the name of the function is
2268 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2269 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2270 pub struct FnHeader {
2271 pub unsafety: Unsafety,
2272 pub asyncness: Spanned<IsAsync>,
2273 pub constness: Spanned<Constness>,
2277 impl Default for FnHeader {
2278 fn default() -> FnHeader {
2280 unsafety: Unsafety::Normal,
2281 asyncness: dummy_spanned(IsAsync::NotAsync),
2282 constness: dummy_spanned(Constness::NotConst),
2288 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2290 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2292 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2293 ExternCrate(Option<Name>),
2294 /// A use declaration item (`use`).
2296 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2298 /// A static item (`static`).
2300 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2301 Static(P<Ty>, Mutability, P<Expr>),
2302 /// A constant item (`const`).
2304 /// E.g., `const FOO: i32 = 42;`.
2305 Const(P<Ty>, P<Expr>),
2306 /// A function declaration (`fn`).
2308 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2309 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2310 /// A module declaration (`mod`).
2312 /// E.g., `mod foo;` or `mod foo { .. }`.
2314 /// An external module (`extern`).
2316 /// E.g., `extern {}` or `extern "C" {}`.
2317 ForeignMod(ForeignMod),
2318 /// Module-level inline assembly (from `global_asm!()`).
2319 GlobalAsm(P<GlobalAsm>),
2320 /// A type alias (`type`).
2322 /// E.g., `type Foo = Bar<u8>;`.
2323 TyAlias(P<Ty>, Generics),
2324 /// An opaque `impl Trait` type alias.
2326 /// E.g., `type Foo = impl Bar + Boo;`.
2327 OpaqueTy(GenericBounds, Generics),
2328 /// An enum definition (`enum`).
2330 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2331 Enum(EnumDef, Generics),
2332 /// A struct definition (`struct`).
2334 /// E.g., `struct Foo<A> { x: A }`.
2335 Struct(VariantData, Generics),
2336 /// A union definition (`union`).
2338 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2339 Union(VariantData, Generics),
2340 /// A trait declaration (`trait`).
2342 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2343 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2346 /// E.g., `trait Foo = Bar + Quux;`.
2347 TraitAlias(Generics, GenericBounds),
2348 /// An implementation.
2350 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2356 Option<TraitRef>, // (optional) trait this impl implements
2360 /// A macro invocation.
2362 /// E.g., `foo!(..)`.
2365 /// A macro definition.
2370 pub fn descriptive_variant(&self) -> &str {
2372 ItemKind::ExternCrate(..) => "extern crate",
2373 ItemKind::Use(..) => "use",
2374 ItemKind::Static(..) => "static item",
2375 ItemKind::Const(..) => "constant item",
2376 ItemKind::Fn(..) => "function",
2377 ItemKind::Mod(..) => "module",
2378 ItemKind::ForeignMod(..) => "foreign module",
2379 ItemKind::GlobalAsm(..) => "global asm",
2380 ItemKind::TyAlias(..) => "type alias",
2381 ItemKind::OpaqueTy(..) => "opaque type",
2382 ItemKind::Enum(..) => "enum",
2383 ItemKind::Struct(..) => "struct",
2384 ItemKind::Union(..) => "union",
2385 ItemKind::Trait(..) => "trait",
2386 ItemKind::TraitAlias(..) => "trait alias",
2387 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2392 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2393 pub struct ForeignItem {
2395 pub attrs: Vec<Attribute>,
2396 pub kind: ForeignItemKind,
2399 pub vis: Visibility,
2402 /// An item within an `extern` block.
2403 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2404 pub enum ForeignItemKind {
2405 /// A foreign function.
2406 Fn(P<FnDecl>, Generics),
2407 /// A foreign static item (`static ext: u8`).
2408 Static(P<Ty>, Mutability),
2411 /// A macro invocation.
2415 impl ForeignItemKind {
2416 pub fn descriptive_variant(&self) -> &str {
2418 ForeignItemKind::Fn(..) => "foreign function",
2419 ForeignItemKind::Static(..) => "foreign static item",
2420 ForeignItemKind::Ty => "foreign type",
2421 ForeignItemKind::Macro(..) => "macro in foreign module",