]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/ast.rs
Auto merge of #75138 - jumbatm:session-diagnostic-derive, r=oli-obk
[rust.git] / compiler / rustc_ast / src / ast.rs
1 //! The Rust abstract syntax tree module.
2 //!
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
7 //!
8 //! Other module items worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
20
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
24
25 use crate::ptr::P;
26 use crate::token::{self, CommentKind, DelimToken};
27 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
28
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::sync::Lrc;
31 use rustc_data_structures::thin_vec::ThinVec;
32 use rustc_macros::HashStable_Generic;
33 use rustc_serialize::{self, Decoder, Encoder};
34 use rustc_span::source_map::{respan, Spanned};
35 use rustc_span::symbol::{kw, sym, Ident, Symbol};
36 use rustc_span::{Span, DUMMY_SP};
37
38 use std::cmp::Ordering;
39 use std::convert::TryFrom;
40 use std::fmt;
41 use std::iter;
42
43 #[cfg(test)]
44 mod tests;
45
46 /// A "Label" is an identifier of some point in sources,
47 /// e.g. in the following code:
48 ///
49 /// ```rust
50 /// 'outer: loop {
51 ///     break 'outer;
52 /// }
53 /// ```
54 ///
55 /// `'outer` is a label.
56 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic)]
57 pub struct Label {
58     pub ident: Ident,
59 }
60
61 impl fmt::Debug for Label {
62     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63         write!(f, "label({:?})", self.ident)
64     }
65 }
66
67 /// A "Lifetime" is an annotation of the scope in which variable
68 /// can be used, e.g. `'a` in `&'a i32`.
69 #[derive(Clone, Encodable, Decodable, Copy)]
70 pub struct Lifetime {
71     pub id: NodeId,
72     pub ident: Ident,
73 }
74
75 impl fmt::Debug for Lifetime {
76     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77         write!(f, "lifetime({}: {})", self.id, self)
78     }
79 }
80
81 impl fmt::Display for Lifetime {
82     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83         write!(f, "{}", self.ident.name)
84     }
85 }
86
87 /// A "Path" is essentially Rust's notion of a name.
88 ///
89 /// It's represented as a sequence of identifiers,
90 /// along with a bunch of supporting information.
91 ///
92 /// E.g., `std::cmp::PartialEq`.
93 #[derive(Clone, Encodable, Decodable, Debug)]
94 pub struct Path {
95     pub span: Span,
96     /// The segments in the path: the things separated by `::`.
97     /// Global paths begin with `kw::PathRoot`.
98     pub segments: Vec<PathSegment>,
99 }
100
101 impl PartialEq<Symbol> for Path {
102     fn eq(&self, symbol: &Symbol) -> bool {
103         self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
104     }
105 }
106
107 impl<CTX> HashStable<CTX> for Path {
108     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
109         self.segments.len().hash_stable(hcx, hasher);
110         for segment in &self.segments {
111             segment.ident.name.hash_stable(hcx, hasher);
112         }
113     }
114 }
115
116 impl Path {
117     // Convert a span and an identifier to the corresponding
118     // one-segment path.
119     pub fn from_ident(ident: Ident) -> Path {
120         Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span }
121     }
122
123     pub fn is_global(&self) -> bool {
124         !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
125     }
126 }
127
128 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
129 ///
130 /// E.g., `std`, `String` or `Box<T>`.
131 #[derive(Clone, Encodable, Decodable, Debug)]
132 pub struct PathSegment {
133     /// The identifier portion of this path segment.
134     pub ident: Ident,
135
136     pub id: NodeId,
137
138     /// Type/lifetime parameters attached to this path. They come in
139     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
140     /// `None` means that no parameter list is supplied (`Path`),
141     /// `Some` means that parameter list is supplied (`Path<X, Y>`)
142     /// but it can be empty (`Path<>`).
143     /// `P` is used as a size optimization for the common case with no parameters.
144     pub args: Option<P<GenericArgs>>,
145 }
146
147 impl PathSegment {
148     pub fn from_ident(ident: Ident) -> Self {
149         PathSegment { ident, id: DUMMY_NODE_ID, args: None }
150     }
151     pub fn path_root(span: Span) -> Self {
152         PathSegment::from_ident(Ident::new(kw::PathRoot, span))
153     }
154 }
155
156 /// The arguments of a path segment.
157 ///
158 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
159 #[derive(Clone, Encodable, Decodable, Debug)]
160 pub enum GenericArgs {
161     /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
162     AngleBracketed(AngleBracketedArgs),
163     /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
164     Parenthesized(ParenthesizedArgs),
165 }
166
167 impl GenericArgs {
168     pub fn is_parenthesized(&self) -> bool {
169         match *self {
170             Parenthesized(..) => true,
171             _ => false,
172         }
173     }
174
175     pub fn is_angle_bracketed(&self) -> bool {
176         match *self {
177             AngleBracketed(..) => true,
178             _ => false,
179         }
180     }
181
182     pub fn span(&self) -> Span {
183         match *self {
184             AngleBracketed(ref data) => data.span,
185             Parenthesized(ref data) => data.span,
186         }
187     }
188 }
189
190 /// Concrete argument in the sequence of generic args.
191 #[derive(Clone, Encodable, Decodable, Debug)]
192 pub enum GenericArg {
193     /// `'a` in `Foo<'a>`
194     Lifetime(Lifetime),
195     /// `Bar` in `Foo<Bar>`
196     Type(P<Ty>),
197     /// `1` in `Foo<1>`
198     Const(AnonConst),
199 }
200
201 impl GenericArg {
202     pub fn span(&self) -> Span {
203         match self {
204             GenericArg::Lifetime(lt) => lt.ident.span,
205             GenericArg::Type(ty) => ty.span,
206             GenericArg::Const(ct) => ct.value.span,
207         }
208     }
209 }
210
211 /// A path like `Foo<'a, T>`.
212 #[derive(Clone, Encodable, Decodable, Debug, Default)]
213 pub struct AngleBracketedArgs {
214     /// The overall span.
215     pub span: Span,
216     /// The comma separated parts in the `<...>`.
217     pub args: Vec<AngleBracketedArg>,
218 }
219
220 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
221 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
222 #[derive(Clone, Encodable, Decodable, Debug)]
223 pub enum AngleBracketedArg {
224     /// Argument for a generic parameter.
225     Arg(GenericArg),
226     /// Constraint for an associated item.
227     Constraint(AssocTyConstraint),
228 }
229
230 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
231     fn into(self) -> Option<P<GenericArgs>> {
232         Some(P(GenericArgs::AngleBracketed(self)))
233     }
234 }
235
236 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
237     fn into(self) -> Option<P<GenericArgs>> {
238         Some(P(GenericArgs::Parenthesized(self)))
239     }
240 }
241
242 /// A path like `Foo(A, B) -> C`.
243 #[derive(Clone, Encodable, Decodable, Debug)]
244 pub struct ParenthesizedArgs {
245     /// Overall span
246     pub span: Span,
247
248     /// `(A, B)`
249     pub inputs: Vec<P<Ty>>,
250
251     /// `C`
252     pub output: FnRetTy,
253 }
254
255 impl ParenthesizedArgs {
256     pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
257         let args = self
258             .inputs
259             .iter()
260             .cloned()
261             .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
262             .collect();
263         AngleBracketedArgs { span: self.span, args }
264     }
265 }
266
267 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
268
269 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
270 ///
271 /// Negative bounds should also be handled here.
272 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
273 pub enum TraitBoundModifier {
274     /// No modifiers
275     None,
276
277     /// `?Trait`
278     Maybe,
279
280     /// `?const Trait`
281     MaybeConst,
282
283     /// `?const ?Trait`
284     //
285     // This parses but will be rejected during AST validation.
286     MaybeConstMaybe,
287 }
288
289 /// The AST represents all type param bounds as types.
290 /// `typeck::collect::compute_bounds` matches these against
291 /// the "special" built-in traits (see `middle::lang_items`) and
292 /// detects `Copy`, `Send` and `Sync`.
293 #[derive(Clone, Encodable, Decodable, Debug)]
294 pub enum GenericBound {
295     Trait(PolyTraitRef, TraitBoundModifier),
296     Outlives(Lifetime),
297 }
298
299 impl GenericBound {
300     pub fn span(&self) -> Span {
301         match self {
302             GenericBound::Trait(ref t, ..) => t.span,
303             GenericBound::Outlives(ref l) => l.ident.span,
304         }
305     }
306 }
307
308 pub type GenericBounds = Vec<GenericBound>;
309
310 /// Specifies the enforced ordering for generic parameters. In the future,
311 /// if we wanted to relax this order, we could override `PartialEq` and
312 /// `PartialOrd`, to allow the kinds to be unordered.
313 #[derive(Hash, Clone, Copy)]
314 pub enum ParamKindOrd {
315     Lifetime,
316     Type,
317     // `unordered` is only `true` if `sess.has_features().const_generics`
318     // is active. Specifically, if it's only `min_const_generics`, it will still require
319     // ordering consts after types.
320     Const { unordered: bool },
321 }
322
323 impl Ord for ParamKindOrd {
324     fn cmp(&self, other: &Self) -> Ordering {
325         use ParamKindOrd::*;
326         let to_int = |v| match v {
327             Lifetime => 0,
328             Type | Const { unordered: true } => 1,
329             // technically both consts should be ordered equally,
330             // but only one is ever encountered at a time, so this is
331             // fine.
332             Const { unordered: false } => 2,
333         };
334
335         to_int(*self).cmp(&to_int(*other))
336     }
337 }
338 impl PartialOrd for ParamKindOrd {
339     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
340         Some(self.cmp(other))
341     }
342 }
343 impl PartialEq for ParamKindOrd {
344     fn eq(&self, other: &Self) -> bool {
345         self.cmp(other) == Ordering::Equal
346     }
347 }
348 impl Eq for ParamKindOrd {}
349
350 impl fmt::Display for ParamKindOrd {
351     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352         match self {
353             ParamKindOrd::Lifetime => "lifetime".fmt(f),
354             ParamKindOrd::Type => "type".fmt(f),
355             ParamKindOrd::Const { .. } => "const".fmt(f),
356         }
357     }
358 }
359
360 #[derive(Clone, Encodable, Decodable, Debug)]
361 pub enum GenericParamKind {
362     /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
363     Lifetime,
364     Type {
365         default: Option<P<Ty>>,
366     },
367     Const {
368         ty: P<Ty>,
369         /// Span of the `const` keyword.
370         kw_span: Span,
371     },
372 }
373
374 #[derive(Clone, Encodable, Decodable, Debug)]
375 pub struct GenericParam {
376     pub id: NodeId,
377     pub ident: Ident,
378     pub attrs: AttrVec,
379     pub bounds: GenericBounds,
380     pub is_placeholder: bool,
381     pub kind: GenericParamKind,
382 }
383
384 /// Represents lifetime, type and const parameters attached to a declaration of
385 /// a function, enum, trait, etc.
386 #[derive(Clone, Encodable, Decodable, Debug)]
387 pub struct Generics {
388     pub params: Vec<GenericParam>,
389     pub where_clause: WhereClause,
390     pub span: Span,
391 }
392
393 impl Default for Generics {
394     /// Creates an instance of `Generics`.
395     fn default() -> Generics {
396         Generics {
397             params: Vec::new(),
398             where_clause: WhereClause {
399                 has_where_token: false,
400                 predicates: Vec::new(),
401                 span: DUMMY_SP,
402             },
403             span: DUMMY_SP,
404         }
405     }
406 }
407
408 /// A where-clause in a definition.
409 #[derive(Clone, Encodable, Decodable, Debug)]
410 pub struct WhereClause {
411     /// `true` if we ate a `where` token: this can happen
412     /// if we parsed no predicates (e.g. `struct Foo where {}`).
413     /// This allows us to accurately pretty-print
414     /// in `nt_to_tokenstream`
415     pub has_where_token: bool,
416     pub predicates: Vec<WherePredicate>,
417     pub span: Span,
418 }
419
420 /// A single predicate in a where-clause.
421 #[derive(Clone, Encodable, Decodable, Debug)]
422 pub enum WherePredicate {
423     /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
424     BoundPredicate(WhereBoundPredicate),
425     /// A lifetime predicate (e.g., `'a: 'b + 'c`).
426     RegionPredicate(WhereRegionPredicate),
427     /// An equality predicate (unsupported).
428     EqPredicate(WhereEqPredicate),
429 }
430
431 impl WherePredicate {
432     pub fn span(&self) -> Span {
433         match self {
434             &WherePredicate::BoundPredicate(ref p) => p.span,
435             &WherePredicate::RegionPredicate(ref p) => p.span,
436             &WherePredicate::EqPredicate(ref p) => p.span,
437         }
438     }
439 }
440
441 /// A type bound.
442 ///
443 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
444 #[derive(Clone, Encodable, Decodable, Debug)]
445 pub struct WhereBoundPredicate {
446     pub span: Span,
447     /// Any generics from a `for` binding.
448     pub bound_generic_params: Vec<GenericParam>,
449     /// The type being bounded.
450     pub bounded_ty: P<Ty>,
451     /// Trait and lifetime bounds (`Clone + Send + 'static`).
452     pub bounds: GenericBounds,
453 }
454
455 /// A lifetime predicate.
456 ///
457 /// E.g., `'a: 'b + 'c`.
458 #[derive(Clone, Encodable, Decodable, Debug)]
459 pub struct WhereRegionPredicate {
460     pub span: Span,
461     pub lifetime: Lifetime,
462     pub bounds: GenericBounds,
463 }
464
465 /// An equality predicate (unsupported).
466 ///
467 /// E.g., `T = int`.
468 #[derive(Clone, Encodable, Decodable, Debug)]
469 pub struct WhereEqPredicate {
470     pub id: NodeId,
471     pub span: Span,
472     pub lhs_ty: P<Ty>,
473     pub rhs_ty: P<Ty>,
474 }
475
476 #[derive(Clone, Encodable, Decodable, Debug)]
477 pub struct Crate {
478     pub module: Mod,
479     pub attrs: Vec<Attribute>,
480     pub span: Span,
481     /// The order of items in the HIR is unrelated to the order of
482     /// items in the AST. However, we generate proc macro harnesses
483     /// based on the AST order, and later refer to these harnesses
484     /// from the HIR. This field keeps track of the order in which
485     /// we generated proc macros harnesses, so that we can map
486     /// HIR proc macros items back to their harness items.
487     pub proc_macros: Vec<NodeId>,
488 }
489
490 /// Possible values inside of compile-time attribute lists.
491 ///
492 /// E.g., the '..' in `#[name(..)]`.
493 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
494 pub enum NestedMetaItem {
495     /// A full MetaItem, for recursive meta items.
496     MetaItem(MetaItem),
497     /// A literal.
498     ///
499     /// E.g., `"foo"`, `64`, `true`.
500     Literal(Lit),
501 }
502
503 /// A spanned compile-time attribute item.
504 ///
505 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
506 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
507 pub struct MetaItem {
508     pub path: Path,
509     pub kind: MetaItemKind,
510     pub span: Span,
511 }
512
513 /// A compile-time attribute item.
514 ///
515 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
516 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
517 pub enum MetaItemKind {
518     /// Word meta item.
519     ///
520     /// E.g., `test` as in `#[test]`.
521     Word,
522     /// List meta item.
523     ///
524     /// E.g., `derive(..)` as in `#[derive(..)]`.
525     List(Vec<NestedMetaItem>),
526     /// Name value meta item.
527     ///
528     /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
529     NameValue(Lit),
530 }
531
532 /// A block (`{ .. }`).
533 ///
534 /// E.g., `{ .. }` as in `fn foo() { .. }`.
535 #[derive(Clone, Encodable, Decodable, Debug)]
536 pub struct Block {
537     /// The statements in the block.
538     pub stmts: Vec<Stmt>,
539     pub id: NodeId,
540     /// Distinguishes between `unsafe { ... }` and `{ ... }`.
541     pub rules: BlockCheckMode,
542     pub span: Span,
543 }
544
545 /// A match pattern.
546 ///
547 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
548 #[derive(Clone, Encodable, Decodable, Debug)]
549 pub struct Pat {
550     pub id: NodeId,
551     pub kind: PatKind,
552     pub span: Span,
553     pub tokens: Option<TokenStream>,
554 }
555
556 impl Pat {
557     /// Attempt reparsing the pattern as a type.
558     /// This is intended for use by diagnostics.
559     pub fn to_ty(&self) -> Option<P<Ty>> {
560         let kind = match &self.kind {
561             // In a type expression `_` is an inference variable.
562             PatKind::Wild => TyKind::Infer,
563             // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
564             PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
565                 TyKind::Path(None, Path::from_ident(*ident))
566             }
567             PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
568             PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
569             // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
570             PatKind::Ref(pat, mutbl) => {
571                 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
572             }
573             // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
574             // when `P` can be reparsed as a type `T`.
575             PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
576             // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
577             // assuming `T0` to `Tn` are all syntactically valid as types.
578             PatKind::Tuple(pats) => {
579                 let mut tys = Vec::with_capacity(pats.len());
580                 // FIXME(#48994) - could just be collected into an Option<Vec>
581                 for pat in pats {
582                     tys.push(pat.to_ty()?);
583                 }
584                 TyKind::Tup(tys)
585             }
586             _ => return None,
587         };
588
589         Some(P(Ty { kind, id: self.id, span: self.span }))
590     }
591
592     /// Walk top-down and call `it` in each place where a pattern occurs
593     /// starting with the root pattern `walk` is called on. If `it` returns
594     /// false then we will descend no further but siblings will be processed.
595     pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
596         if !it(self) {
597             return;
598         }
599
600         match &self.kind {
601             // Walk into the pattern associated with `Ident` (if any).
602             PatKind::Ident(_, _, Some(p)) => p.walk(it),
603
604             // Walk into each field of struct.
605             PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
606
607             // Sequence of patterns.
608             PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
609                 s.iter().for_each(|p| p.walk(it))
610             }
611
612             // Trivial wrappers over inner patterns.
613             PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
614
615             // These patterns do not contain subpatterns, skip.
616             PatKind::Wild
617             | PatKind::Rest
618             | PatKind::Lit(_)
619             | PatKind::Range(..)
620             | PatKind::Ident(..)
621             | PatKind::Path(..)
622             | PatKind::MacCall(_) => {}
623         }
624     }
625
626     /// Is this a `..` pattern?
627     pub fn is_rest(&self) -> bool {
628         match self.kind {
629             PatKind::Rest => true,
630             _ => false,
631         }
632     }
633 }
634
635 /// A single field in a struct pattern
636 ///
637 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
638 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
639 /// except is_shorthand is true
640 #[derive(Clone, Encodable, Decodable, Debug)]
641 pub struct FieldPat {
642     /// The identifier for the field
643     pub ident: Ident,
644     /// The pattern the field is destructured to
645     pub pat: P<Pat>,
646     pub is_shorthand: bool,
647     pub attrs: AttrVec,
648     pub id: NodeId,
649     pub span: Span,
650     pub is_placeholder: bool,
651 }
652
653 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
654 pub enum BindingMode {
655     ByRef(Mutability),
656     ByValue(Mutability),
657 }
658
659 #[derive(Clone, Encodable, Decodable, Debug)]
660 pub enum RangeEnd {
661     Included(RangeSyntax),
662     Excluded,
663 }
664
665 #[derive(Clone, Encodable, Decodable, Debug)]
666 pub enum RangeSyntax {
667     /// `...`
668     DotDotDot,
669     /// `..=`
670     DotDotEq,
671 }
672
673 #[derive(Clone, Encodable, Decodable, Debug)]
674 pub enum PatKind {
675     /// Represents a wildcard pattern (`_`).
676     Wild,
677
678     /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
679     /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
680     /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
681     /// during name resolution.
682     Ident(BindingMode, Ident, Option<P<Pat>>),
683
684     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
685     /// The `bool` is `true` in the presence of a `..`.
686     Struct(Path, Vec<FieldPat>, /* recovered */ bool),
687
688     /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
689     TupleStruct(Path, Vec<P<Pat>>),
690
691     /// An or-pattern `A | B | C`.
692     /// Invariant: `pats.len() >= 2`.
693     Or(Vec<P<Pat>>),
694
695     /// A possibly qualified path pattern.
696     /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
697     /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
698     /// only legally refer to associated constants.
699     Path(Option<QSelf>, Path),
700
701     /// A tuple pattern (`(a, b)`).
702     Tuple(Vec<P<Pat>>),
703
704     /// A `box` pattern.
705     Box(P<Pat>),
706
707     /// A reference pattern (e.g., `&mut (a, b)`).
708     Ref(P<Pat>, Mutability),
709
710     /// A literal.
711     Lit(P<Expr>),
712
713     /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
714     Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
715
716     /// A slice pattern `[a, b, c]`.
717     Slice(Vec<P<Pat>>),
718
719     /// A rest pattern `..`.
720     ///
721     /// Syntactically it is valid anywhere.
722     ///
723     /// Semantically however, it only has meaning immediately inside:
724     /// - a slice pattern: `[a, .., b]`,
725     /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
726     /// - a tuple pattern: `(a, .., b)`,
727     /// - a tuple struct/variant pattern: `$path(a, .., b)`.
728     ///
729     /// In all of these cases, an additional restriction applies,
730     /// only one rest pattern may occur in the pattern sequences.
731     Rest,
732
733     /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
734     Paren(P<Pat>),
735
736     /// A macro pattern; pre-expansion.
737     MacCall(MacCall),
738 }
739
740 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
741 #[derive(HashStable_Generic, Encodable, Decodable)]
742 pub enum Mutability {
743     Mut,
744     Not,
745 }
746
747 impl Mutability {
748     /// Returns `MutMutable` only if both `self` and `other` are mutable.
749     pub fn and(self, other: Self) -> Self {
750         match self {
751             Mutability::Mut => other,
752             Mutability::Not => Mutability::Not,
753         }
754     }
755
756     pub fn invert(self) -> Self {
757         match self {
758             Mutability::Mut => Mutability::Not,
759             Mutability::Not => Mutability::Mut,
760         }
761     }
762
763     pub fn prefix_str(&self) -> &'static str {
764         match self {
765             Mutability::Mut => "mut ",
766             Mutability::Not => "",
767         }
768     }
769 }
770
771 /// The kind of borrow in an `AddrOf` expression,
772 /// e.g., `&place` or `&raw const place`.
773 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
774 #[derive(Encodable, Decodable, HashStable_Generic)]
775 pub enum BorrowKind {
776     /// A normal borrow, `&$expr` or `&mut $expr`.
777     /// The resulting type is either `&'a T` or `&'a mut T`
778     /// where `T = typeof($expr)` and `'a` is some lifetime.
779     Ref,
780     /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
781     /// The resulting type is either `*const T` or `*mut T`
782     /// where `T = typeof($expr)`.
783     Raw,
784 }
785
786 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
787 pub enum BinOpKind {
788     /// The `+` operator (addition)
789     Add,
790     /// The `-` operator (subtraction)
791     Sub,
792     /// The `*` operator (multiplication)
793     Mul,
794     /// The `/` operator (division)
795     Div,
796     /// The `%` operator (modulus)
797     Rem,
798     /// The `&&` operator (logical and)
799     And,
800     /// The `||` operator (logical or)
801     Or,
802     /// The `^` operator (bitwise xor)
803     BitXor,
804     /// The `&` operator (bitwise and)
805     BitAnd,
806     /// The `|` operator (bitwise or)
807     BitOr,
808     /// The `<<` operator (shift left)
809     Shl,
810     /// The `>>` operator (shift right)
811     Shr,
812     /// The `==` operator (equality)
813     Eq,
814     /// The `<` operator (less than)
815     Lt,
816     /// The `<=` operator (less than or equal to)
817     Le,
818     /// The `!=` operator (not equal to)
819     Ne,
820     /// The `>=` operator (greater than or equal to)
821     Ge,
822     /// The `>` operator (greater than)
823     Gt,
824 }
825
826 impl BinOpKind {
827     pub fn to_string(&self) -> &'static str {
828         use BinOpKind::*;
829         match *self {
830             Add => "+",
831             Sub => "-",
832             Mul => "*",
833             Div => "/",
834             Rem => "%",
835             And => "&&",
836             Or => "||",
837             BitXor => "^",
838             BitAnd => "&",
839             BitOr => "|",
840             Shl => "<<",
841             Shr => ">>",
842             Eq => "==",
843             Lt => "<",
844             Le => "<=",
845             Ne => "!=",
846             Ge => ">=",
847             Gt => ">",
848         }
849     }
850     pub fn lazy(&self) -> bool {
851         match *self {
852             BinOpKind::And | BinOpKind::Or => true,
853             _ => false,
854         }
855     }
856
857     pub fn is_shift(&self) -> bool {
858         match *self {
859             BinOpKind::Shl | BinOpKind::Shr => true,
860             _ => false,
861         }
862     }
863
864     pub fn is_comparison(&self) -> bool {
865         use BinOpKind::*;
866         // Note for developers: please keep this as is;
867         // we want compilation to fail if another variant is added.
868         match *self {
869             Eq | Lt | Le | Ne | Gt | Ge => true,
870             And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
871         }
872     }
873
874     /// Returns `true` if the binary operator takes its arguments by value
875     pub fn is_by_value(&self) -> bool {
876         !self.is_comparison()
877     }
878 }
879
880 pub type BinOp = Spanned<BinOpKind>;
881
882 /// Unary operator.
883 ///
884 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
885 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
886 pub enum UnOp {
887     /// The `*` operator for dereferencing
888     Deref,
889     /// The `!` operator for logical inversion
890     Not,
891     /// The `-` operator for negation
892     Neg,
893 }
894
895 impl UnOp {
896     /// Returns `true` if the unary operator takes its argument by value
897     pub fn is_by_value(u: UnOp) -> bool {
898         match u {
899             UnOp::Neg | UnOp::Not => true,
900             _ => false,
901         }
902     }
903
904     pub fn to_string(op: UnOp) -> &'static str {
905         match op {
906             UnOp::Deref => "*",
907             UnOp::Not => "!",
908             UnOp::Neg => "-",
909         }
910     }
911 }
912
913 /// A statement
914 #[derive(Clone, Encodable, Decodable, Debug)]
915 pub struct Stmt {
916     pub id: NodeId,
917     pub kind: StmtKind,
918     pub span: Span,
919 }
920
921 impl Stmt {
922     pub fn add_trailing_semicolon(mut self) -> Self {
923         self.kind = match self.kind {
924             StmtKind::Expr(expr) => StmtKind::Semi(expr),
925             StmtKind::MacCall(mac) => {
926                 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs }| MacCallStmt {
927                     mac,
928                     style: MacStmtStyle::Semicolon,
929                     attrs,
930                 }))
931             }
932             kind => kind,
933         };
934         self
935     }
936
937     pub fn is_item(&self) -> bool {
938         match self.kind {
939             StmtKind::Item(_) => true,
940             _ => false,
941         }
942     }
943
944     pub fn is_expr(&self) -> bool {
945         match self.kind {
946             StmtKind::Expr(_) => true,
947             _ => false,
948         }
949     }
950 }
951
952 #[derive(Clone, Encodable, Decodable, Debug)]
953 pub enum StmtKind {
954     /// A local (let) binding.
955     Local(P<Local>),
956     /// An item definition.
957     Item(P<Item>),
958     /// Expr without trailing semi-colon.
959     Expr(P<Expr>),
960     /// Expr with a trailing semi-colon.
961     Semi(P<Expr>),
962     /// Just a trailing semi-colon.
963     Empty,
964     /// Macro.
965     MacCall(P<MacCallStmt>),
966 }
967
968 #[derive(Clone, Encodable, Decodable, Debug)]
969 pub struct MacCallStmt {
970     pub mac: MacCall,
971     pub style: MacStmtStyle,
972     pub attrs: AttrVec,
973 }
974
975 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
976 pub enum MacStmtStyle {
977     /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
978     /// `foo!(...);`, `foo![...];`).
979     Semicolon,
980     /// The macro statement had braces (e.g., `foo! { ... }`).
981     Braces,
982     /// The macro statement had parentheses or brackets and no semicolon (e.g.,
983     /// `foo!(...)`). All of these will end up being converted into macro
984     /// expressions.
985     NoBraces,
986 }
987
988 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
989 #[derive(Clone, Encodable, Decodable, Debug)]
990 pub struct Local {
991     pub id: NodeId,
992     pub pat: P<Pat>,
993     pub ty: Option<P<Ty>>,
994     /// Initializer expression to set the value, if any.
995     pub init: Option<P<Expr>>,
996     pub span: Span,
997     pub attrs: AttrVec,
998 }
999
1000 /// An arm of a 'match'.
1001 ///
1002 /// E.g., `0..=10 => { println!("match!") }` as in
1003 ///
1004 /// ```
1005 /// match 123 {
1006 ///     0..=10 => { println!("match!") },
1007 ///     _ => { println!("no match!") },
1008 /// }
1009 /// ```
1010 #[derive(Clone, Encodable, Decodable, Debug)]
1011 pub struct Arm {
1012     pub attrs: Vec<Attribute>,
1013     /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1014     pub pat: P<Pat>,
1015     /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1016     pub guard: Option<P<Expr>>,
1017     /// Match arm body.
1018     pub body: P<Expr>,
1019     pub span: Span,
1020     pub id: NodeId,
1021     pub is_placeholder: bool,
1022 }
1023
1024 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1025 #[derive(Clone, Encodable, Decodable, Debug)]
1026 pub struct Field {
1027     pub attrs: AttrVec,
1028     pub id: NodeId,
1029     pub span: Span,
1030     pub ident: Ident,
1031     pub expr: P<Expr>,
1032     pub is_shorthand: bool,
1033     pub is_placeholder: bool,
1034 }
1035
1036 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1037 pub enum BlockCheckMode {
1038     Default,
1039     Unsafe(UnsafeSource),
1040 }
1041
1042 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1043 pub enum UnsafeSource {
1044     CompilerGenerated,
1045     UserProvided,
1046 }
1047
1048 /// A constant (expression) that's not an item or associated item,
1049 /// but needs its own `DefId` for type-checking, const-eval, etc.
1050 /// These are usually found nested inside types (e.g., array lengths)
1051 /// or expressions (e.g., repeat counts), and also used to define
1052 /// explicit discriminant values for enum variants.
1053 #[derive(Clone, Encodable, Decodable, Debug)]
1054 pub struct AnonConst {
1055     pub id: NodeId,
1056     pub value: P<Expr>,
1057 }
1058
1059 /// An expression.
1060 #[derive(Clone, Encodable, Decodable, Debug)]
1061 pub struct Expr {
1062     pub id: NodeId,
1063     pub kind: ExprKind,
1064     pub span: Span,
1065     pub attrs: AttrVec,
1066     pub tokens: Option<TokenStream>,
1067 }
1068
1069 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1070 #[cfg(target_arch = "x86_64")]
1071 rustc_data_structures::static_assert_size!(Expr, 104);
1072
1073 impl Expr {
1074     /// Returns `true` if this expression would be valid somewhere that expects a value;
1075     /// for example, an `if` condition.
1076     pub fn returns(&self) -> bool {
1077         if let ExprKind::Block(ref block, _) = self.kind {
1078             match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1079                 // Implicit return
1080                 Some(&StmtKind::Expr(_)) => true,
1081                 Some(&StmtKind::Semi(ref expr)) => {
1082                     if let ExprKind::Ret(_) = expr.kind {
1083                         // Last statement is explicit return.
1084                         true
1085                     } else {
1086                         false
1087                     }
1088                 }
1089                 // This is a block that doesn't end in either an implicit or explicit return.
1090                 _ => false,
1091             }
1092         } else {
1093             // This is not a block, it is a value.
1094             true
1095         }
1096     }
1097
1098     /// Is this expr either `N`, or `{ N }`.
1099     ///
1100     /// If this is not the case, name resolution does not resolve `N` when using
1101     /// `feature(min_const_generics)` as more complex expressions are not supported.
1102     pub fn is_potential_trivial_const_param(&self) -> bool {
1103         let this = if let ExprKind::Block(ref block, None) = self.kind {
1104             if block.stmts.len() == 1 {
1105                 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1106             } else {
1107                 self
1108             }
1109         } else {
1110             self
1111         };
1112
1113         if let ExprKind::Path(None, ref path) = this.kind {
1114             if path.segments.len() == 1 && path.segments[0].args.is_none() {
1115                 return true;
1116             }
1117         }
1118
1119         false
1120     }
1121
1122     pub fn to_bound(&self) -> Option<GenericBound> {
1123         match &self.kind {
1124             ExprKind::Path(None, path) => Some(GenericBound::Trait(
1125                 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1126                 TraitBoundModifier::None,
1127             )),
1128             _ => None,
1129         }
1130     }
1131
1132     /// Attempts to reparse as `Ty` (for diagnostic purposes).
1133     pub fn to_ty(&self) -> Option<P<Ty>> {
1134         let kind = match &self.kind {
1135             // Trivial conversions.
1136             ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1137             ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1138
1139             ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1140
1141             ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1142                 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1143             }
1144
1145             ExprKind::Repeat(expr, expr_len) => {
1146                 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1147             }
1148
1149             ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1150
1151             ExprKind::Tup(exprs) => {
1152                 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1153                 TyKind::Tup(tys)
1154             }
1155
1156             // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1157             // then type of result is trait object.
1158             // Otherwise we don't assume the result type.
1159             ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1160                 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1161                     TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1162                 } else {
1163                     return None;
1164                 }
1165             }
1166
1167             // This expression doesn't look like a type syntactically.
1168             _ => return None,
1169         };
1170
1171         Some(P(Ty { kind, id: self.id, span: self.span }))
1172     }
1173
1174     pub fn precedence(&self) -> ExprPrecedence {
1175         match self.kind {
1176             ExprKind::Box(_) => ExprPrecedence::Box,
1177             ExprKind::Array(_) => ExprPrecedence::Array,
1178             ExprKind::Call(..) => ExprPrecedence::Call,
1179             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1180             ExprKind::Tup(_) => ExprPrecedence::Tup,
1181             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1182             ExprKind::Unary(..) => ExprPrecedence::Unary,
1183             ExprKind::Lit(_) => ExprPrecedence::Lit,
1184             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1185             ExprKind::Let(..) => ExprPrecedence::Let,
1186             ExprKind::If(..) => ExprPrecedence::If,
1187             ExprKind::While(..) => ExprPrecedence::While,
1188             ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1189             ExprKind::Loop(..) => ExprPrecedence::Loop,
1190             ExprKind::Match(..) => ExprPrecedence::Match,
1191             ExprKind::Closure(..) => ExprPrecedence::Closure,
1192             ExprKind::Block(..) => ExprPrecedence::Block,
1193             ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1194             ExprKind::Async(..) => ExprPrecedence::Async,
1195             ExprKind::Await(..) => ExprPrecedence::Await,
1196             ExprKind::Assign(..) => ExprPrecedence::Assign,
1197             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1198             ExprKind::Field(..) => ExprPrecedence::Field,
1199             ExprKind::Index(..) => ExprPrecedence::Index,
1200             ExprKind::Range(..) => ExprPrecedence::Range,
1201             ExprKind::Path(..) => ExprPrecedence::Path,
1202             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1203             ExprKind::Break(..) => ExprPrecedence::Break,
1204             ExprKind::Continue(..) => ExprPrecedence::Continue,
1205             ExprKind::Ret(..) => ExprPrecedence::Ret,
1206             ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1207             ExprKind::MacCall(..) => ExprPrecedence::Mac,
1208             ExprKind::Struct(..) => ExprPrecedence::Struct,
1209             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1210             ExprKind::Paren(..) => ExprPrecedence::Paren,
1211             ExprKind::Try(..) => ExprPrecedence::Try,
1212             ExprKind::Yield(..) => ExprPrecedence::Yield,
1213             ExprKind::Err => ExprPrecedence::Err,
1214         }
1215     }
1216 }
1217
1218 /// Limit types of a range (inclusive or exclusive)
1219 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1220 pub enum RangeLimits {
1221     /// Inclusive at the beginning, exclusive at the end
1222     HalfOpen,
1223     /// Inclusive at the beginning and end
1224     Closed,
1225 }
1226
1227 #[derive(Clone, Encodable, Decodable, Debug)]
1228 pub enum ExprKind {
1229     /// A `box x` expression.
1230     Box(P<Expr>),
1231     /// An array (`[a, b, c, d]`)
1232     Array(Vec<P<Expr>>),
1233     /// A function call
1234     ///
1235     /// The first field resolves to the function itself,
1236     /// and the second field is the list of arguments.
1237     /// This also represents calling the constructor of
1238     /// tuple-like ADTs such as tuple structs and enum variants.
1239     Call(P<Expr>, Vec<P<Expr>>),
1240     /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1241     ///
1242     /// The `PathSegment` represents the method name and its generic arguments
1243     /// (within the angle brackets).
1244     /// The first element of the vector of an `Expr` is the expression that evaluates
1245     /// to the object on which the method is being called on (the receiver),
1246     /// and the remaining elements are the rest of the arguments.
1247     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1248     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1249     /// This `Span` is the span of the function, without the dot and receiver
1250     /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1251     MethodCall(PathSegment, Vec<P<Expr>>, Span),
1252     /// A tuple (e.g., `(a, b, c, d)`).
1253     Tup(Vec<P<Expr>>),
1254     /// A binary operation (e.g., `a + b`, `a * b`).
1255     Binary(BinOp, P<Expr>, P<Expr>),
1256     /// A unary operation (e.g., `!x`, `*x`).
1257     Unary(UnOp, P<Expr>),
1258     /// A literal (e.g., `1`, `"foo"`).
1259     Lit(Lit),
1260     /// A cast (e.g., `foo as f64`).
1261     Cast(P<Expr>, P<Ty>),
1262     /// A type ascription (e.g., `42: usize`).
1263     Type(P<Expr>, P<Ty>),
1264     /// A `let pat = expr` expression that is only semantically allowed in the condition
1265     /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1266     Let(P<Pat>, P<Expr>),
1267     /// An `if` block, with an optional `else` block.
1268     ///
1269     /// `if expr { block } else { expr }`
1270     If(P<Expr>, P<Block>, Option<P<Expr>>),
1271     /// A while loop, with an optional label.
1272     ///
1273     /// `'label: while expr { block }`
1274     While(P<Expr>, P<Block>, Option<Label>),
1275     /// A `for` loop, with an optional label.
1276     ///
1277     /// `'label: for pat in expr { block }`
1278     ///
1279     /// This is desugared to a combination of `loop` and `match` expressions.
1280     ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1281     /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1282     ///
1283     /// `'label: loop { block }`
1284     Loop(P<Block>, Option<Label>),
1285     /// A `match` block.
1286     Match(P<Expr>, Vec<Arm>),
1287     /// A closure (e.g., `move |a, b, c| a + b + c`).
1288     ///
1289     /// The final span is the span of the argument block `|...|`.
1290     Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1291     /// A block (`'label: { ... }`).
1292     Block(P<Block>, Option<Label>),
1293     /// An async block (`async move { ... }`).
1294     ///
1295     /// The `NodeId` is the `NodeId` for the closure that results from
1296     /// desugaring an async block, just like the NodeId field in the
1297     /// `Async::Yes` variant. This is necessary in order to create a def for the
1298     /// closure which can be used as a parent of any child defs. Defs
1299     /// created during lowering cannot be made the parent of any other
1300     /// preexisting defs.
1301     Async(CaptureBy, NodeId, P<Block>),
1302     /// An await expression (`my_future.await`).
1303     Await(P<Expr>),
1304
1305     /// A try block (`try { ... }`).
1306     TryBlock(P<Block>),
1307
1308     /// An assignment (`a = foo()`).
1309     /// The `Span` argument is the span of the `=` token.
1310     Assign(P<Expr>, P<Expr>, Span),
1311     /// An assignment with an operator.
1312     ///
1313     /// E.g., `a += 1`.
1314     AssignOp(BinOp, P<Expr>, P<Expr>),
1315     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1316     Field(P<Expr>, Ident),
1317     /// An indexing operation (e.g., `foo[2]`).
1318     Index(P<Expr>, P<Expr>),
1319     /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1320     Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1321
1322     /// Variable reference, possibly containing `::` and/or type
1323     /// parameters (e.g., `foo::bar::<baz>`).
1324     ///
1325     /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1326     Path(Option<QSelf>, Path),
1327
1328     /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1329     AddrOf(BorrowKind, Mutability, P<Expr>),
1330     /// A `break`, with an optional label to break, and an optional expression.
1331     Break(Option<Label>, Option<P<Expr>>),
1332     /// A `continue`, with an optional label.
1333     Continue(Option<Label>),
1334     /// A `return`, with an optional value to be returned.
1335     Ret(Option<P<Expr>>),
1336
1337     /// Output of the `asm!()` macro.
1338     InlineAsm(P<InlineAsm>),
1339     /// Output of the `llvm_asm!()` macro.
1340     LlvmInlineAsm(P<LlvmInlineAsm>),
1341
1342     /// A macro invocation; pre-expansion.
1343     MacCall(MacCall),
1344
1345     /// A struct literal expression.
1346     ///
1347     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1348     /// where `base` is the `Option<Expr>`.
1349     Struct(Path, Vec<Field>, Option<P<Expr>>),
1350
1351     /// An array literal constructed from one repeated element.
1352     ///
1353     /// E.g., `[1; 5]`. The expression is the element to be
1354     /// repeated; the constant is the number of times to repeat it.
1355     Repeat(P<Expr>, AnonConst),
1356
1357     /// No-op: used solely so we can pretty-print faithfully.
1358     Paren(P<Expr>),
1359
1360     /// A try expression (`expr?`).
1361     Try(P<Expr>),
1362
1363     /// A `yield`, with an optional value to be yielded.
1364     Yield(Option<P<Expr>>),
1365
1366     /// Placeholder for an expression that wasn't syntactically well formed in some way.
1367     Err,
1368 }
1369
1370 /// The explicit `Self` type in a "qualified path". The actual
1371 /// path, including the trait and the associated item, is stored
1372 /// separately. `position` represents the index of the associated
1373 /// item qualified with this `Self` type.
1374 ///
1375 /// ```ignore (only-for-syntax-highlight)
1376 /// <Vec<T> as a::b::Trait>::AssociatedItem
1377 ///  ^~~~~     ~~~~~~~~~~~~~~^
1378 ///  ty        position = 3
1379 ///
1380 /// <Vec<T>>::AssociatedItem
1381 ///  ^~~~~    ^
1382 ///  ty       position = 0
1383 /// ```
1384 #[derive(Clone, Encodable, Decodable, Debug)]
1385 pub struct QSelf {
1386     pub ty: P<Ty>,
1387
1388     /// The span of `a::b::Trait` in a path like `<Vec<T> as
1389     /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1390     /// 0`, this is an empty span.
1391     pub path_span: Span,
1392     pub position: usize,
1393 }
1394
1395 /// A capture clause used in closures and `async` blocks.
1396 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1397 pub enum CaptureBy {
1398     /// `move |x| y + x`.
1399     Value,
1400     /// `move` keyword was not specified.
1401     Ref,
1402 }
1403
1404 /// The movability of a generator / closure literal:
1405 /// whether a generator contains self-references, causing it to be `!Unpin`.
1406 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1407 #[derive(HashStable_Generic)]
1408 pub enum Movability {
1409     /// May contain self-references, `!Unpin`.
1410     Static,
1411     /// Must not contain self-references, `Unpin`.
1412     Movable,
1413 }
1414
1415 /// Represents a macro invocation. The `path` indicates which macro
1416 /// is being invoked, and the `args` are arguments passed to it.
1417 #[derive(Clone, Encodable, Decodable, Debug)]
1418 pub struct MacCall {
1419     pub path: Path,
1420     pub args: P<MacArgs>,
1421     pub prior_type_ascription: Option<(Span, bool)>,
1422 }
1423
1424 impl MacCall {
1425     pub fn span(&self) -> Span {
1426         self.path.span.to(self.args.span().unwrap_or(self.path.span))
1427     }
1428 }
1429
1430 /// Arguments passed to an attribute or a function-like macro.
1431 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1432 pub enum MacArgs {
1433     /// No arguments - `#[attr]`.
1434     Empty,
1435     /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1436     Delimited(DelimSpan, MacDelimiter, TokenStream),
1437     /// Arguments of a key-value attribute - `#[attr = "value"]`.
1438     Eq(
1439         /// Span of the `=` token.
1440         Span,
1441         /// Token stream of the "value".
1442         TokenStream,
1443     ),
1444 }
1445
1446 impl MacArgs {
1447     pub fn delim(&self) -> DelimToken {
1448         match self {
1449             MacArgs::Delimited(_, delim, _) => delim.to_token(),
1450             MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1451         }
1452     }
1453
1454     pub fn span(&self) -> Option<Span> {
1455         match *self {
1456             MacArgs::Empty => None,
1457             MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1458             MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1459         }
1460     }
1461
1462     /// Tokens inside the delimiters or after `=`.
1463     /// Proc macros see these tokens, for example.
1464     pub fn inner_tokens(&self) -> TokenStream {
1465         match self {
1466             MacArgs::Empty => TokenStream::default(),
1467             MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1468         }
1469     }
1470
1471     /// Tokens together with the delimiters or `=`.
1472     /// Use of this method generally means that something suboptimal or hacky is happening.
1473     pub fn outer_tokens(&self) -> TokenStream {
1474         match *self {
1475             MacArgs::Empty => TokenStream::default(),
1476             MacArgs::Delimited(dspan, delim, ref tokens) => {
1477                 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1478             }
1479             MacArgs::Eq(eq_span, ref tokens) => {
1480                 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1481             }
1482         }
1483     }
1484
1485     /// Whether a macro with these arguments needs a semicolon
1486     /// when used as a standalone item or statement.
1487     pub fn need_semicolon(&self) -> bool {
1488         !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1489     }
1490 }
1491
1492 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1493 pub enum MacDelimiter {
1494     Parenthesis,
1495     Bracket,
1496     Brace,
1497 }
1498
1499 impl MacDelimiter {
1500     pub fn to_token(self) -> DelimToken {
1501         match self {
1502             MacDelimiter::Parenthesis => DelimToken::Paren,
1503             MacDelimiter::Bracket => DelimToken::Bracket,
1504             MacDelimiter::Brace => DelimToken::Brace,
1505         }
1506     }
1507
1508     pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1509         match delim {
1510             token::Paren => Some(MacDelimiter::Parenthesis),
1511             token::Bracket => Some(MacDelimiter::Bracket),
1512             token::Brace => Some(MacDelimiter::Brace),
1513             token::NoDelim => None,
1514         }
1515     }
1516 }
1517
1518 /// Represents a macro definition.
1519 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1520 pub struct MacroDef {
1521     pub body: P<MacArgs>,
1522     /// `true` if macro was defined with `macro_rules`.
1523     pub macro_rules: bool,
1524 }
1525
1526 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1527 #[derive(HashStable_Generic)]
1528 pub enum StrStyle {
1529     /// A regular string, like `"foo"`.
1530     Cooked,
1531     /// A raw string, like `r##"foo"##`.
1532     ///
1533     /// The value is the number of `#` symbols used.
1534     Raw(u16),
1535 }
1536
1537 /// An AST literal.
1538 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1539 pub struct Lit {
1540     /// The original literal token as written in source code.
1541     pub token: token::Lit,
1542     /// The "semantic" representation of the literal lowered from the original tokens.
1543     /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1544     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1545     pub kind: LitKind,
1546     pub span: Span,
1547 }
1548
1549 /// Same as `Lit`, but restricted to string literals.
1550 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1551 pub struct StrLit {
1552     /// The original literal token as written in source code.
1553     pub style: StrStyle,
1554     pub symbol: Symbol,
1555     pub suffix: Option<Symbol>,
1556     pub span: Span,
1557     /// The unescaped "semantic" representation of the literal lowered from the original token.
1558     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1559     pub symbol_unescaped: Symbol,
1560 }
1561
1562 impl StrLit {
1563     pub fn as_lit(&self) -> Lit {
1564         let token_kind = match self.style {
1565             StrStyle::Cooked => token::Str,
1566             StrStyle::Raw(n) => token::StrRaw(n),
1567         };
1568         Lit {
1569             token: token::Lit::new(token_kind, self.symbol, self.suffix),
1570             span: self.span,
1571             kind: LitKind::Str(self.symbol_unescaped, self.style),
1572         }
1573     }
1574 }
1575
1576 /// Type of the integer literal based on provided suffix.
1577 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1578 #[derive(HashStable_Generic)]
1579 pub enum LitIntType {
1580     /// e.g. `42_i32`.
1581     Signed(IntTy),
1582     /// e.g. `42_u32`.
1583     Unsigned(UintTy),
1584     /// e.g. `42`.
1585     Unsuffixed,
1586 }
1587
1588 /// Type of the float literal based on provided suffix.
1589 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1590 #[derive(HashStable_Generic)]
1591 pub enum LitFloatType {
1592     /// A float literal with a suffix (`1f32` or `1E10f32`).
1593     Suffixed(FloatTy),
1594     /// A float literal without a suffix (`1.0 or 1.0E10`).
1595     Unsuffixed,
1596 }
1597
1598 /// Literal kind.
1599 ///
1600 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1601 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1602 pub enum LitKind {
1603     /// A string literal (`"foo"`).
1604     Str(Symbol, StrStyle),
1605     /// A byte string (`b"foo"`).
1606     ByteStr(Lrc<Vec<u8>>),
1607     /// A byte char (`b'f'`).
1608     Byte(u8),
1609     /// A character literal (`'a'`).
1610     Char(char),
1611     /// An integer literal (`1`).
1612     Int(u128, LitIntType),
1613     /// A float literal (`1f64` or `1E10f64`).
1614     Float(Symbol, LitFloatType),
1615     /// A boolean literal.
1616     Bool(bool),
1617     /// Placeholder for a literal that wasn't well-formed in some way.
1618     Err(Symbol),
1619 }
1620
1621 impl LitKind {
1622     /// Returns `true` if this literal is a string.
1623     pub fn is_str(&self) -> bool {
1624         match *self {
1625             LitKind::Str(..) => true,
1626             _ => false,
1627         }
1628     }
1629
1630     /// Returns `true` if this literal is byte literal string.
1631     pub fn is_bytestr(&self) -> bool {
1632         match self {
1633             LitKind::ByteStr(_) => true,
1634             _ => false,
1635         }
1636     }
1637
1638     /// Returns `true` if this is a numeric literal.
1639     pub fn is_numeric(&self) -> bool {
1640         match *self {
1641             LitKind::Int(..) | LitKind::Float(..) => true,
1642             _ => false,
1643         }
1644     }
1645
1646     /// Returns `true` if this literal has no suffix.
1647     /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1648     pub fn is_unsuffixed(&self) -> bool {
1649         !self.is_suffixed()
1650     }
1651
1652     /// Returns `true` if this literal has a suffix.
1653     pub fn is_suffixed(&self) -> bool {
1654         match *self {
1655             // suffixed variants
1656             LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1657             | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1658             // unsuffixed variants
1659             LitKind::Str(..)
1660             | LitKind::ByteStr(..)
1661             | LitKind::Byte(..)
1662             | LitKind::Char(..)
1663             | LitKind::Int(_, LitIntType::Unsuffixed)
1664             | LitKind::Float(_, LitFloatType::Unsuffixed)
1665             | LitKind::Bool(..)
1666             | LitKind::Err(..) => false,
1667         }
1668     }
1669 }
1670
1671 // N.B., If you change this, you'll probably want to change the corresponding
1672 // type structure in `middle/ty.rs` as well.
1673 #[derive(Clone, Encodable, Decodable, Debug)]
1674 pub struct MutTy {
1675     pub ty: P<Ty>,
1676     pub mutbl: Mutability,
1677 }
1678
1679 /// Represents a function's signature in a trait declaration,
1680 /// trait implementation, or free function.
1681 #[derive(Clone, Encodable, Decodable, Debug)]
1682 pub struct FnSig {
1683     pub header: FnHeader,
1684     pub decl: P<FnDecl>,
1685     pub span: Span,
1686 }
1687
1688 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1689 #[derive(Encodable, Decodable, HashStable_Generic)]
1690 pub enum FloatTy {
1691     F32,
1692     F64,
1693 }
1694
1695 impl FloatTy {
1696     pub fn name_str(self) -> &'static str {
1697         match self {
1698             FloatTy::F32 => "f32",
1699             FloatTy::F64 => "f64",
1700         }
1701     }
1702
1703     pub fn name(self) -> Symbol {
1704         match self {
1705             FloatTy::F32 => sym::f32,
1706             FloatTy::F64 => sym::f64,
1707         }
1708     }
1709
1710     pub fn bit_width(self) -> u64 {
1711         match self {
1712             FloatTy::F32 => 32,
1713             FloatTy::F64 => 64,
1714         }
1715     }
1716 }
1717
1718 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1719 #[derive(Encodable, Decodable, HashStable_Generic)]
1720 pub enum IntTy {
1721     Isize,
1722     I8,
1723     I16,
1724     I32,
1725     I64,
1726     I128,
1727 }
1728
1729 impl IntTy {
1730     pub fn name_str(&self) -> &'static str {
1731         match *self {
1732             IntTy::Isize => "isize",
1733             IntTy::I8 => "i8",
1734             IntTy::I16 => "i16",
1735             IntTy::I32 => "i32",
1736             IntTy::I64 => "i64",
1737             IntTy::I128 => "i128",
1738         }
1739     }
1740
1741     pub fn name(&self) -> Symbol {
1742         match *self {
1743             IntTy::Isize => sym::isize,
1744             IntTy::I8 => sym::i8,
1745             IntTy::I16 => sym::i16,
1746             IntTy::I32 => sym::i32,
1747             IntTy::I64 => sym::i64,
1748             IntTy::I128 => sym::i128,
1749         }
1750     }
1751
1752     pub fn val_to_string(&self, val: i128) -> String {
1753         // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1754         // are parsed as `u128`, so we wouldn't want to print an extra negative
1755         // sign.
1756         format!("{}{}", val as u128, self.name_str())
1757     }
1758
1759     pub fn bit_width(&self) -> Option<u64> {
1760         Some(match *self {
1761             IntTy::Isize => return None,
1762             IntTy::I8 => 8,
1763             IntTy::I16 => 16,
1764             IntTy::I32 => 32,
1765             IntTy::I64 => 64,
1766             IntTy::I128 => 128,
1767         })
1768     }
1769
1770     pub fn normalize(&self, target_width: u32) -> Self {
1771         match self {
1772             IntTy::Isize => match target_width {
1773                 16 => IntTy::I16,
1774                 32 => IntTy::I32,
1775                 64 => IntTy::I64,
1776                 _ => unreachable!(),
1777             },
1778             _ => *self,
1779         }
1780     }
1781 }
1782
1783 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1784 #[derive(Encodable, Decodable, HashStable_Generic)]
1785 pub enum UintTy {
1786     Usize,
1787     U8,
1788     U16,
1789     U32,
1790     U64,
1791     U128,
1792 }
1793
1794 impl UintTy {
1795     pub fn name_str(&self) -> &'static str {
1796         match *self {
1797             UintTy::Usize => "usize",
1798             UintTy::U8 => "u8",
1799             UintTy::U16 => "u16",
1800             UintTy::U32 => "u32",
1801             UintTy::U64 => "u64",
1802             UintTy::U128 => "u128",
1803         }
1804     }
1805
1806     pub fn name(&self) -> Symbol {
1807         match *self {
1808             UintTy::Usize => sym::usize,
1809             UintTy::U8 => sym::u8,
1810             UintTy::U16 => sym::u16,
1811             UintTy::U32 => sym::u32,
1812             UintTy::U64 => sym::u64,
1813             UintTy::U128 => sym::u128,
1814         }
1815     }
1816
1817     pub fn val_to_string(&self, val: u128) -> String {
1818         format!("{}{}", val, self.name_str())
1819     }
1820
1821     pub fn bit_width(&self) -> Option<u64> {
1822         Some(match *self {
1823             UintTy::Usize => return None,
1824             UintTy::U8 => 8,
1825             UintTy::U16 => 16,
1826             UintTy::U32 => 32,
1827             UintTy::U64 => 64,
1828             UintTy::U128 => 128,
1829         })
1830     }
1831
1832     pub fn normalize(&self, target_width: u32) -> Self {
1833         match self {
1834             UintTy::Usize => match target_width {
1835                 16 => UintTy::U16,
1836                 32 => UintTy::U32,
1837                 64 => UintTy::U64,
1838                 _ => unreachable!(),
1839             },
1840             _ => *self,
1841         }
1842     }
1843 }
1844
1845 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1846 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1847 #[derive(Clone, Encodable, Decodable, Debug)]
1848 pub struct AssocTyConstraint {
1849     pub id: NodeId,
1850     pub ident: Ident,
1851     pub kind: AssocTyConstraintKind,
1852     pub span: Span,
1853 }
1854
1855 /// The kinds of an `AssocTyConstraint`.
1856 #[derive(Clone, Encodable, Decodable, Debug)]
1857 pub enum AssocTyConstraintKind {
1858     /// E.g., `A = Bar` in `Foo<A = Bar>`.
1859     Equality { ty: P<Ty> },
1860     /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1861     Bound { bounds: GenericBounds },
1862 }
1863
1864 #[derive(Clone, Encodable, Decodable, Debug)]
1865 pub struct Ty {
1866     pub id: NodeId,
1867     pub kind: TyKind,
1868     pub span: Span,
1869 }
1870
1871 #[derive(Clone, Encodable, Decodable, Debug)]
1872 pub struct BareFnTy {
1873     pub unsafety: Unsafe,
1874     pub ext: Extern,
1875     pub generic_params: Vec<GenericParam>,
1876     pub decl: P<FnDecl>,
1877 }
1878
1879 /// The various kinds of type recognized by the compiler.
1880 #[derive(Clone, Encodable, Decodable, Debug)]
1881 pub enum TyKind {
1882     /// A variable-length slice (`[T]`).
1883     Slice(P<Ty>),
1884     /// A fixed length array (`[T; n]`).
1885     Array(P<Ty>, AnonConst),
1886     /// A raw pointer (`*const T` or `*mut T`).
1887     Ptr(MutTy),
1888     /// A reference (`&'a T` or `&'a mut T`).
1889     Rptr(Option<Lifetime>, MutTy),
1890     /// A bare function (e.g., `fn(usize) -> bool`).
1891     BareFn(P<BareFnTy>),
1892     /// The never type (`!`).
1893     Never,
1894     /// A tuple (`(A, B, C, D,...)`).
1895     Tup(Vec<P<Ty>>),
1896     /// A path (`module::module::...::Type`), optionally
1897     /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1898     ///
1899     /// Type parameters are stored in the `Path` itself.
1900     Path(Option<QSelf>, Path),
1901     /// A trait object type `Bound1 + Bound2 + Bound3`
1902     /// where `Bound` is a trait or a lifetime.
1903     TraitObject(GenericBounds, TraitObjectSyntax),
1904     /// An `impl Bound1 + Bound2 + Bound3` type
1905     /// where `Bound` is a trait or a lifetime.
1906     ///
1907     /// The `NodeId` exists to prevent lowering from having to
1908     /// generate `NodeId`s on the fly, which would complicate
1909     /// the generation of opaque `type Foo = impl Trait` items significantly.
1910     ImplTrait(NodeId, GenericBounds),
1911     /// No-op; kept solely so that we can pretty-print faithfully.
1912     Paren(P<Ty>),
1913     /// Unused for now.
1914     Typeof(AnonConst),
1915     /// This means the type should be inferred instead of it having been
1916     /// specified. This can appear anywhere in a type.
1917     Infer,
1918     /// Inferred type of a `self` or `&self` argument in a method.
1919     ImplicitSelf,
1920     /// A macro in the type position.
1921     MacCall(MacCall),
1922     /// Placeholder for a kind that has failed to be defined.
1923     Err,
1924     /// Placeholder for a `va_list`.
1925     CVarArgs,
1926 }
1927
1928 impl TyKind {
1929     pub fn is_implicit_self(&self) -> bool {
1930         if let TyKind::ImplicitSelf = *self { true } else { false }
1931     }
1932
1933     pub fn is_unit(&self) -> bool {
1934         if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1935     }
1936 }
1937
1938 /// Syntax used to declare a trait object.
1939 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1940 pub enum TraitObjectSyntax {
1941     Dyn,
1942     None,
1943 }
1944
1945 /// Inline assembly operand explicit register or register class.
1946 ///
1947 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1948 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1949 pub enum InlineAsmRegOrRegClass {
1950     Reg(Symbol),
1951     RegClass(Symbol),
1952 }
1953
1954 bitflags::bitflags! {
1955     #[derive(Encodable, Decodable, HashStable_Generic)]
1956     pub struct InlineAsmOptions: u8 {
1957         const PURE = 1 << 0;
1958         const NOMEM = 1 << 1;
1959         const READONLY = 1 << 2;
1960         const PRESERVES_FLAGS = 1 << 3;
1961         const NORETURN = 1 << 4;
1962         const NOSTACK = 1 << 5;
1963         const ATT_SYNTAX = 1 << 6;
1964     }
1965 }
1966
1967 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1968 pub enum InlineAsmTemplatePiece {
1969     String(String),
1970     Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1971 }
1972
1973 impl fmt::Display for InlineAsmTemplatePiece {
1974     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1975         match self {
1976             Self::String(s) => {
1977                 for c in s.chars() {
1978                     match c {
1979                         '{' => f.write_str("{{")?,
1980                         '}' => f.write_str("}}")?,
1981                         _ => c.fmt(f)?,
1982                     }
1983                 }
1984                 Ok(())
1985             }
1986             Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
1987                 write!(f, "{{{}:{}}}", operand_idx, modifier)
1988             }
1989             Self::Placeholder { operand_idx, modifier: None, .. } => {
1990                 write!(f, "{{{}}}", operand_idx)
1991             }
1992         }
1993     }
1994 }
1995
1996 impl InlineAsmTemplatePiece {
1997     /// Rebuilds the asm template string from its pieces.
1998     pub fn to_string(s: &[Self]) -> String {
1999         use fmt::Write;
2000         let mut out = String::new();
2001         for p in s.iter() {
2002             let _ = write!(out, "{}", p);
2003         }
2004         out
2005     }
2006 }
2007
2008 /// Inline assembly operand.
2009 ///
2010 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2011 #[derive(Clone, Encodable, Decodable, Debug)]
2012 pub enum InlineAsmOperand {
2013     In {
2014         reg: InlineAsmRegOrRegClass,
2015         expr: P<Expr>,
2016     },
2017     Out {
2018         reg: InlineAsmRegOrRegClass,
2019         late: bool,
2020         expr: Option<P<Expr>>,
2021     },
2022     InOut {
2023         reg: InlineAsmRegOrRegClass,
2024         late: bool,
2025         expr: P<Expr>,
2026     },
2027     SplitInOut {
2028         reg: InlineAsmRegOrRegClass,
2029         late: bool,
2030         in_expr: P<Expr>,
2031         out_expr: Option<P<Expr>>,
2032     },
2033     Const {
2034         expr: P<Expr>,
2035     },
2036     Sym {
2037         expr: P<Expr>,
2038     },
2039 }
2040
2041 /// Inline assembly.
2042 ///
2043 /// E.g., `asm!("NOP");`.
2044 #[derive(Clone, Encodable, Decodable, Debug)]
2045 pub struct InlineAsm {
2046     pub template: Vec<InlineAsmTemplatePiece>,
2047     pub operands: Vec<(InlineAsmOperand, Span)>,
2048     pub options: InlineAsmOptions,
2049     pub line_spans: Vec<Span>,
2050 }
2051
2052 /// Inline assembly dialect.
2053 ///
2054 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2055 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2056 pub enum LlvmAsmDialect {
2057     Att,
2058     Intel,
2059 }
2060
2061 /// LLVM-style inline assembly.
2062 ///
2063 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2064 #[derive(Clone, Encodable, Decodable, Debug)]
2065 pub struct LlvmInlineAsmOutput {
2066     pub constraint: Symbol,
2067     pub expr: P<Expr>,
2068     pub is_rw: bool,
2069     pub is_indirect: bool,
2070 }
2071
2072 /// LLVM-style inline assembly.
2073 ///
2074 /// E.g., `llvm_asm!("NOP");`.
2075 #[derive(Clone, Encodable, Decodable, Debug)]
2076 pub struct LlvmInlineAsm {
2077     pub asm: Symbol,
2078     pub asm_str_style: StrStyle,
2079     pub outputs: Vec<LlvmInlineAsmOutput>,
2080     pub inputs: Vec<(Symbol, P<Expr>)>,
2081     pub clobbers: Vec<Symbol>,
2082     pub volatile: bool,
2083     pub alignstack: bool,
2084     pub dialect: LlvmAsmDialect,
2085 }
2086
2087 /// A parameter in a function header.
2088 ///
2089 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2090 #[derive(Clone, Encodable, Decodable, Debug)]
2091 pub struct Param {
2092     pub attrs: AttrVec,
2093     pub ty: P<Ty>,
2094     pub pat: P<Pat>,
2095     pub id: NodeId,
2096     pub span: Span,
2097     pub is_placeholder: bool,
2098 }
2099
2100 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2101 ///
2102 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2103 #[derive(Clone, Encodable, Decodable, Debug)]
2104 pub enum SelfKind {
2105     /// `self`, `mut self`
2106     Value(Mutability),
2107     /// `&'lt self`, `&'lt mut self`
2108     Region(Option<Lifetime>, Mutability),
2109     /// `self: TYPE`, `mut self: TYPE`
2110     Explicit(P<Ty>, Mutability),
2111 }
2112
2113 pub type ExplicitSelf = Spanned<SelfKind>;
2114
2115 impl Param {
2116     /// Attempts to cast parameter to `ExplicitSelf`.
2117     pub fn to_self(&self) -> Option<ExplicitSelf> {
2118         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2119             if ident.name == kw::SelfLower {
2120                 return match self.ty.kind {
2121                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2122                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2123                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2124                     }
2125                     _ => Some(respan(
2126                         self.pat.span.to(self.ty.span),
2127                         SelfKind::Explicit(self.ty.clone(), mutbl),
2128                     )),
2129                 };
2130             }
2131         }
2132         None
2133     }
2134
2135     /// Returns `true` if parameter is `self`.
2136     pub fn is_self(&self) -> bool {
2137         if let PatKind::Ident(_, ident, _) = self.pat.kind {
2138             ident.name == kw::SelfLower
2139         } else {
2140             false
2141         }
2142     }
2143
2144     /// Builds a `Param` object from `ExplicitSelf`.
2145     pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2146         let span = eself.span.to(eself_ident.span);
2147         let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2148         let param = |mutbl, ty| Param {
2149             attrs,
2150             pat: P(Pat {
2151                 id: DUMMY_NODE_ID,
2152                 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2153                 span,
2154                 tokens: None,
2155             }),
2156             span,
2157             ty,
2158             id: DUMMY_NODE_ID,
2159             is_placeholder: false,
2160         };
2161         match eself.node {
2162             SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2163             SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2164             SelfKind::Region(lt, mutbl) => param(
2165                 Mutability::Not,
2166                 P(Ty {
2167                     id: DUMMY_NODE_ID,
2168                     kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2169                     span,
2170                 }),
2171             ),
2172         }
2173     }
2174 }
2175
2176 /// A signature (not the body) of a function declaration.
2177 ///
2178 /// E.g., `fn foo(bar: baz)`.
2179 ///
2180 /// Please note that it's different from `FnHeader` structure
2181 /// which contains metadata about function safety, asyncness, constness and ABI.
2182 #[derive(Clone, Encodable, Decodable, Debug)]
2183 pub struct FnDecl {
2184     pub inputs: Vec<Param>,
2185     pub output: FnRetTy,
2186 }
2187
2188 impl FnDecl {
2189     pub fn get_self(&self) -> Option<ExplicitSelf> {
2190         self.inputs.get(0).and_then(Param::to_self)
2191     }
2192     pub fn has_self(&self) -> bool {
2193         self.inputs.get(0).map_or(false, Param::is_self)
2194     }
2195     pub fn c_variadic(&self) -> bool {
2196         self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2197             TyKind::CVarArgs => true,
2198             _ => false,
2199         })
2200     }
2201 }
2202
2203 /// Is the trait definition an auto trait?
2204 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2205 pub enum IsAuto {
2206     Yes,
2207     No,
2208 }
2209
2210 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2211 #[derive(HashStable_Generic)]
2212 pub enum Unsafe {
2213     Yes(Span),
2214     No,
2215 }
2216
2217 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2218 pub enum Async {
2219     Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2220     No,
2221 }
2222
2223 impl Async {
2224     pub fn is_async(self) -> bool {
2225         if let Async::Yes { .. } = self { true } else { false }
2226     }
2227
2228     /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2229     pub fn opt_return_id(self) -> Option<NodeId> {
2230         match self {
2231             Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2232             Async::No => None,
2233         }
2234     }
2235 }
2236
2237 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2238 #[derive(HashStable_Generic)]
2239 pub enum Const {
2240     Yes(Span),
2241     No,
2242 }
2243
2244 /// Item defaultness.
2245 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2246 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2247 pub enum Defaultness {
2248     Default(Span),
2249     Final,
2250 }
2251
2252 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2253 pub enum ImplPolarity {
2254     /// `impl Trait for Type`
2255     Positive,
2256     /// `impl !Trait for Type`
2257     Negative(Span),
2258 }
2259
2260 impl fmt::Debug for ImplPolarity {
2261     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2262         match *self {
2263             ImplPolarity::Positive => "positive".fmt(f),
2264             ImplPolarity::Negative(_) => "negative".fmt(f),
2265         }
2266     }
2267 }
2268
2269 #[derive(Clone, Encodable, Decodable, Debug)]
2270 pub enum FnRetTy {
2271     /// Returns type is not specified.
2272     ///
2273     /// Functions default to `()` and closures default to inference.
2274     /// Span points to where return type would be inserted.
2275     Default(Span),
2276     /// Everything else.
2277     Ty(P<Ty>),
2278 }
2279
2280 impl FnRetTy {
2281     pub fn span(&self) -> Span {
2282         match *self {
2283             FnRetTy::Default(span) => span,
2284             FnRetTy::Ty(ref ty) => ty.span,
2285         }
2286     }
2287 }
2288
2289 /// Module declaration.
2290 ///
2291 /// E.g., `mod foo;` or `mod foo { .. }`.
2292 #[derive(Clone, Encodable, Decodable, Debug, Default)]
2293 pub struct Mod {
2294     /// A span from the first token past `{` to the last token until `}`.
2295     /// For `mod foo;`, the inner span ranges from the first token
2296     /// to the last token in the external file.
2297     pub inner: Span,
2298     pub items: Vec<P<Item>>,
2299     /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2300     pub inline: bool,
2301 }
2302
2303 /// Foreign module declaration.
2304 ///
2305 /// E.g., `extern { .. }` or `extern C { .. }`.
2306 #[derive(Clone, Encodable, Decodable, Debug)]
2307 pub struct ForeignMod {
2308     pub abi: Option<StrLit>,
2309     pub items: Vec<P<ForeignItem>>,
2310 }
2311
2312 /// Global inline assembly.
2313 ///
2314 /// Also known as "module-level assembly" or "file-scoped assembly".
2315 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2316 pub struct GlobalAsm {
2317     pub asm: Symbol,
2318 }
2319
2320 #[derive(Clone, Encodable, Decodable, Debug)]
2321 pub struct EnumDef {
2322     pub variants: Vec<Variant>,
2323 }
2324 /// Enum variant.
2325 #[derive(Clone, Encodable, Decodable, Debug)]
2326 pub struct Variant {
2327     /// Attributes of the variant.
2328     pub attrs: Vec<Attribute>,
2329     /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2330     pub id: NodeId,
2331     /// Span
2332     pub span: Span,
2333     /// The visibility of the variant. Syntactically accepted but not semantically.
2334     pub vis: Visibility,
2335     /// Name of the variant.
2336     pub ident: Ident,
2337
2338     /// Fields and constructor id of the variant.
2339     pub data: VariantData,
2340     /// Explicit discriminant, e.g., `Foo = 1`.
2341     pub disr_expr: Option<AnonConst>,
2342     /// Is a macro placeholder
2343     pub is_placeholder: bool,
2344 }
2345
2346 /// Part of `use` item to the right of its prefix.
2347 #[derive(Clone, Encodable, Decodable, Debug)]
2348 pub enum UseTreeKind {
2349     /// `use prefix` or `use prefix as rename`
2350     ///
2351     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2352     /// namespace.
2353     Simple(Option<Ident>, NodeId, NodeId),
2354     /// `use prefix::{...}`
2355     Nested(Vec<(UseTree, NodeId)>),
2356     /// `use prefix::*`
2357     Glob,
2358 }
2359
2360 /// A tree of paths sharing common prefixes.
2361 /// Used in `use` items both at top-level and inside of braces in import groups.
2362 #[derive(Clone, Encodable, Decodable, Debug)]
2363 pub struct UseTree {
2364     pub prefix: Path,
2365     pub kind: UseTreeKind,
2366     pub span: Span,
2367 }
2368
2369 impl UseTree {
2370     pub fn ident(&self) -> Ident {
2371         match self.kind {
2372             UseTreeKind::Simple(Some(rename), ..) => rename,
2373             UseTreeKind::Simple(None, ..) => {
2374                 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2375             }
2376             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2377         }
2378     }
2379 }
2380
2381 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2382 /// are contained as statements within items. These two cases need to be
2383 /// distinguished for pretty-printing.
2384 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2385 pub enum AttrStyle {
2386     Outer,
2387     Inner,
2388 }
2389
2390 rustc_index::newtype_index! {
2391     pub struct AttrId {
2392         ENCODABLE = custom
2393         DEBUG_FORMAT = "AttrId({})"
2394     }
2395 }
2396
2397 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2398     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2399         s.emit_unit()
2400     }
2401 }
2402
2403 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2404     fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2405         d.read_nil().map(|_| crate::attr::mk_attr_id())
2406     }
2407 }
2408
2409 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2410 pub struct AttrItem {
2411     pub path: Path,
2412     pub args: MacArgs,
2413 }
2414
2415 /// A list of attributes.
2416 pub type AttrVec = ThinVec<Attribute>;
2417
2418 /// Metadata associated with an item.
2419 #[derive(Clone, Encodable, Decodable, Debug)]
2420 pub struct Attribute {
2421     pub kind: AttrKind,
2422     pub id: AttrId,
2423     /// Denotes if the attribute decorates the following construct (outer)
2424     /// or the construct this attribute is contained within (inner).
2425     pub style: AttrStyle,
2426     pub span: Span,
2427 }
2428
2429 #[derive(Clone, Encodable, Decodable, Debug)]
2430 pub enum AttrKind {
2431     /// A normal attribute.
2432     Normal(AttrItem),
2433
2434     /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2435     /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2436     /// variant (which is much less compact and thus more expensive).
2437     DocComment(CommentKind, Symbol),
2438 }
2439
2440 /// `TraitRef`s appear in impls.
2441 ///
2442 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2443 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2444 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2445 /// same as the impl's `NodeId`).
2446 #[derive(Clone, Encodable, Decodable, Debug)]
2447 pub struct TraitRef {
2448     pub path: Path,
2449     pub ref_id: NodeId,
2450 }
2451
2452 #[derive(Clone, Encodable, Decodable, Debug)]
2453 pub struct PolyTraitRef {
2454     /// The `'a` in `<'a> Foo<&'a T>`.
2455     pub bound_generic_params: Vec<GenericParam>,
2456
2457     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2458     pub trait_ref: TraitRef,
2459
2460     pub span: Span,
2461 }
2462
2463 impl PolyTraitRef {
2464     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2465         PolyTraitRef {
2466             bound_generic_params: generic_params,
2467             trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2468             span,
2469         }
2470     }
2471 }
2472
2473 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2474 pub enum CrateSugar {
2475     /// Source is `pub(crate)`.
2476     PubCrate,
2477
2478     /// Source is (just) `crate`.
2479     JustCrate,
2480 }
2481
2482 pub type Visibility = Spanned<VisibilityKind>;
2483
2484 #[derive(Clone, Encodable, Decodable, Debug)]
2485 pub enum VisibilityKind {
2486     Public,
2487     Crate(CrateSugar),
2488     Restricted { path: P<Path>, id: NodeId },
2489     Inherited,
2490 }
2491
2492 impl VisibilityKind {
2493     pub fn is_pub(&self) -> bool {
2494         if let VisibilityKind::Public = *self { true } else { false }
2495     }
2496 }
2497
2498 /// Field of a struct.
2499 ///
2500 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2501 #[derive(Clone, Encodable, Decodable, Debug)]
2502 pub struct StructField {
2503     pub attrs: Vec<Attribute>,
2504     pub id: NodeId,
2505     pub span: Span,
2506     pub vis: Visibility,
2507     pub ident: Option<Ident>,
2508
2509     pub ty: P<Ty>,
2510     pub is_placeholder: bool,
2511 }
2512
2513 /// Fields and constructor ids of enum variants and structs.
2514 #[derive(Clone, Encodable, Decodable, Debug)]
2515 pub enum VariantData {
2516     /// Struct variant.
2517     ///
2518     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2519     Struct(Vec<StructField>, bool),
2520     /// Tuple variant.
2521     ///
2522     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2523     Tuple(Vec<StructField>, NodeId),
2524     /// Unit variant.
2525     ///
2526     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2527     Unit(NodeId),
2528 }
2529
2530 impl VariantData {
2531     /// Return the fields of this variant.
2532     pub fn fields(&self) -> &[StructField] {
2533         match *self {
2534             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2535             _ => &[],
2536         }
2537     }
2538
2539     /// Return the `NodeId` of this variant's constructor, if it has one.
2540     pub fn ctor_id(&self) -> Option<NodeId> {
2541         match *self {
2542             VariantData::Struct(..) => None,
2543             VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2544         }
2545     }
2546 }
2547
2548 /// An item definition.
2549 #[derive(Clone, Encodable, Decodable, Debug)]
2550 pub struct Item<K = ItemKind> {
2551     pub attrs: Vec<Attribute>,
2552     pub id: NodeId,
2553     pub span: Span,
2554     pub vis: Visibility,
2555     /// The name of the item.
2556     /// It might be a dummy name in case of anonymous items.
2557     pub ident: Ident,
2558
2559     pub kind: K,
2560
2561     /// Original tokens this item was parsed from. This isn't necessarily
2562     /// available for all items, although over time more and more items should
2563     /// have this be `Some`. Right now this is primarily used for procedural
2564     /// macros, notably custom attributes.
2565     ///
2566     /// Note that the tokens here do not include the outer attributes, but will
2567     /// include inner attributes.
2568     pub tokens: Option<TokenStream>,
2569 }
2570
2571 impl Item {
2572     /// Return the span that encompasses the attributes.
2573     pub fn span_with_attributes(&self) -> Span {
2574         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2575     }
2576 }
2577
2578 impl<K: Into<ItemKind>> Item<K> {
2579     pub fn into_item(self) -> Item {
2580         let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2581         Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2582     }
2583 }
2584
2585 /// `extern` qualifier on a function item or function type.
2586 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2587 pub enum Extern {
2588     None,
2589     Implicit,
2590     Explicit(StrLit),
2591 }
2592
2593 impl Extern {
2594     pub fn from_abi(abi: Option<StrLit>) -> Extern {
2595         abi.map_or(Extern::Implicit, Extern::Explicit)
2596     }
2597 }
2598
2599 /// A function header.
2600 ///
2601 /// All the information between the visibility and the name of the function is
2602 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2603 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2604 pub struct FnHeader {
2605     pub unsafety: Unsafe,
2606     pub asyncness: Async,
2607     pub constness: Const,
2608     pub ext: Extern,
2609 }
2610
2611 impl FnHeader {
2612     /// Does this function header have any qualifiers or is it empty?
2613     pub fn has_qualifiers(&self) -> bool {
2614         let Self { unsafety, asyncness, constness, ext } = self;
2615         matches!(unsafety, Unsafe::Yes(_))
2616             || asyncness.is_async()
2617             || matches!(constness, Const::Yes(_))
2618             || !matches!(ext, Extern::None)
2619     }
2620 }
2621
2622 impl Default for FnHeader {
2623     fn default() -> FnHeader {
2624         FnHeader {
2625             unsafety: Unsafe::No,
2626             asyncness: Async::No,
2627             constness: Const::No,
2628             ext: Extern::None,
2629         }
2630     }
2631 }
2632
2633 #[derive(Clone, Encodable, Decodable, Debug)]
2634 pub enum ItemKind {
2635     /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2636     ///
2637     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2638     ExternCrate(Option<Symbol>),
2639     /// A use declaration item (`use`).
2640     ///
2641     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2642     Use(P<UseTree>),
2643     /// A static item (`static`).
2644     ///
2645     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2646     Static(P<Ty>, Mutability, Option<P<Expr>>),
2647     /// A constant item (`const`).
2648     ///
2649     /// E.g., `const FOO: i32 = 42;`.
2650     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2651     /// A function declaration (`fn`).
2652     ///
2653     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2654     Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2655     /// A module declaration (`mod`).
2656     ///
2657     /// E.g., `mod foo;` or `mod foo { .. }`.
2658     Mod(Mod),
2659     /// An external module (`extern`).
2660     ///
2661     /// E.g., `extern {}` or `extern "C" {}`.
2662     ForeignMod(ForeignMod),
2663     /// Module-level inline assembly (from `global_asm!()`).
2664     GlobalAsm(P<GlobalAsm>),
2665     /// A type alias (`type`).
2666     ///
2667     /// E.g., `type Foo = Bar<u8>;`.
2668     TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2669     /// An enum definition (`enum`).
2670     ///
2671     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2672     Enum(EnumDef, Generics),
2673     /// A struct definition (`struct`).
2674     ///
2675     /// E.g., `struct Foo<A> { x: A }`.
2676     Struct(VariantData, Generics),
2677     /// A union definition (`union`).
2678     ///
2679     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2680     Union(VariantData, Generics),
2681     /// A trait declaration (`trait`).
2682     ///
2683     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2684     Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2685     /// Trait alias
2686     ///
2687     /// E.g., `trait Foo = Bar + Quux;`.
2688     TraitAlias(Generics, GenericBounds),
2689     /// An implementation.
2690     ///
2691     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2692     Impl {
2693         unsafety: Unsafe,
2694         polarity: ImplPolarity,
2695         defaultness: Defaultness,
2696         constness: Const,
2697         generics: Generics,
2698
2699         /// The trait being implemented, if any.
2700         of_trait: Option<TraitRef>,
2701
2702         self_ty: P<Ty>,
2703         items: Vec<P<AssocItem>>,
2704     },
2705     /// A macro invocation.
2706     ///
2707     /// E.g., `foo!(..)`.
2708     MacCall(MacCall),
2709
2710     /// A macro definition.
2711     MacroDef(MacroDef),
2712 }
2713
2714 impl ItemKind {
2715     pub fn article(&self) -> &str {
2716         use ItemKind::*;
2717         match self {
2718             Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2719             | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2720             ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2721         }
2722     }
2723
2724     pub fn descr(&self) -> &str {
2725         match self {
2726             ItemKind::ExternCrate(..) => "extern crate",
2727             ItemKind::Use(..) => "`use` import",
2728             ItemKind::Static(..) => "static item",
2729             ItemKind::Const(..) => "constant item",
2730             ItemKind::Fn(..) => "function",
2731             ItemKind::Mod(..) => "module",
2732             ItemKind::ForeignMod(..) => "extern block",
2733             ItemKind::GlobalAsm(..) => "global asm item",
2734             ItemKind::TyAlias(..) => "type alias",
2735             ItemKind::Enum(..) => "enum",
2736             ItemKind::Struct(..) => "struct",
2737             ItemKind::Union(..) => "union",
2738             ItemKind::Trait(..) => "trait",
2739             ItemKind::TraitAlias(..) => "trait alias",
2740             ItemKind::MacCall(..) => "item macro invocation",
2741             ItemKind::MacroDef(..) => "macro definition",
2742             ItemKind::Impl { .. } => "implementation",
2743         }
2744     }
2745
2746     pub fn generics(&self) -> Option<&Generics> {
2747         match self {
2748             Self::Fn(_, _, generics, _)
2749             | Self::TyAlias(_, generics, ..)
2750             | Self::Enum(_, generics)
2751             | Self::Struct(_, generics)
2752             | Self::Union(_, generics)
2753             | Self::Trait(_, _, generics, ..)
2754             | Self::TraitAlias(generics, _)
2755             | Self::Impl { generics, .. } => Some(generics),
2756             _ => None,
2757         }
2758     }
2759 }
2760
2761 /// Represents associated items.
2762 /// These include items in `impl` and `trait` definitions.
2763 pub type AssocItem = Item<AssocItemKind>;
2764
2765 /// Represents associated item kinds.
2766 ///
2767 /// The term "provided" in the variants below refers to the item having a default
2768 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2769 /// In an implementation, all items must be provided.
2770 /// The `Option`s below denote the bodies, where `Some(_)`
2771 /// means "provided" and conversely `None` means "required".
2772 #[derive(Clone, Encodable, Decodable, Debug)]
2773 pub enum AssocItemKind {
2774     /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2775     /// If `def` is parsed, then the constant is provided, and otherwise required.
2776     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2777     /// An associated function.
2778     Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2779     /// An associated type.
2780     TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2781     /// A macro expanding to associated items.
2782     MacCall(MacCall),
2783 }
2784
2785 impl AssocItemKind {
2786     pub fn defaultness(&self) -> Defaultness {
2787         match *self {
2788             Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def,
2789             Self::MacCall(..) => Defaultness::Final,
2790         }
2791     }
2792 }
2793
2794 impl From<AssocItemKind> for ItemKind {
2795     fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2796         match assoc_item_kind {
2797             AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2798             AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2799             AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2800             AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2801         }
2802     }
2803 }
2804
2805 impl TryFrom<ItemKind> for AssocItemKind {
2806     type Error = ItemKind;
2807
2808     fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2809         Ok(match item_kind {
2810             ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2811             ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
2812             ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
2813             ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2814             _ => return Err(item_kind),
2815         })
2816     }
2817 }
2818
2819 /// An item in `extern` block.
2820 #[derive(Clone, Encodable, Decodable, Debug)]
2821 pub enum ForeignItemKind {
2822     /// A foreign static item (`static FOO: u8`).
2823     Static(P<Ty>, Mutability, Option<P<Expr>>),
2824     /// A foreign function.
2825     Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2826     /// A foreign type.
2827     TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2828     /// A macro expanding to foreign items.
2829     MacCall(MacCall),
2830 }
2831
2832 impl From<ForeignItemKind> for ItemKind {
2833     fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2834         match foreign_item_kind {
2835             ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2836             ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2837             ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2838             ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2839         }
2840     }
2841 }
2842
2843 impl TryFrom<ItemKind> for ForeignItemKind {
2844     type Error = ItemKind;
2845
2846     fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2847         Ok(match item_kind {
2848             ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2849             ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
2850             ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
2851             ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2852             _ => return Err(item_kind),
2853         })
2854     }
2855 }
2856
2857 pub type ForeignItem = Item<ForeignItemKind>;