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::{ExpnId, SyntaxContext};
9 use crate::parse::token::{self, DelimToken};
10 use crate::print::pprust;
12 use crate::source_map::{dummy_spanned, respan, Spanned};
13 use crate::symbol::{kw, sym, Symbol};
14 use crate::tokenstream::TokenStream;
17 use rustc_data_structures::indexed_vec::Idx;
18 #[cfg(target_arch = "x86_64")]
19 use rustc_data_structures::static_assert_size;
20 use rustc_target::spec::abi::Abi;
21 use syntax_pos::{Span, DUMMY_SP};
23 use rustc_data_structures::fx::FxHashSet;
24 use rustc_data_structures::sync::Lrc;
25 use rustc_serialize::{self, Decoder, Encoder};
28 pub use rustc_target::abi::FloatTy;
33 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
38 impl fmt::Debug for Label {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 write!(f, "label({:?})", self.ident)
44 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
50 impl fmt::Debug for Lifetime {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 impl fmt::Display for Lifetime {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 write!(f, "{}", self.ident.name.as_str())
67 /// A "Path" is essentially Rust's notion of a name.
69 /// It's represented as a sequence of identifiers,
70 /// along with a bunch of supporting information.
72 /// E.g., `std::cmp::PartialEq`.
73 #[derive(Clone, RustcEncodable, RustcDecodable)]
76 /// The segments in the path: the things separated by `::`.
77 /// Global paths begin with `kw::PathRoot`.
78 pub segments: Vec<PathSegment>,
81 impl PartialEq<Symbol> for Path {
82 fn eq(&self, symbol: &Symbol) -> bool {
83 self.segments.len() == 1 && {
84 self.segments[0].ident.name == *symbol
89 impl fmt::Debug for Path {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 write!(f, "path({})", pprust::path_to_string(self))
95 impl fmt::Display for Path {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 write!(f, "{}", pprust::path_to_string(self))
102 // Convert a span and an identifier to the corresponding
104 pub fn from_ident(ident: Ident) -> Path {
106 segments: vec![PathSegment::from_ident(ident)],
111 pub fn is_global(&self) -> bool {
112 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
116 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
118 /// E.g., `std`, `String` or `Box<T>`.
119 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
120 pub struct PathSegment {
121 /// The identifier portion of this path segment.
126 /// Type/lifetime parameters attached to this path. They come in
127 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
128 /// `None` means that no parameter list is supplied (`Path`),
129 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
130 /// but it can be empty (`Path<>`).
131 /// `P` is used as a size optimization for the common case with no parameters.
132 pub args: Option<P<GenericArgs>>,
136 pub fn from_ident(ident: Ident) -> Self {
137 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
139 pub fn path_root(span: Span) -> Self {
140 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
144 /// The arguments of a path segment.
146 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
147 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
148 pub enum GenericArgs {
149 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
150 AngleBracketed(AngleBracketedArgs),
151 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
152 Parenthesized(ParenthesizedArgs),
156 pub fn is_parenthesized(&self) -> bool {
158 Parenthesized(..) => true,
163 pub fn is_angle_bracketed(&self) -> bool {
165 AngleBracketed(..) => true,
170 pub fn span(&self) -> Span {
172 AngleBracketed(ref data) => data.span,
173 Parenthesized(ref data) => data.span,
178 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
179 pub enum GenericArg {
186 pub fn span(&self) -> Span {
188 GenericArg::Lifetime(lt) => lt.ident.span,
189 GenericArg::Type(ty) => ty.span,
190 GenericArg::Const(ct) => ct.value.span,
195 /// A path like `Foo<'a, T>`.
196 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
197 pub struct AngleBracketedArgs {
198 /// The overall span.
200 /// The arguments for this path segment.
201 pub args: Vec<GenericArg>,
202 /// Constraints on associated types, if any.
203 /// E.g., `Foo<A = Bar, B: Baz>`.
204 pub constraints: Vec<AssocTyConstraint>,
207 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
208 fn into(self) -> Option<P<GenericArgs>> {
209 Some(P(GenericArgs::AngleBracketed(self)))
213 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
214 fn into(self) -> Option<P<GenericArgs>> {
215 Some(P(GenericArgs::Parenthesized(self)))
219 /// A path like `Foo(A, B) -> C`.
220 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
221 pub struct ParenthesizedArgs {
226 pub inputs: Vec<P<Ty>>,
229 pub output: Option<P<Ty>>,
232 impl ParenthesizedArgs {
233 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
236 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
242 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
244 use rustc_data_structures::indexed_vec::Idx;
245 use rustc_data_structures::newtype_index;
249 DEBUG_FORMAT = "NodeId({})"
254 pub use node_id_inner::NodeId;
257 pub fn placeholder_from_expn_id(expn_id: ExpnId) -> Self {
258 NodeId::from_u32(expn_id.as_u32())
261 pub fn placeholder_to_expn_id(self) -> ExpnId {
262 ExpnId::from_u32(self.as_u32())
266 impl fmt::Display for NodeId {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 fmt::Display::fmt(&self.as_u32(), f)
272 impl rustc_serialize::UseSpecializedEncodable for NodeId {
273 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
274 s.emit_u32(self.as_u32())
278 impl rustc_serialize::UseSpecializedDecodable for NodeId {
279 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
280 d.read_u32().map(NodeId::from_u32)
284 /// `NodeId` used to represent the root of the crate.
285 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
287 /// When parsing and doing expansions, we initially give all AST nodes this AST
288 /// node value. Then later, in the renumber pass, we renumber them to have
289 /// small, positive ids.
290 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
292 /// A modifier on a bound, currently this is only used for `?Sized`, where the
293 /// modifier is `Maybe`. Negative bounds should also be handled here.
294 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
295 pub enum TraitBoundModifier {
300 /// The AST represents all type param bounds as types.
301 /// `typeck::collect::compute_bounds` matches these against
302 /// the "special" built-in traits (see `middle::lang_items`) and
303 /// detects `Copy`, `Send` and `Sync`.
304 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
305 pub enum GenericBound {
306 Trait(PolyTraitRef, TraitBoundModifier),
311 pub fn span(&self) -> Span {
313 &GenericBound::Trait(ref t, ..) => t.span,
314 &GenericBound::Outlives(ref l) => l.ident.span,
319 pub type GenericBounds = Vec<GenericBound>;
321 /// Specifies the enforced ordering for generic parameters. In the future,
322 /// if we wanted to relax this order, we could override `PartialEq` and
323 /// `PartialOrd`, to allow the kinds to be unordered.
324 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
325 pub enum ParamKindOrd {
331 impl fmt::Display for ParamKindOrd {
332 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 ParamKindOrd::Lifetime => "lifetime".fmt(f),
335 ParamKindOrd::Type => "type".fmt(f),
336 ParamKindOrd::Const => "const".fmt(f),
341 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
342 pub enum GenericParamKind {
343 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
345 Type { default: Option<P<Ty>> },
349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
350 pub struct GenericParam {
353 pub attrs: ThinVec<Attribute>,
354 pub bounds: GenericBounds,
356 pub kind: GenericParamKind,
359 /// Represents lifetime, type and const parameters attached to a declaration of
360 /// a function, enum, trait, etc.
361 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
362 pub struct Generics {
363 pub params: Vec<GenericParam>,
364 pub where_clause: WhereClause,
368 impl Default for Generics {
369 /// Creates an instance of `Generics`.
370 fn default() -> Generics {
373 where_clause: WhereClause {
374 predicates: Vec::new(),
382 /// A where-clause in a definition.
383 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
384 pub struct WhereClause {
385 pub predicates: Vec<WherePredicate>,
389 /// A single predicate in a where-clause.
390 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
391 pub enum WherePredicate {
392 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
393 BoundPredicate(WhereBoundPredicate),
394 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
395 RegionPredicate(WhereRegionPredicate),
396 /// An equality predicate (unsupported).
397 EqPredicate(WhereEqPredicate),
400 impl WherePredicate {
401 pub fn span(&self) -> Span {
403 &WherePredicate::BoundPredicate(ref p) => p.span,
404 &WherePredicate::RegionPredicate(ref p) => p.span,
405 &WherePredicate::EqPredicate(ref p) => p.span,
412 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
413 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
414 pub struct WhereBoundPredicate {
416 /// Any generics from a `for` binding
417 pub bound_generic_params: Vec<GenericParam>,
418 /// The type being bounded
419 pub bounded_ty: P<Ty>,
420 /// Trait and lifetime bounds (`Clone+Send+'static`)
421 pub bounds: GenericBounds,
424 /// A lifetime predicate.
426 /// E.g., `'a: 'b + 'c`.
427 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
428 pub struct WhereRegionPredicate {
430 pub lifetime: Lifetime,
431 pub bounds: GenericBounds,
434 /// An equality predicate (unsupported).
437 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
438 pub struct WhereEqPredicate {
445 /// The set of `MetaItem`s that define the compilation environment of the crate,
446 /// used to drive conditional compilation.
447 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
449 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
452 pub attrs: Vec<Attribute>,
456 /// Possible values inside of compile-time attribute lists.
458 /// E.g., the '..' in `#[name(..)]`.
459 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
460 pub enum NestedMetaItem {
461 /// A full MetaItem, for recursive meta items.
465 /// E.g., `"foo"`, `64`, `true`.
469 /// A spanned compile-time attribute item.
471 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
472 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
473 pub struct MetaItem {
475 pub node: MetaItemKind,
479 /// A compile-time attribute item.
481 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
482 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
483 pub enum MetaItemKind {
486 /// E.g., `test` as in `#[test]`.
490 /// E.g., `derive(..)` as in `#[derive(..)]`.
491 List(Vec<NestedMetaItem>),
492 /// Name value meta item.
494 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
498 /// A Block (`{ .. }`).
500 /// E.g., `{ .. }` as in `fn foo() { .. }`.
501 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
503 /// Statements in a block
504 pub stmts: Vec<Stmt>,
506 /// Distinguishes between `unsafe { ... }` and `{ ... }`
507 pub rules: BlockCheckMode,
511 #[derive(Clone, RustcEncodable, RustcDecodable)]
518 impl fmt::Debug for Pat {
519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
525 /// Attempt reparsing the pattern as a type.
526 /// This is intended for use by diagnostics.
527 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
528 let node = match &self.node {
529 // In a type expression `_` is an inference variable.
530 PatKind::Wild => TyKind::Infer,
531 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
532 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
533 TyKind::Path(None, Path::from_ident(*ident))
535 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
536 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
537 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
538 PatKind::Ref(pat, mutbl) => pat
540 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
541 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
542 // when `P` can be reparsed as a type `T`.
543 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
544 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
545 // assuming `T0` to `Tn` are all syntactically valid as types.
546 PatKind::Tuple(pats) => {
547 let mut tys = Vec::with_capacity(pats.len());
548 // FIXME(#48994) - could just be collected into an Option<Vec>
550 tys.push(pat.to_ty()?);
564 pub fn walk<F>(&self, it: &mut F) -> bool
566 F: FnMut(&Pat) -> bool,
573 PatKind::Ident(_, _, Some(p)) => p.walk(it),
574 PatKind::Struct(_, fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
575 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) => {
576 s.iter().all(|p| p.walk(it))
578 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
585 | PatKind::Mac(_) => true,
589 /// Is this a `..` pattern?
590 pub fn is_rest(&self) -> bool {
592 PatKind::Rest => true,
598 /// A single field in a struct pattern
600 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
601 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
602 /// except is_shorthand is true
603 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
604 pub struct FieldPat {
605 /// The identifier for the field
607 /// The pattern the field is destructured to
609 pub is_shorthand: bool,
610 pub attrs: ThinVec<Attribute>,
613 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
614 pub enum BindingMode {
619 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
621 Included(RangeSyntax),
625 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
626 pub enum RangeSyntax {
631 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
633 /// Represents a wildcard pattern (`_`).
636 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
637 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
638 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
639 /// during name resolution.
640 Ident(BindingMode, Ident, Option<P<Pat>>),
642 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
643 /// The `bool` is `true` in the presence of a `..`.
644 Struct(Path, Vec<Spanned<FieldPat>>, /* recovered */ bool),
646 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
647 TupleStruct(Path, Vec<P<Pat>>),
649 /// A possibly qualified path pattern.
650 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
651 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
652 /// only legally refer to associated constants.
653 Path(Option<QSelf>, Path),
655 /// A tuple pattern (`(a, b)`).
661 /// A reference pattern (e.g., `&mut (a, b)`).
662 Ref(P<Pat>, Mutability),
667 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
668 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
670 /// A slice pattern `[a, b, c]`.
673 /// A rest pattern `..`.
675 /// Syntactically it is valid anywhere.
677 /// Semantically however, it only has meaning immediately inside:
678 /// - a slice pattern: `[a, .., b]`,
679 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
680 /// - a tuple pattern: `(a, .., b)`,
681 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
683 /// In all of these cases, an additional restriction applies,
684 /// only one rest pattern may occur in the pattern sequences.
687 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
690 /// A macro pattern; pre-expansion.
695 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
697 pub enum Mutability {
702 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
704 /// The `+` operator (addition)
706 /// The `-` operator (subtraction)
708 /// The `*` operator (multiplication)
710 /// The `/` operator (division)
712 /// The `%` operator (modulus)
714 /// The `&&` operator (logical and)
716 /// The `||` operator (logical or)
718 /// The `^` operator (bitwise xor)
720 /// The `&` operator (bitwise and)
722 /// The `|` operator (bitwise or)
724 /// The `<<` operator (shift left)
726 /// The `>>` operator (shift right)
728 /// The `==` operator (equality)
730 /// The `<` operator (less than)
732 /// The `<=` operator (less than or equal to)
734 /// The `!=` operator (not equal to)
736 /// The `>=` operator (greater than or equal to)
738 /// The `>` operator (greater than)
743 pub fn to_string(&self) -> &'static str {
766 pub fn lazy(&self) -> bool {
768 BinOpKind::And | BinOpKind::Or => true,
773 pub fn is_shift(&self) -> bool {
775 BinOpKind::Shl | BinOpKind::Shr => true,
780 pub fn is_comparison(&self) -> bool {
783 Eq | Lt | Le | Ne | Gt | Ge => true,
784 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
788 /// Returns `true` if the binary operator takes its arguments by value
789 pub fn is_by_value(&self) -> bool {
790 !self.is_comparison()
794 pub type BinOp = Spanned<BinOpKind>;
796 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
798 /// The `*` operator for dereferencing
800 /// The `!` operator for logical inversion
802 /// The `-` operator for negation
807 /// Returns `true` if the unary operator takes its argument by value
808 pub fn is_by_value(u: UnOp) -> bool {
810 UnOp::Neg | UnOp::Not => true,
815 pub fn to_string(op: UnOp) -> &'static str {
825 #[derive(Clone, RustcEncodable, RustcDecodable)]
833 pub fn add_trailing_semicolon(mut self) -> Self {
834 self.node = match self.node {
835 StmtKind::Expr(expr) => StmtKind::Semi(expr),
836 StmtKind::Mac(mac) => {
837 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
844 pub fn is_item(&self) -> bool {
846 StmtKind::Item(_) => true,
851 pub fn is_expr(&self) -> bool {
853 StmtKind::Expr(_) => true,
859 impl fmt::Debug for Stmt {
860 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
865 pprust::stmt_to_string(self)
870 #[derive(Clone, RustcEncodable, RustcDecodable)]
872 /// A local (let) binding.
875 /// An item definition.
878 /// Expr without trailing semi-colon.
880 /// Expr with a trailing semi-colon.
883 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
886 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
887 pub enum MacStmtStyle {
888 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
889 /// `foo!(...);`, `foo![...];`).
891 /// The macro statement had braces (e.g., `foo! { ... }`).
893 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
894 /// `foo!(...)`). All of these will end up being converted into macro
899 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
900 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
903 pub ty: Option<P<Ty>>,
904 /// Initializer expression to set the value, if any.
905 pub init: Option<P<Expr>>,
908 pub attrs: ThinVec<Attribute>,
911 /// An arm of a 'match'.
913 /// E.g., `0..=10 => { println!("match!") }` as in
917 /// 0..=10 => { println!("match!") },
918 /// _ => { println!("no match!") },
921 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
923 pub attrs: Vec<Attribute>,
924 pub pats: Vec<P<Pat>>,
925 pub guard: Option<P<Expr>>,
930 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
935 pub is_shorthand: bool,
936 pub attrs: ThinVec<Attribute>,
939 pub type SpannedIdent = Spanned<Ident>;
941 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
942 pub enum BlockCheckMode {
944 Unsafe(UnsafeSource),
947 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
948 pub enum UnsafeSource {
953 /// A constant (expression) that's not an item or associated item,
954 /// but needs its own `DefId` for type-checking, const-eval, etc.
955 /// These are usually found nested inside types (e.g., array lengths)
956 /// or expressions (e.g., repeat counts), and also used to define
957 /// explicit discriminant values for enum variants.
958 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
959 pub struct AnonConst {
965 #[derive(Clone, RustcEncodable, RustcDecodable)]
970 pub attrs: ThinVec<Attribute>,
973 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
974 #[cfg(target_arch = "x86_64")]
975 static_assert_size!(Expr, 96);
978 /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
980 pub fn returns(&self) -> bool {
981 if let ExprKind::Block(ref block, _) = self.node {
982 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
984 Some(&StmtKind::Expr(_)) => true,
985 Some(&StmtKind::Semi(ref expr)) => {
986 if let ExprKind::Ret(_) = expr.node {
987 // last statement is explicit return
993 // This is a block that doesn't end in either an implicit or explicit return
997 // This is not a block, it is a value
1002 fn to_bound(&self) -> Option<GenericBound> {
1004 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1005 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1006 TraitBoundModifier::None,
1012 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
1013 let node = match &self.node {
1014 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1015 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1016 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1017 ExprKind::AddrOf(mutbl, expr) => expr
1019 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
1020 ExprKind::Repeat(expr, expr_len) => {
1021 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1023 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1024 ExprKind::Tup(exprs) => {
1027 .map(|expr| expr.to_ty())
1028 .collect::<Option<Vec<_>>>()?;
1031 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1032 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1033 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1048 pub fn precedence(&self) -> ExprPrecedence {
1050 ExprKind::Box(_) => ExprPrecedence::Box,
1051 ExprKind::Array(_) => ExprPrecedence::Array,
1052 ExprKind::Call(..) => ExprPrecedence::Call,
1053 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1054 ExprKind::Tup(_) => ExprPrecedence::Tup,
1055 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1056 ExprKind::Unary(..) => ExprPrecedence::Unary,
1057 ExprKind::Lit(_) => ExprPrecedence::Lit,
1058 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1059 ExprKind::Let(..) => ExprPrecedence::Let,
1060 ExprKind::If(..) => ExprPrecedence::If,
1061 ExprKind::While(..) => ExprPrecedence::While,
1062 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1063 ExprKind::Loop(..) => ExprPrecedence::Loop,
1064 ExprKind::Match(..) => ExprPrecedence::Match,
1065 ExprKind::Closure(..) => ExprPrecedence::Closure,
1066 ExprKind::Block(..) => ExprPrecedence::Block,
1067 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1068 ExprKind::Async(..) => ExprPrecedence::Async,
1069 ExprKind::Await(..) => ExprPrecedence::Await,
1070 ExprKind::Assign(..) => ExprPrecedence::Assign,
1071 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1072 ExprKind::Field(..) => ExprPrecedence::Field,
1073 ExprKind::Index(..) => ExprPrecedence::Index,
1074 ExprKind::Range(..) => ExprPrecedence::Range,
1075 ExprKind::Path(..) => ExprPrecedence::Path,
1076 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1077 ExprKind::Break(..) => ExprPrecedence::Break,
1078 ExprKind::Continue(..) => ExprPrecedence::Continue,
1079 ExprKind::Ret(..) => ExprPrecedence::Ret,
1080 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1081 ExprKind::Mac(..) => ExprPrecedence::Mac,
1082 ExprKind::Struct(..) => ExprPrecedence::Struct,
1083 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1084 ExprKind::Paren(..) => ExprPrecedence::Paren,
1085 ExprKind::Try(..) => ExprPrecedence::Try,
1086 ExprKind::Yield(..) => ExprPrecedence::Yield,
1087 ExprKind::Err => ExprPrecedence::Err,
1092 impl fmt::Debug for Expr {
1093 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1094 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1098 /// Limit types of a range (inclusive or exclusive)
1099 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1100 pub enum RangeLimits {
1101 /// Inclusive at the beginning, exclusive at the end
1103 /// Inclusive at the beginning and end
1107 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1109 /// A `box x` expression.
1111 /// An array (`[a, b, c, d]`)
1112 Array(Vec<P<Expr>>),
1115 /// The first field resolves to the function itself,
1116 /// and the second field is the list of arguments.
1117 /// This also represents calling the constructor of
1118 /// tuple-like ADTs such as tuple structs and enum variants.
1119 Call(P<Expr>, Vec<P<Expr>>),
1120 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1122 /// The `PathSegment` represents the method name and its generic arguments
1123 /// (within the angle brackets).
1124 /// The first element of the vector of an `Expr` is the expression that evaluates
1125 /// to the object on which the method is being called on (the receiver),
1126 /// and the remaining elements are the rest of the arguments.
1127 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1128 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1129 MethodCall(PathSegment, Vec<P<Expr>>),
1130 /// A tuple (e.g., `(a, b, c, d)`).
1132 /// A binary operation (e.g., `a + b`, `a * b`).
1133 Binary(BinOp, P<Expr>, P<Expr>),
1134 /// A unary operation (e.g., `!x`, `*x`).
1135 Unary(UnOp, P<Expr>),
1136 /// A literal (e.g., `1`, `"foo"`).
1138 /// A cast (e.g., `foo as f64`).
1139 Cast(P<Expr>, P<Ty>),
1140 /// A type ascription (e.g., `42: usize`).
1141 Type(P<Expr>, P<Ty>),
1142 /// A `let pats = expr` expression that is only semantically allowed in the condition
1143 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1145 /// The `Vec<P<Pat>>` is for or-patterns at the top level.
1146 /// FIXME(54883): Change this to just `P<Pat>`.
1147 Let(Vec<P<Pat>>, P<Expr>),
1148 /// An `if` block, with an optional `else` block.
1150 /// `if expr { block } else { expr }`
1151 If(P<Expr>, P<Block>, Option<P<Expr>>),
1152 /// A while loop, with an optional label.
1154 /// `'label: while expr { block }`
1155 While(P<Expr>, P<Block>, Option<Label>),
1156 /// A `for` loop, with an optional label.
1158 /// `'label: for pat in expr { block }`
1160 /// This is desugared to a combination of `loop` and `match` expressions.
1161 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1162 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1164 /// `'label: loop { block }`
1165 Loop(P<Block>, Option<Label>),
1166 /// A `match` block.
1167 Match(P<Expr>, Vec<Arm>),
1168 /// A closure (e.g., `move |a, b, c| a + b + c`).
1170 /// The final span is the span of the argument block `|...|`.
1171 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1172 /// A block (`'label: { ... }`).
1173 Block(P<Block>, Option<Label>),
1174 /// An async block (`async move { ... }`).
1176 /// The `NodeId` is the `NodeId` for the closure that results from
1177 /// desugaring an async block, just like the NodeId field in the
1178 /// `IsAsync` enum. This is necessary in order to create a def for the
1179 /// closure which can be used as a parent of any child defs. Defs
1180 /// created during lowering cannot be made the parent of any other
1181 /// preexisting defs.
1182 Async(CaptureBy, NodeId, P<Block>),
1183 /// An await expression (`my_future.await`).
1186 /// A try block (`try { ... }`).
1189 /// An assignment (`a = foo()`).
1190 Assign(P<Expr>, P<Expr>),
1191 /// An assignment with an operator.
1194 AssignOp(BinOp, P<Expr>, P<Expr>),
1195 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1196 Field(P<Expr>, Ident),
1197 /// An indexing operation (e.g., `foo[2]`).
1198 Index(P<Expr>, P<Expr>),
1199 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1200 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1202 /// Variable reference, possibly containing `::` and/or type
1203 /// parameters (e.g., `foo::bar::<baz>`).
1205 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1206 Path(Option<QSelf>, Path),
1208 /// A referencing operation (`&a` or `&mut a`).
1209 AddrOf(Mutability, P<Expr>),
1210 /// A `break`, with an optional label to break, and an optional expression.
1211 Break(Option<Label>, Option<P<Expr>>),
1212 /// A `continue`, with an optional label.
1213 Continue(Option<Label>),
1214 /// A `return`, with an optional value to be returned.
1215 Ret(Option<P<Expr>>),
1217 /// Output of the `asm!()` macro.
1218 InlineAsm(P<InlineAsm>),
1220 /// A macro invocation; pre-expansion.
1223 /// A struct literal expression.
1225 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1226 /// where `base` is the `Option<Expr>`.
1227 Struct(Path, Vec<Field>, Option<P<Expr>>),
1229 /// An array literal constructed from one repeated element.
1231 /// E.g., `[1; 5]`. The expression is the element to be
1232 /// repeated; the constant is the number of times to repeat it.
1233 Repeat(P<Expr>, AnonConst),
1235 /// No-op: used solely so we can pretty-print faithfully.
1238 /// A try expression (`expr?`).
1241 /// A `yield`, with an optional value to be yielded.
1242 Yield(Option<P<Expr>>),
1244 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1248 /// The explicit `Self` type in a "qualified path". The actual
1249 /// path, including the trait and the associated item, is stored
1250 /// separately. `position` represents the index of the associated
1251 /// item qualified with this `Self` type.
1253 /// ```ignore (only-for-syntax-highlight)
1254 /// <Vec<T> as a::b::Trait>::AssociatedItem
1255 /// ^~~~~ ~~~~~~~~~~~~~~^
1258 /// <Vec<T>>::AssociatedItem
1262 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1266 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1267 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1268 /// 0`, this is an empty span.
1269 pub path_span: Span,
1270 pub position: usize,
1273 /// A capture clause.
1274 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1275 pub enum CaptureBy {
1280 /// The movability of a generator / closure literal.
1281 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1282 pub enum Movability {
1287 pub type Mac = Spanned<Mac_>;
1289 /// Represents a macro invocation. The `Path` indicates which macro
1290 /// is being invoked, and the vector of token-trees contains the source
1291 /// of the macro invocation.
1293 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1294 /// stored in the enclosing item.
1295 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1298 pub delim: MacDelimiter,
1299 pub tts: TokenStream,
1300 pub prior_type_ascription: Option<(Span, bool)>,
1303 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1304 pub enum MacDelimiter {
1311 pub fn stream(&self) -> TokenStream {
1317 crate fn to_token(self) -> DelimToken {
1319 MacDelimiter::Parenthesis => DelimToken::Paren,
1320 MacDelimiter::Bracket => DelimToken::Bracket,
1321 MacDelimiter::Brace => DelimToken::Brace,
1326 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1327 pub struct MacroDef {
1328 pub tokens: TokenStream,
1333 pub fn stream(&self) -> TokenStream {
1334 self.tokens.clone().into()
1338 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1340 /// A regular string, like `"foo"`.
1342 /// A raw string, like `r##"foo"##`.
1344 /// The value is the number of `#` symbols used.
1349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1351 /// The original literal token as written in source code.
1352 pub token: token::Lit,
1353 /// The "semantic" representation of the literal lowered from the original tokens.
1354 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1355 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1360 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1361 pub enum LitIntType {
1369 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1370 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1372 /// A string literal (`"foo"`).
1373 Str(Symbol, StrStyle),
1374 /// A byte string (`b"foo"`).
1375 ByteStr(Lrc<Vec<u8>>),
1376 /// A byte char (`b'f'`).
1378 /// A character literal (`'a'`).
1380 /// An integer literal (`1`).
1381 Int(u128, LitIntType),
1382 /// A float literal (`1f64` or `1E10f64`).
1383 Float(Symbol, FloatTy),
1384 /// A float literal without a suffix (`1.0 or 1.0E10`).
1385 FloatUnsuffixed(Symbol),
1386 /// A boolean literal.
1388 /// Placeholder for a literal that wasn't well-formed in some way.
1393 /// Returns `true` if this literal is a string.
1394 pub fn is_str(&self) -> bool {
1396 LitKind::Str(..) => true,
1401 /// Returns `true` if this literal is byte literal string.
1402 pub fn is_bytestr(&self) -> bool {
1404 LitKind::ByteStr(_) => true,
1409 /// Returns `true` if this is a numeric literal.
1410 pub fn is_numeric(&self) -> bool {
1412 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1417 /// Returns `true` if this literal has no suffix.
1418 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1419 pub fn is_unsuffixed(&self) -> bool {
1421 // unsuffixed variants
1423 | LitKind::ByteStr(..)
1426 | LitKind::Int(_, LitIntType::Unsuffixed)
1427 | LitKind::FloatUnsuffixed(..)
1429 | LitKind::Err(..) => true,
1430 // suffixed variants
1431 LitKind::Int(_, LitIntType::Signed(..))
1432 | LitKind::Int(_, LitIntType::Unsigned(..))
1433 | LitKind::Float(..) => false,
1437 /// Returns `true` if this literal has a suffix.
1438 pub fn is_suffixed(&self) -> bool {
1439 !self.is_unsuffixed()
1443 // N.B., If you change this, you'll probably want to change the corresponding
1444 // type structure in `middle/ty.rs` as well.
1445 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1448 pub mutbl: Mutability,
1451 /// Represents a method's signature in a trait declaration,
1452 /// or in an implementation.
1453 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1454 pub struct MethodSig {
1455 pub header: FnHeader,
1456 pub decl: P<FnDecl>,
1459 /// Represents an item declaration within a trait declaration,
1460 /// possibly including a default implementation. A trait item is
1461 /// either required (meaning it doesn't have an implementation, just a
1462 /// signature) or provided (meaning it has a default implementation).
1463 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1464 pub struct TraitItem {
1467 pub attrs: Vec<Attribute>,
1468 pub generics: Generics,
1469 pub node: TraitItemKind,
1471 /// See `Item::tokens` for what this is.
1472 pub tokens: Option<TokenStream>,
1475 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1476 pub enum TraitItemKind {
1477 Const(P<Ty>, Option<P<Expr>>),
1478 Method(MethodSig, Option<P<Block>>),
1479 Type(GenericBounds, Option<P<Ty>>),
1483 /// Represents anything within an `impl` block.
1484 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1485 pub struct ImplItem {
1488 pub vis: Visibility,
1489 pub defaultness: Defaultness,
1490 pub attrs: Vec<Attribute>,
1491 pub generics: Generics,
1492 pub node: ImplItemKind,
1494 /// See `Item::tokens` for what this is.
1495 pub tokens: Option<TokenStream>,
1498 /// Represents various kinds of content within an `impl`.
1499 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1500 pub enum ImplItemKind {
1501 Const(P<Ty>, P<Expr>),
1502 Method(MethodSig, P<Block>),
1504 OpaqueTy(GenericBounds),
1508 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1518 impl fmt::Debug for IntTy {
1519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1520 fmt::Display::fmt(self, f)
1524 impl fmt::Display for IntTy {
1525 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1526 write!(f, "{}", self.ty_to_string())
1531 pub fn ty_to_string(&self) -> &'static str {
1533 IntTy::Isize => "isize",
1535 IntTy::I16 => "i16",
1536 IntTy::I32 => "i32",
1537 IntTy::I64 => "i64",
1538 IntTy::I128 => "i128",
1542 pub fn to_symbol(&self) -> Symbol {
1544 IntTy::Isize => sym::isize,
1545 IntTy::I8 => sym::i8,
1546 IntTy::I16 => sym::i16,
1547 IntTy::I32 => sym::i32,
1548 IntTy::I64 => sym::i64,
1549 IntTy::I128 => sym::i128,
1553 pub fn val_to_string(&self, val: i128) -> String {
1554 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1555 // are parsed as `u128`, so we wouldn't want to print an extra negative
1557 format!("{}{}", val as u128, self.ty_to_string())
1560 pub fn bit_width(&self) -> Option<usize> {
1562 IntTy::Isize => return None,
1572 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1583 pub fn ty_to_string(&self) -> &'static str {
1585 UintTy::Usize => "usize",
1587 UintTy::U16 => "u16",
1588 UintTy::U32 => "u32",
1589 UintTy::U64 => "u64",
1590 UintTy::U128 => "u128",
1594 pub fn to_symbol(&self) -> Symbol {
1596 UintTy::Usize => sym::usize,
1597 UintTy::U8 => sym::u8,
1598 UintTy::U16 => sym::u16,
1599 UintTy::U32 => sym::u32,
1600 UintTy::U64 => sym::u64,
1601 UintTy::U128 => sym::u128,
1605 pub fn val_to_string(&self, val: u128) -> String {
1606 format!("{}{}", val, self.ty_to_string())
1609 pub fn bit_width(&self) -> Option<usize> {
1611 UintTy::Usize => return None,
1616 UintTy::U128 => 128,
1621 impl fmt::Debug for UintTy {
1622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1623 fmt::Display::fmt(self, f)
1627 impl fmt::Display for UintTy {
1628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1629 write!(f, "{}", self.ty_to_string())
1633 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1634 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1635 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1636 pub struct AssocTyConstraint {
1639 pub kind: AssocTyConstraintKind,
1643 /// The kinds of an `AssocTyConstraint`.
1644 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1645 pub enum AssocTyConstraintKind {
1646 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1650 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1652 bounds: GenericBounds,
1656 #[derive(Clone, RustcEncodable, RustcDecodable)]
1663 impl fmt::Debug for Ty {
1664 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1665 write!(f, "type({})", pprust::ty_to_string(self))
1669 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1670 pub struct BareFnTy {
1671 pub unsafety: Unsafety,
1673 pub generic_params: Vec<GenericParam>,
1674 pub decl: P<FnDecl>,
1677 /// The various kinds of type recognized by the compiler.
1678 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1680 /// A variable-length slice (`[T]`).
1682 /// A fixed length array (`[T; n]`).
1683 Array(P<Ty>, AnonConst),
1684 /// A raw pointer (`*const T` or `*mut T`).
1686 /// A reference (`&'a T` or `&'a mut T`).
1687 Rptr(Option<Lifetime>, MutTy),
1688 /// A bare function (e.g., `fn(usize) -> bool`).
1689 BareFn(P<BareFnTy>),
1690 /// The never type (`!`).
1692 /// A tuple (`(A, B, C, D,...)`).
1694 /// A path (`module::module::...::Type`), optionally
1695 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1697 /// Type parameters are stored in the `Path` itself.
1698 Path(Option<QSelf>, Path),
1699 /// A trait object type `Bound1 + Bound2 + Bound3`
1700 /// where `Bound` is a trait or a lifetime.
1701 TraitObject(GenericBounds, TraitObjectSyntax),
1702 /// An `impl Bound1 + Bound2 + Bound3` type
1703 /// where `Bound` is a trait or a lifetime.
1705 /// The `NodeId` exists to prevent lowering from having to
1706 /// generate `NodeId`s on the fly, which would complicate
1707 /// the generation of opaque `type Foo = impl Trait` items significantly.
1708 ImplTrait(NodeId, GenericBounds),
1709 /// No-op; kept solely so that we can pretty-print faithfully.
1713 /// This means the type should be inferred instead of it having been
1714 /// specified. This can appear anywhere in a type.
1716 /// Inferred type of a `self` or `&self` argument in a method.
1718 /// A macro in the type position.
1720 /// Placeholder for a kind that has failed to be defined.
1722 /// Placeholder for a `va_list`.
1727 pub fn is_implicit_self(&self) -> bool {
1728 if let TyKind::ImplicitSelf = *self {
1735 pub fn is_unit(&self) -> bool {
1736 if let TyKind::Tup(ref tys) = *self {
1744 /// Syntax used to declare a trait object.
1745 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1746 pub enum TraitObjectSyntax {
1751 /// Inline assembly dialect.
1753 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1754 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1755 pub enum AsmDialect {
1760 /// Inline assembly.
1762 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1763 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1764 pub struct InlineAsmOutput {
1765 pub constraint: Symbol,
1768 pub is_indirect: bool,
1771 /// Inline assembly.
1773 /// E.g., `asm!("NOP");`.
1774 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1775 pub struct InlineAsm {
1777 pub asm_str_style: StrStyle,
1778 pub outputs: Vec<InlineAsmOutput>,
1779 pub inputs: Vec<(Symbol, P<Expr>)>,
1780 pub clobbers: Vec<Symbol>,
1782 pub alignstack: bool,
1783 pub dialect: AsmDialect,
1784 pub ctxt: SyntaxContext,
1787 /// An argument in a function header.
1789 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1790 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1792 pub attrs: ThinVec<Attribute>,
1799 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1801 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1802 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1804 /// `self`, `mut self`
1806 /// `&'lt self`, `&'lt mut self`
1807 Region(Option<Lifetime>, Mutability),
1808 /// `self: TYPE`, `mut self: TYPE`
1809 Explicit(P<Ty>, Mutability),
1812 pub type ExplicitSelf = Spanned<SelfKind>;
1815 pub fn to_self(&self) -> Option<ExplicitSelf> {
1816 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1817 if ident.name == kw::SelfLower {
1818 return match self.ty.node {
1819 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1820 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1821 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1824 self.pat.span.to(self.ty.span),
1825 SelfKind::Explicit(self.ty.clone(), mutbl),
1833 pub fn is_self(&self) -> bool {
1834 if let PatKind::Ident(_, ident, _) = self.pat.node {
1835 ident.name == kw::SelfLower
1841 pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1842 let span = eself.span.to(eself_ident.span);
1843 let infer_ty = P(Ty {
1845 node: TyKind::ImplicitSelf,
1848 let arg = |mutbl, ty| Arg {
1852 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1860 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1861 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1862 SelfKind::Region(lt, mutbl) => arg(
1863 Mutability::Immutable,
1880 /// A header (not the body) of a function declaration.
1882 /// E.g., `fn foo(bar: baz)`.
1883 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1885 pub inputs: Vec<Arg>,
1886 pub output: FunctionRetTy,
1887 pub c_variadic: bool,
1891 pub fn get_self(&self) -> Option<ExplicitSelf> {
1892 self.inputs.get(0).and_then(Arg::to_self)
1894 pub fn has_self(&self) -> bool {
1895 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1899 /// Is the trait definition an auto trait?
1900 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1906 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1912 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1916 return_impl_trait_id: NodeId,
1922 pub fn is_async(self) -> bool {
1923 if let IsAsync::Async { .. } = self {
1930 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1931 pub fn opt_return_id(self) -> Option<NodeId> {
1934 return_impl_trait_id,
1936 } => Some(return_impl_trait_id),
1937 IsAsync::NotAsync => None,
1942 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1943 pub enum Constness {
1948 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1949 pub enum Defaultness {
1954 impl fmt::Display for Unsafety {
1955 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1958 Unsafety::Normal => "normal",
1959 Unsafety::Unsafe => "unsafe",
1966 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1967 pub enum ImplPolarity {
1968 /// `impl Trait for Type`
1970 /// `impl !Trait for Type`
1974 impl fmt::Debug for ImplPolarity {
1975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1977 ImplPolarity::Positive => "positive".fmt(f),
1978 ImplPolarity::Negative => "negative".fmt(f),
1983 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1984 pub enum FunctionRetTy {
1985 /// Returns type is not specified.
1987 /// Functions default to `()` and closures default to inference.
1988 /// Span points to where return type would be inserted.
1990 /// Everything else.
1994 impl FunctionRetTy {
1995 pub fn span(&self) -> Span {
1997 FunctionRetTy::Default(span) => span,
1998 FunctionRetTy::Ty(ref ty) => ty.span,
2003 /// Module declaration.
2005 /// E.g., `mod foo;` or `mod foo { .. }`.
2006 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2008 /// A span from the first token past `{` to the last token until `}`.
2009 /// For `mod foo;`, the inner span ranges from the first token
2010 /// to the last token in the external file.
2012 pub items: Vec<P<Item>>,
2013 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2017 /// Foreign module declaration.
2019 /// E.g., `extern { .. }` or `extern C { .. }`.
2020 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2021 pub struct ForeignMod {
2023 pub items: Vec<ForeignItem>,
2026 /// Global inline assembly.
2028 /// Also known as "module-level assembly" or "file-scoped assembly".
2029 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2030 pub struct GlobalAsm {
2032 pub ctxt: SyntaxContext,
2035 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2036 pub struct EnumDef {
2037 pub variants: Vec<Variant>,
2040 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2041 pub struct Variant_ {
2042 /// Name of the variant.
2044 /// Attributes of the variant.
2045 pub attrs: Vec<Attribute>,
2046 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2048 /// Fields and constructor id of the variant.
2049 pub data: VariantData,
2050 /// Explicit discriminant, e.g., `Foo = 1`.
2051 pub disr_expr: Option<AnonConst>,
2054 pub type Variant = Spanned<Variant_>;
2056 /// Part of `use` item to the right of its prefix.
2057 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2058 pub enum UseTreeKind {
2059 /// `use prefix` or `use prefix as rename`
2061 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2063 Simple(Option<Ident>, NodeId, NodeId),
2064 /// `use prefix::{...}`
2065 Nested(Vec<(UseTree, NodeId)>),
2070 /// A tree of paths sharing common prefixes.
2071 /// Used in `use` items both at top-level and inside of braces in import groups.
2072 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2073 pub struct UseTree {
2075 pub kind: UseTreeKind,
2080 pub fn ident(&self) -> Ident {
2082 UseTreeKind::Simple(Some(rename), ..) => rename,
2083 UseTreeKind::Simple(None, ..) => {
2087 .expect("empty prefix in a simple import")
2090 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2095 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2096 /// are contained as statements within items. These two cases need to be
2097 /// distinguished for pretty-printing.
2098 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
2099 pub enum AttrStyle {
2104 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2105 pub struct AttrId(pub usize);
2107 impl Idx for AttrId {
2108 fn new(idx: usize) -> Self {
2111 fn index(self) -> usize {
2116 impl rustc_serialize::Encodable for AttrId {
2117 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2122 impl rustc_serialize::Decodable for AttrId {
2123 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2124 d.read_nil().map(|_| crate::attr::mk_attr_id())
2128 /// Metadata associated with an item.
2129 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
2130 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2131 pub struct Attribute {
2133 pub style: AttrStyle,
2135 pub tokens: TokenStream,
2136 pub is_sugared_doc: bool,
2140 /// `TraitRef`s appear in impls.
2142 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2143 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2144 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2145 /// same as the impl's `NodeId`).
2146 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2147 pub struct TraitRef {
2152 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2153 pub struct PolyTraitRef {
2154 /// The `'a` in `<'a> Foo<&'a T>`.
2155 pub bound_generic_params: Vec<GenericParam>,
2157 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2158 pub trait_ref: TraitRef,
2164 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2166 bound_generic_params: generic_params,
2167 trait_ref: TraitRef {
2169 ref_id: DUMMY_NODE_ID,
2176 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2177 pub enum CrateSugar {
2178 /// Source is `pub(crate)`.
2181 /// Source is (just) `crate`.
2185 pub type Visibility = Spanned<VisibilityKind>;
2187 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2188 pub enum VisibilityKind {
2191 Restricted { path: P<Path>, id: NodeId },
2195 impl VisibilityKind {
2196 pub fn is_pub(&self) -> bool {
2197 if let VisibilityKind::Public = *self {
2205 /// Field of a struct.
2207 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2208 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2209 pub struct StructField {
2211 pub ident: Option<Ident>,
2212 pub vis: Visibility,
2215 pub attrs: Vec<Attribute>,
2218 /// Fields and constructor ids of enum variants and structs.
2219 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2220 pub enum VariantData {
2223 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2224 Struct(Vec<StructField>, bool),
2227 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2228 Tuple(Vec<StructField>, NodeId),
2231 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2236 /// Return the fields of this variant.
2237 pub fn fields(&self) -> &[StructField] {
2239 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2244 /// Return the `NodeId` of this variant's constructor, if it has one.
2245 pub fn ctor_id(&self) -> Option<NodeId> {
2247 VariantData::Struct(..) => None,
2248 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2255 /// The name might be a dummy name in case of anonymous items.
2256 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2259 pub attrs: Vec<Attribute>,
2262 pub vis: Visibility,
2265 /// Original tokens this item was parsed from. This isn't necessarily
2266 /// available for all items, although over time more and more items should
2267 /// have this be `Some`. Right now this is primarily used for procedural
2268 /// macros, notably custom attributes.
2270 /// Note that the tokens here do not include the outer attributes, but will
2271 /// include inner attributes.
2272 pub tokens: Option<TokenStream>,
2276 /// Return the span that encompasses the attributes.
2277 pub fn span_with_attributes(&self) -> Span {
2278 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2282 /// A function header.
2284 /// All the information between the visibility and the name of the function is
2285 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2286 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2287 pub struct FnHeader {
2288 pub unsafety: Unsafety,
2289 pub asyncness: Spanned<IsAsync>,
2290 pub constness: Spanned<Constness>,
2294 impl Default for FnHeader {
2295 fn default() -> FnHeader {
2297 unsafety: Unsafety::Normal,
2298 asyncness: dummy_spanned(IsAsync::NotAsync),
2299 constness: dummy_spanned(Constness::NotConst),
2305 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2307 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2309 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2310 ExternCrate(Option<Name>),
2311 /// A use declaration (`use` or `pub use`) item.
2313 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2315 /// A static item (`static` or `pub static`).
2317 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2318 Static(P<Ty>, Mutability, P<Expr>),
2319 /// A constant item (`const` or `pub const`).
2321 /// E.g., `const FOO: i32 = 42;`.
2322 Const(P<Ty>, P<Expr>),
2323 /// A function declaration (`fn` or `pub fn`).
2325 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2326 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2327 /// A module declaration (`mod` or `pub mod`).
2329 /// E.g., `mod foo;` or `mod foo { .. }`.
2331 /// An external module (`extern` or `pub extern`).
2333 /// E.g., `extern {}` or `extern "C" {}`.
2334 ForeignMod(ForeignMod),
2335 /// Module-level inline assembly (from `global_asm!()`).
2336 GlobalAsm(P<GlobalAsm>),
2337 /// A type alias (`type` or `pub type`).
2339 /// E.g., `type Foo = Bar<u8>;`.
2340 TyAlias(P<Ty>, Generics),
2341 /// An opaque `impl Trait` type alias.
2343 /// E.g., `type Foo = impl Bar + Boo;`.
2344 OpaqueTy(GenericBounds, Generics),
2345 /// An enum definition (`enum` or `pub enum`).
2347 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2348 Enum(EnumDef, Generics),
2349 /// A struct definition (`struct` or `pub struct`).
2351 /// E.g., `struct Foo<A> { x: A }`.
2352 Struct(VariantData, Generics),
2353 /// A union definition (`union` or `pub union`).
2355 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2356 Union(VariantData, Generics),
2357 /// A Trait declaration (`trait` or `pub trait`).
2359 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2360 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2363 /// E.g., `trait Foo = Bar + Quux;`.
2364 TraitAlias(Generics, GenericBounds),
2365 /// An implementation.
2367 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2373 Option<TraitRef>, // (optional) trait this impl implements
2377 /// A macro invocation.
2379 /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2382 /// A macro definition.
2387 pub fn descriptive_variant(&self) -> &str {
2389 ItemKind::ExternCrate(..) => "extern crate",
2390 ItemKind::Use(..) => "use",
2391 ItemKind::Static(..) => "static item",
2392 ItemKind::Const(..) => "constant item",
2393 ItemKind::Fn(..) => "function",
2394 ItemKind::Mod(..) => "module",
2395 ItemKind::ForeignMod(..) => "foreign module",
2396 ItemKind::GlobalAsm(..) => "global asm",
2397 ItemKind::TyAlias(..) => "type alias",
2398 ItemKind::OpaqueTy(..) => "opaque type",
2399 ItemKind::Enum(..) => "enum",
2400 ItemKind::Struct(..) => "struct",
2401 ItemKind::Union(..) => "union",
2402 ItemKind::Trait(..) => "trait",
2403 ItemKind::TraitAlias(..) => "trait alias",
2404 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2409 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2410 pub struct ForeignItem {
2412 pub attrs: Vec<Attribute>,
2413 pub node: ForeignItemKind,
2416 pub vis: Visibility,
2419 /// An item within an `extern` block.
2420 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2421 pub enum ForeignItemKind {
2422 /// A foreign function.
2423 Fn(P<FnDecl>, Generics),
2424 /// A foreign static item (`static ext: u8`).
2425 Static(P<Ty>, Mutability),
2428 /// A macro invocation.
2432 impl ForeignItemKind {
2433 pub fn descriptive_variant(&self) -> &str {
2435 ForeignItemKind::Fn(..) => "foreign function",
2436 ForeignItemKind::Static(..) => "foreign static item",
2437 ForeignItemKind::Ty => "foreign type",
2438 ForeignItemKind::Macro(..) => "macro in foreign module",