]> git.lizzy.rs Git - rust.git/blob - src/librustc_ast/ast.rs
Rollup merge of #75837 - GuillaumeGomez:fix-font-color-help-button, r=Cldfire
[rust.git] / src / librustc_ast / 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) => StmtKind::MacCall(
926                 mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)),
927             ),
928             kind => kind,
929         };
930         self
931     }
932
933     pub fn is_item(&self) -> bool {
934         match self.kind {
935             StmtKind::Item(_) => true,
936             _ => false,
937         }
938     }
939
940     pub fn is_expr(&self) -> bool {
941         match self.kind {
942             StmtKind::Expr(_) => true,
943             _ => false,
944         }
945     }
946 }
947
948 #[derive(Clone, Encodable, Decodable, Debug)]
949 pub enum StmtKind {
950     /// A local (let) binding.
951     Local(P<Local>),
952     /// An item definition.
953     Item(P<Item>),
954     /// Expr without trailing semi-colon.
955     Expr(P<Expr>),
956     /// Expr with a trailing semi-colon.
957     Semi(P<Expr>),
958     /// Just a trailing semi-colon.
959     Empty,
960     /// Macro.
961     MacCall(P<(MacCall, MacStmtStyle, AttrVec)>),
962 }
963
964 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
965 pub enum MacStmtStyle {
966     /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
967     /// `foo!(...);`, `foo![...];`).
968     Semicolon,
969     /// The macro statement had braces (e.g., `foo! { ... }`).
970     Braces,
971     /// The macro statement had parentheses or brackets and no semicolon (e.g.,
972     /// `foo!(...)`). All of these will end up being converted into macro
973     /// expressions.
974     NoBraces,
975 }
976
977 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
978 #[derive(Clone, Encodable, Decodable, Debug)]
979 pub struct Local {
980     pub id: NodeId,
981     pub pat: P<Pat>,
982     pub ty: Option<P<Ty>>,
983     /// Initializer expression to set the value, if any.
984     pub init: Option<P<Expr>>,
985     pub span: Span,
986     pub attrs: AttrVec,
987 }
988
989 /// An arm of a 'match'.
990 ///
991 /// E.g., `0..=10 => { println!("match!") }` as in
992 ///
993 /// ```
994 /// match 123 {
995 ///     0..=10 => { println!("match!") },
996 ///     _ => { println!("no match!") },
997 /// }
998 /// ```
999 #[derive(Clone, Encodable, Decodable, Debug)]
1000 pub struct Arm {
1001     pub attrs: Vec<Attribute>,
1002     /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1003     pub pat: P<Pat>,
1004     /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1005     pub guard: Option<P<Expr>>,
1006     /// Match arm body.
1007     pub body: P<Expr>,
1008     pub span: Span,
1009     pub id: NodeId,
1010     pub is_placeholder: bool,
1011 }
1012
1013 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1014 #[derive(Clone, Encodable, Decodable, Debug)]
1015 pub struct Field {
1016     pub attrs: AttrVec,
1017     pub id: NodeId,
1018     pub span: Span,
1019     pub ident: Ident,
1020     pub expr: P<Expr>,
1021     pub is_shorthand: bool,
1022     pub is_placeholder: bool,
1023 }
1024
1025 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1026 pub enum BlockCheckMode {
1027     Default,
1028     Unsafe(UnsafeSource),
1029 }
1030
1031 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1032 pub enum UnsafeSource {
1033     CompilerGenerated,
1034     UserProvided,
1035 }
1036
1037 /// A constant (expression) that's not an item or associated item,
1038 /// but needs its own `DefId` for type-checking, const-eval, etc.
1039 /// These are usually found nested inside types (e.g., array lengths)
1040 /// or expressions (e.g., repeat counts), and also used to define
1041 /// explicit discriminant values for enum variants.
1042 #[derive(Clone, Encodable, Decodable, Debug)]
1043 pub struct AnonConst {
1044     pub id: NodeId,
1045     pub value: P<Expr>,
1046 }
1047
1048 /// An expression.
1049 #[derive(Clone, Encodable, Decodable, Debug)]
1050 pub struct Expr {
1051     pub id: NodeId,
1052     pub kind: ExprKind,
1053     pub span: Span,
1054     pub attrs: AttrVec,
1055     pub tokens: Option<TokenStream>,
1056 }
1057
1058 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1059 #[cfg(target_arch = "x86_64")]
1060 rustc_data_structures::static_assert_size!(Expr, 104);
1061
1062 impl Expr {
1063     /// Returns `true` if this expression would be valid somewhere that expects a value;
1064     /// for example, an `if` condition.
1065     pub fn returns(&self) -> bool {
1066         if let ExprKind::Block(ref block, _) = self.kind {
1067             match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1068                 // Implicit return
1069                 Some(&StmtKind::Expr(_)) => true,
1070                 Some(&StmtKind::Semi(ref expr)) => {
1071                     if let ExprKind::Ret(_) = expr.kind {
1072                         // Last statement is explicit return.
1073                         true
1074                     } else {
1075                         false
1076                     }
1077                 }
1078                 // This is a block that doesn't end in either an implicit or explicit return.
1079                 _ => false,
1080             }
1081         } else {
1082             // This is not a block, it is a value.
1083             true
1084         }
1085     }
1086
1087     /// Is this expr either `N`, or `{ N }`.
1088     ///
1089     /// If this is not the case, name resolution does not resolve `N` when using
1090     /// `feature(min_const_generics)` as more complex expressions are not supported.
1091     pub fn is_potential_trivial_const_param(&self) -> bool {
1092         let this = if let ExprKind::Block(ref block, None) = self.kind {
1093             if block.stmts.len() == 1 {
1094                 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1095             } else {
1096                 self
1097             }
1098         } else {
1099             self
1100         };
1101
1102         if let ExprKind::Path(None, ref path) = this.kind {
1103             if path.segments.len() == 1 && path.segments[0].args.is_none() {
1104                 return true;
1105             }
1106         }
1107
1108         false
1109     }
1110
1111     pub fn to_bound(&self) -> Option<GenericBound> {
1112         match &self.kind {
1113             ExprKind::Path(None, path) => Some(GenericBound::Trait(
1114                 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1115                 TraitBoundModifier::None,
1116             )),
1117             _ => None,
1118         }
1119     }
1120
1121     /// Attempts to reparse as `Ty` (for diagnostic purposes).
1122     pub fn to_ty(&self) -> Option<P<Ty>> {
1123         let kind = match &self.kind {
1124             // Trivial conversions.
1125             ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1126             ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1127
1128             ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1129
1130             ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1131                 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1132             }
1133
1134             ExprKind::Repeat(expr, expr_len) => {
1135                 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1136             }
1137
1138             ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1139
1140             ExprKind::Tup(exprs) => {
1141                 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1142                 TyKind::Tup(tys)
1143             }
1144
1145             // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1146             // then type of result is trait object.
1147             // Otherwise we don't assume the result type.
1148             ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1149                 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1150                     TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1151                 } else {
1152                     return None;
1153                 }
1154             }
1155
1156             // This expression doesn't look like a type syntactically.
1157             _ => return None,
1158         };
1159
1160         Some(P(Ty { kind, id: self.id, span: self.span }))
1161     }
1162
1163     pub fn precedence(&self) -> ExprPrecedence {
1164         match self.kind {
1165             ExprKind::Box(_) => ExprPrecedence::Box,
1166             ExprKind::Array(_) => ExprPrecedence::Array,
1167             ExprKind::Call(..) => ExprPrecedence::Call,
1168             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1169             ExprKind::Tup(_) => ExprPrecedence::Tup,
1170             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1171             ExprKind::Unary(..) => ExprPrecedence::Unary,
1172             ExprKind::Lit(_) => ExprPrecedence::Lit,
1173             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1174             ExprKind::Let(..) => ExprPrecedence::Let,
1175             ExprKind::If(..) => ExprPrecedence::If,
1176             ExprKind::While(..) => ExprPrecedence::While,
1177             ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1178             ExprKind::Loop(..) => ExprPrecedence::Loop,
1179             ExprKind::Match(..) => ExprPrecedence::Match,
1180             ExprKind::Closure(..) => ExprPrecedence::Closure,
1181             ExprKind::Block(..) => ExprPrecedence::Block,
1182             ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1183             ExprKind::Async(..) => ExprPrecedence::Async,
1184             ExprKind::Await(..) => ExprPrecedence::Await,
1185             ExprKind::Assign(..) => ExprPrecedence::Assign,
1186             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1187             ExprKind::Field(..) => ExprPrecedence::Field,
1188             ExprKind::Index(..) => ExprPrecedence::Index,
1189             ExprKind::Range(..) => ExprPrecedence::Range,
1190             ExprKind::Path(..) => ExprPrecedence::Path,
1191             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1192             ExprKind::Break(..) => ExprPrecedence::Break,
1193             ExprKind::Continue(..) => ExprPrecedence::Continue,
1194             ExprKind::Ret(..) => ExprPrecedence::Ret,
1195             ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1196             ExprKind::MacCall(..) => ExprPrecedence::Mac,
1197             ExprKind::Struct(..) => ExprPrecedence::Struct,
1198             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1199             ExprKind::Paren(..) => ExprPrecedence::Paren,
1200             ExprKind::Try(..) => ExprPrecedence::Try,
1201             ExprKind::Yield(..) => ExprPrecedence::Yield,
1202             ExprKind::Err => ExprPrecedence::Err,
1203         }
1204     }
1205 }
1206
1207 /// Limit types of a range (inclusive or exclusive)
1208 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1209 pub enum RangeLimits {
1210     /// Inclusive at the beginning, exclusive at the end
1211     HalfOpen,
1212     /// Inclusive at the beginning and end
1213     Closed,
1214 }
1215
1216 #[derive(Clone, Encodable, Decodable, Debug)]
1217 pub enum ExprKind {
1218     /// A `box x` expression.
1219     Box(P<Expr>),
1220     /// An array (`[a, b, c, d]`)
1221     Array(Vec<P<Expr>>),
1222     /// A function call
1223     ///
1224     /// The first field resolves to the function itself,
1225     /// and the second field is the list of arguments.
1226     /// This also represents calling the constructor of
1227     /// tuple-like ADTs such as tuple structs and enum variants.
1228     Call(P<Expr>, Vec<P<Expr>>),
1229     /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1230     ///
1231     /// The `PathSegment` represents the method name and its generic arguments
1232     /// (within the angle brackets).
1233     /// The first element of the vector of an `Expr` is the expression that evaluates
1234     /// to the object on which the method is being called on (the receiver),
1235     /// and the remaining elements are the rest of the arguments.
1236     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1237     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1238     /// This `Span` is the span of the function, without the dot and receiver
1239     /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1240     MethodCall(PathSegment, Vec<P<Expr>>, Span),
1241     /// A tuple (e.g., `(a, b, c, d)`).
1242     Tup(Vec<P<Expr>>),
1243     /// A binary operation (e.g., `a + b`, `a * b`).
1244     Binary(BinOp, P<Expr>, P<Expr>),
1245     /// A unary operation (e.g., `!x`, `*x`).
1246     Unary(UnOp, P<Expr>),
1247     /// A literal (e.g., `1`, `"foo"`).
1248     Lit(Lit),
1249     /// A cast (e.g., `foo as f64`).
1250     Cast(P<Expr>, P<Ty>),
1251     /// A type ascription (e.g., `42: usize`).
1252     Type(P<Expr>, P<Ty>),
1253     /// A `let pat = expr` expression that is only semantically allowed in the condition
1254     /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1255     Let(P<Pat>, P<Expr>),
1256     /// An `if` block, with an optional `else` block.
1257     ///
1258     /// `if expr { block } else { expr }`
1259     If(P<Expr>, P<Block>, Option<P<Expr>>),
1260     /// A while loop, with an optional label.
1261     ///
1262     /// `'label: while expr { block }`
1263     While(P<Expr>, P<Block>, Option<Label>),
1264     /// A `for` loop, with an optional label.
1265     ///
1266     /// `'label: for pat in expr { block }`
1267     ///
1268     /// This is desugared to a combination of `loop` and `match` expressions.
1269     ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1270     /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1271     ///
1272     /// `'label: loop { block }`
1273     Loop(P<Block>, Option<Label>),
1274     /// A `match` block.
1275     Match(P<Expr>, Vec<Arm>),
1276     /// A closure (e.g., `move |a, b, c| a + b + c`).
1277     ///
1278     /// The final span is the span of the argument block `|...|`.
1279     Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1280     /// A block (`'label: { ... }`).
1281     Block(P<Block>, Option<Label>),
1282     /// An async block (`async move { ... }`).
1283     ///
1284     /// The `NodeId` is the `NodeId` for the closure that results from
1285     /// desugaring an async block, just like the NodeId field in the
1286     /// `Async::Yes` variant. This is necessary in order to create a def for the
1287     /// closure which can be used as a parent of any child defs. Defs
1288     /// created during lowering cannot be made the parent of any other
1289     /// preexisting defs.
1290     Async(CaptureBy, NodeId, P<Block>),
1291     /// An await expression (`my_future.await`).
1292     Await(P<Expr>),
1293
1294     /// A try block (`try { ... }`).
1295     TryBlock(P<Block>),
1296
1297     /// An assignment (`a = foo()`).
1298     /// The `Span` argument is the span of the `=` token.
1299     Assign(P<Expr>, P<Expr>, Span),
1300     /// An assignment with an operator.
1301     ///
1302     /// E.g., `a += 1`.
1303     AssignOp(BinOp, P<Expr>, P<Expr>),
1304     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1305     Field(P<Expr>, Ident),
1306     /// An indexing operation (e.g., `foo[2]`).
1307     Index(P<Expr>, P<Expr>),
1308     /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1309     Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1310
1311     /// Variable reference, possibly containing `::` and/or type
1312     /// parameters (e.g., `foo::bar::<baz>`).
1313     ///
1314     /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1315     Path(Option<QSelf>, Path),
1316
1317     /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1318     AddrOf(BorrowKind, Mutability, P<Expr>),
1319     /// A `break`, with an optional label to break, and an optional expression.
1320     Break(Option<Label>, Option<P<Expr>>),
1321     /// A `continue`, with an optional label.
1322     Continue(Option<Label>),
1323     /// A `return`, with an optional value to be returned.
1324     Ret(Option<P<Expr>>),
1325
1326     /// Output of the `asm!()` macro.
1327     InlineAsm(P<InlineAsm>),
1328     /// Output of the `llvm_asm!()` macro.
1329     LlvmInlineAsm(P<LlvmInlineAsm>),
1330
1331     /// A macro invocation; pre-expansion.
1332     MacCall(MacCall),
1333
1334     /// A struct literal expression.
1335     ///
1336     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1337     /// where `base` is the `Option<Expr>`.
1338     Struct(Path, Vec<Field>, Option<P<Expr>>),
1339
1340     /// An array literal constructed from one repeated element.
1341     ///
1342     /// E.g., `[1; 5]`. The expression is the element to be
1343     /// repeated; the constant is the number of times to repeat it.
1344     Repeat(P<Expr>, AnonConst),
1345
1346     /// No-op: used solely so we can pretty-print faithfully.
1347     Paren(P<Expr>),
1348
1349     /// A try expression (`expr?`).
1350     Try(P<Expr>),
1351
1352     /// A `yield`, with an optional value to be yielded.
1353     Yield(Option<P<Expr>>),
1354
1355     /// Placeholder for an expression that wasn't syntactically well formed in some way.
1356     Err,
1357 }
1358
1359 /// The explicit `Self` type in a "qualified path". The actual
1360 /// path, including the trait and the associated item, is stored
1361 /// separately. `position` represents the index of the associated
1362 /// item qualified with this `Self` type.
1363 ///
1364 /// ```ignore (only-for-syntax-highlight)
1365 /// <Vec<T> as a::b::Trait>::AssociatedItem
1366 ///  ^~~~~     ~~~~~~~~~~~~~~^
1367 ///  ty        position = 3
1368 ///
1369 /// <Vec<T>>::AssociatedItem
1370 ///  ^~~~~    ^
1371 ///  ty       position = 0
1372 /// ```
1373 #[derive(Clone, Encodable, Decodable, Debug)]
1374 pub struct QSelf {
1375     pub ty: P<Ty>,
1376
1377     /// The span of `a::b::Trait` in a path like `<Vec<T> as
1378     /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1379     /// 0`, this is an empty span.
1380     pub path_span: Span,
1381     pub position: usize,
1382 }
1383
1384 /// A capture clause used in closures and `async` blocks.
1385 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1386 pub enum CaptureBy {
1387     /// `move |x| y + x`.
1388     Value,
1389     /// `move` keyword was not specified.
1390     Ref,
1391 }
1392
1393 /// The movability of a generator / closure literal:
1394 /// whether a generator contains self-references, causing it to be `!Unpin`.
1395 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1396 #[derive(HashStable_Generic)]
1397 pub enum Movability {
1398     /// May contain self-references, `!Unpin`.
1399     Static,
1400     /// Must not contain self-references, `Unpin`.
1401     Movable,
1402 }
1403
1404 /// Represents a macro invocation. The `path` indicates which macro
1405 /// is being invoked, and the `args` are arguments passed to it.
1406 #[derive(Clone, Encodable, Decodable, Debug)]
1407 pub struct MacCall {
1408     pub path: Path,
1409     pub args: P<MacArgs>,
1410     pub prior_type_ascription: Option<(Span, bool)>,
1411 }
1412
1413 impl MacCall {
1414     pub fn span(&self) -> Span {
1415         self.path.span.to(self.args.span().unwrap_or(self.path.span))
1416     }
1417 }
1418
1419 /// Arguments passed to an attribute or a function-like macro.
1420 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1421 pub enum MacArgs {
1422     /// No arguments - `#[attr]`.
1423     Empty,
1424     /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1425     Delimited(DelimSpan, MacDelimiter, TokenStream),
1426     /// Arguments of a key-value attribute - `#[attr = "value"]`.
1427     Eq(
1428         /// Span of the `=` token.
1429         Span,
1430         /// Token stream of the "value".
1431         TokenStream,
1432     ),
1433 }
1434
1435 impl MacArgs {
1436     pub fn delim(&self) -> DelimToken {
1437         match self {
1438             MacArgs::Delimited(_, delim, _) => delim.to_token(),
1439             MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1440         }
1441     }
1442
1443     pub fn span(&self) -> Option<Span> {
1444         match *self {
1445             MacArgs::Empty => None,
1446             MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1447             MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1448         }
1449     }
1450
1451     /// Tokens inside the delimiters or after `=`.
1452     /// Proc macros see these tokens, for example.
1453     pub fn inner_tokens(&self) -> TokenStream {
1454         match self {
1455             MacArgs::Empty => TokenStream::default(),
1456             MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1457         }
1458     }
1459
1460     /// Tokens together with the delimiters or `=`.
1461     /// Use of this method generally means that something suboptimal or hacky is happening.
1462     pub fn outer_tokens(&self) -> TokenStream {
1463         match *self {
1464             MacArgs::Empty => TokenStream::default(),
1465             MacArgs::Delimited(dspan, delim, ref tokens) => {
1466                 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1467             }
1468             MacArgs::Eq(eq_span, ref tokens) => {
1469                 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1470             }
1471         }
1472     }
1473
1474     /// Whether a macro with these arguments needs a semicolon
1475     /// when used as a standalone item or statement.
1476     pub fn need_semicolon(&self) -> bool {
1477         !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1478     }
1479 }
1480
1481 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1482 pub enum MacDelimiter {
1483     Parenthesis,
1484     Bracket,
1485     Brace,
1486 }
1487
1488 impl MacDelimiter {
1489     pub fn to_token(self) -> DelimToken {
1490         match self {
1491             MacDelimiter::Parenthesis => DelimToken::Paren,
1492             MacDelimiter::Bracket => DelimToken::Bracket,
1493             MacDelimiter::Brace => DelimToken::Brace,
1494         }
1495     }
1496
1497     pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1498         match delim {
1499             token::Paren => Some(MacDelimiter::Parenthesis),
1500             token::Bracket => Some(MacDelimiter::Bracket),
1501             token::Brace => Some(MacDelimiter::Brace),
1502             token::NoDelim => None,
1503         }
1504     }
1505 }
1506
1507 /// Represents a macro definition.
1508 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1509 pub struct MacroDef {
1510     pub body: P<MacArgs>,
1511     /// `true` if macro was defined with `macro_rules`.
1512     pub macro_rules: bool,
1513 }
1514
1515 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1516 #[derive(HashStable_Generic)]
1517 pub enum StrStyle {
1518     /// A regular string, like `"foo"`.
1519     Cooked,
1520     /// A raw string, like `r##"foo"##`.
1521     ///
1522     /// The value is the number of `#` symbols used.
1523     Raw(u16),
1524 }
1525
1526 /// An AST literal.
1527 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1528 pub struct Lit {
1529     /// The original literal token as written in source code.
1530     pub token: token::Lit,
1531     /// The "semantic" representation of the literal lowered from the original tokens.
1532     /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1533     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1534     pub kind: LitKind,
1535     pub span: Span,
1536 }
1537
1538 /// Same as `Lit`, but restricted to string literals.
1539 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1540 pub struct StrLit {
1541     /// The original literal token as written in source code.
1542     pub style: StrStyle,
1543     pub symbol: Symbol,
1544     pub suffix: Option<Symbol>,
1545     pub span: Span,
1546     /// The unescaped "semantic" representation of the literal lowered from the original token.
1547     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1548     pub symbol_unescaped: Symbol,
1549 }
1550
1551 impl StrLit {
1552     pub fn as_lit(&self) -> Lit {
1553         let token_kind = match self.style {
1554             StrStyle::Cooked => token::Str,
1555             StrStyle::Raw(n) => token::StrRaw(n),
1556         };
1557         Lit {
1558             token: token::Lit::new(token_kind, self.symbol, self.suffix),
1559             span: self.span,
1560             kind: LitKind::Str(self.symbol_unescaped, self.style),
1561         }
1562     }
1563 }
1564
1565 /// Type of the integer literal based on provided suffix.
1566 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1567 #[derive(HashStable_Generic)]
1568 pub enum LitIntType {
1569     /// e.g. `42_i32`.
1570     Signed(IntTy),
1571     /// e.g. `42_u32`.
1572     Unsigned(UintTy),
1573     /// e.g. `42`.
1574     Unsuffixed,
1575 }
1576
1577 /// Type of the float literal based on provided suffix.
1578 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1579 #[derive(HashStable_Generic)]
1580 pub enum LitFloatType {
1581     /// A float literal with a suffix (`1f32` or `1E10f32`).
1582     Suffixed(FloatTy),
1583     /// A float literal without a suffix (`1.0 or 1.0E10`).
1584     Unsuffixed,
1585 }
1586
1587 /// Literal kind.
1588 ///
1589 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1590 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1591 pub enum LitKind {
1592     /// A string literal (`"foo"`).
1593     Str(Symbol, StrStyle),
1594     /// A byte string (`b"foo"`).
1595     ByteStr(Lrc<Vec<u8>>),
1596     /// A byte char (`b'f'`).
1597     Byte(u8),
1598     /// A character literal (`'a'`).
1599     Char(char),
1600     /// An integer literal (`1`).
1601     Int(u128, LitIntType),
1602     /// A float literal (`1f64` or `1E10f64`).
1603     Float(Symbol, LitFloatType),
1604     /// A boolean literal.
1605     Bool(bool),
1606     /// Placeholder for a literal that wasn't well-formed in some way.
1607     Err(Symbol),
1608 }
1609
1610 impl LitKind {
1611     /// Returns `true` if this literal is a string.
1612     pub fn is_str(&self) -> bool {
1613         match *self {
1614             LitKind::Str(..) => true,
1615             _ => false,
1616         }
1617     }
1618
1619     /// Returns `true` if this literal is byte literal string.
1620     pub fn is_bytestr(&self) -> bool {
1621         match self {
1622             LitKind::ByteStr(_) => true,
1623             _ => false,
1624         }
1625     }
1626
1627     /// Returns `true` if this is a numeric literal.
1628     pub fn is_numeric(&self) -> bool {
1629         match *self {
1630             LitKind::Int(..) | LitKind::Float(..) => true,
1631             _ => false,
1632         }
1633     }
1634
1635     /// Returns `true` if this literal has no suffix.
1636     /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1637     pub fn is_unsuffixed(&self) -> bool {
1638         !self.is_suffixed()
1639     }
1640
1641     /// Returns `true` if this literal has a suffix.
1642     pub fn is_suffixed(&self) -> bool {
1643         match *self {
1644             // suffixed variants
1645             LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1646             | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1647             // unsuffixed variants
1648             LitKind::Str(..)
1649             | LitKind::ByteStr(..)
1650             | LitKind::Byte(..)
1651             | LitKind::Char(..)
1652             | LitKind::Int(_, LitIntType::Unsuffixed)
1653             | LitKind::Float(_, LitFloatType::Unsuffixed)
1654             | LitKind::Bool(..)
1655             | LitKind::Err(..) => false,
1656         }
1657     }
1658 }
1659
1660 // N.B., If you change this, you'll probably want to change the corresponding
1661 // type structure in `middle/ty.rs` as well.
1662 #[derive(Clone, Encodable, Decodable, Debug)]
1663 pub struct MutTy {
1664     pub ty: P<Ty>,
1665     pub mutbl: Mutability,
1666 }
1667
1668 /// Represents a function's signature in a trait declaration,
1669 /// trait implementation, or free function.
1670 #[derive(Clone, Encodable, Decodable, Debug)]
1671 pub struct FnSig {
1672     pub header: FnHeader,
1673     pub decl: P<FnDecl>,
1674     pub span: Span,
1675 }
1676
1677 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1678 #[derive(Encodable, Decodable, HashStable_Generic)]
1679 pub enum FloatTy {
1680     F32,
1681     F64,
1682 }
1683
1684 impl FloatTy {
1685     pub fn name_str(self) -> &'static str {
1686         match self {
1687             FloatTy::F32 => "f32",
1688             FloatTy::F64 => "f64",
1689         }
1690     }
1691
1692     pub fn name(self) -> Symbol {
1693         match self {
1694             FloatTy::F32 => sym::f32,
1695             FloatTy::F64 => sym::f64,
1696         }
1697     }
1698
1699     pub fn bit_width(self) -> u64 {
1700         match self {
1701             FloatTy::F32 => 32,
1702             FloatTy::F64 => 64,
1703         }
1704     }
1705 }
1706
1707 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1708 #[derive(Encodable, Decodable, HashStable_Generic)]
1709 pub enum IntTy {
1710     Isize,
1711     I8,
1712     I16,
1713     I32,
1714     I64,
1715     I128,
1716 }
1717
1718 impl IntTy {
1719     pub fn name_str(&self) -> &'static str {
1720         match *self {
1721             IntTy::Isize => "isize",
1722             IntTy::I8 => "i8",
1723             IntTy::I16 => "i16",
1724             IntTy::I32 => "i32",
1725             IntTy::I64 => "i64",
1726             IntTy::I128 => "i128",
1727         }
1728     }
1729
1730     pub fn name(&self) -> Symbol {
1731         match *self {
1732             IntTy::Isize => sym::isize,
1733             IntTy::I8 => sym::i8,
1734             IntTy::I16 => sym::i16,
1735             IntTy::I32 => sym::i32,
1736             IntTy::I64 => sym::i64,
1737             IntTy::I128 => sym::i128,
1738         }
1739     }
1740
1741     pub fn val_to_string(&self, val: i128) -> String {
1742         // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1743         // are parsed as `u128`, so we wouldn't want to print an extra negative
1744         // sign.
1745         format!("{}{}", val as u128, self.name_str())
1746     }
1747
1748     pub fn bit_width(&self) -> Option<u64> {
1749         Some(match *self {
1750             IntTy::Isize => return None,
1751             IntTy::I8 => 8,
1752             IntTy::I16 => 16,
1753             IntTy::I32 => 32,
1754             IntTy::I64 => 64,
1755             IntTy::I128 => 128,
1756         })
1757     }
1758
1759     pub fn normalize(&self, target_width: u32) -> Self {
1760         match self {
1761             IntTy::Isize => match target_width {
1762                 16 => IntTy::I16,
1763                 32 => IntTy::I32,
1764                 64 => IntTy::I64,
1765                 _ => unreachable!(),
1766             },
1767             _ => *self,
1768         }
1769     }
1770 }
1771
1772 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1773 #[derive(Encodable, Decodable, HashStable_Generic)]
1774 pub enum UintTy {
1775     Usize,
1776     U8,
1777     U16,
1778     U32,
1779     U64,
1780     U128,
1781 }
1782
1783 impl UintTy {
1784     pub fn name_str(&self) -> &'static str {
1785         match *self {
1786             UintTy::Usize => "usize",
1787             UintTy::U8 => "u8",
1788             UintTy::U16 => "u16",
1789             UintTy::U32 => "u32",
1790             UintTy::U64 => "u64",
1791             UintTy::U128 => "u128",
1792         }
1793     }
1794
1795     pub fn name(&self) -> Symbol {
1796         match *self {
1797             UintTy::Usize => sym::usize,
1798             UintTy::U8 => sym::u8,
1799             UintTy::U16 => sym::u16,
1800             UintTy::U32 => sym::u32,
1801             UintTy::U64 => sym::u64,
1802             UintTy::U128 => sym::u128,
1803         }
1804     }
1805
1806     pub fn val_to_string(&self, val: u128) -> String {
1807         format!("{}{}", val, self.name_str())
1808     }
1809
1810     pub fn bit_width(&self) -> Option<u64> {
1811         Some(match *self {
1812             UintTy::Usize => return None,
1813             UintTy::U8 => 8,
1814             UintTy::U16 => 16,
1815             UintTy::U32 => 32,
1816             UintTy::U64 => 64,
1817             UintTy::U128 => 128,
1818         })
1819     }
1820
1821     pub fn normalize(&self, target_width: u32) -> Self {
1822         match self {
1823             UintTy::Usize => match target_width {
1824                 16 => UintTy::U16,
1825                 32 => UintTy::U32,
1826                 64 => UintTy::U64,
1827                 _ => unreachable!(),
1828             },
1829             _ => *self,
1830         }
1831     }
1832 }
1833
1834 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1835 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1836 #[derive(Clone, Encodable, Decodable, Debug)]
1837 pub struct AssocTyConstraint {
1838     pub id: NodeId,
1839     pub ident: Ident,
1840     pub kind: AssocTyConstraintKind,
1841     pub span: Span,
1842 }
1843
1844 /// The kinds of an `AssocTyConstraint`.
1845 #[derive(Clone, Encodable, Decodable, Debug)]
1846 pub enum AssocTyConstraintKind {
1847     /// E.g., `A = Bar` in `Foo<A = Bar>`.
1848     Equality { ty: P<Ty> },
1849     /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1850     Bound { bounds: GenericBounds },
1851 }
1852
1853 #[derive(Clone, Encodable, Decodable, Debug)]
1854 pub struct Ty {
1855     pub id: NodeId,
1856     pub kind: TyKind,
1857     pub span: Span,
1858 }
1859
1860 #[derive(Clone, Encodable, Decodable, Debug)]
1861 pub struct BareFnTy {
1862     pub unsafety: Unsafe,
1863     pub ext: Extern,
1864     pub generic_params: Vec<GenericParam>,
1865     pub decl: P<FnDecl>,
1866 }
1867
1868 /// The various kinds of type recognized by the compiler.
1869 #[derive(Clone, Encodable, Decodable, Debug)]
1870 pub enum TyKind {
1871     /// A variable-length slice (`[T]`).
1872     Slice(P<Ty>),
1873     /// A fixed length array (`[T; n]`).
1874     Array(P<Ty>, AnonConst),
1875     /// A raw pointer (`*const T` or `*mut T`).
1876     Ptr(MutTy),
1877     /// A reference (`&'a T` or `&'a mut T`).
1878     Rptr(Option<Lifetime>, MutTy),
1879     /// A bare function (e.g., `fn(usize) -> bool`).
1880     BareFn(P<BareFnTy>),
1881     /// The never type (`!`).
1882     Never,
1883     /// A tuple (`(A, B, C, D,...)`).
1884     Tup(Vec<P<Ty>>),
1885     /// A path (`module::module::...::Type`), optionally
1886     /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1887     ///
1888     /// Type parameters are stored in the `Path` itself.
1889     Path(Option<QSelf>, Path),
1890     /// A trait object type `Bound1 + Bound2 + Bound3`
1891     /// where `Bound` is a trait or a lifetime.
1892     TraitObject(GenericBounds, TraitObjectSyntax),
1893     /// An `impl Bound1 + Bound2 + Bound3` type
1894     /// where `Bound` is a trait or a lifetime.
1895     ///
1896     /// The `NodeId` exists to prevent lowering from having to
1897     /// generate `NodeId`s on the fly, which would complicate
1898     /// the generation of opaque `type Foo = impl Trait` items significantly.
1899     ImplTrait(NodeId, GenericBounds),
1900     /// No-op; kept solely so that we can pretty-print faithfully.
1901     Paren(P<Ty>),
1902     /// Unused for now.
1903     Typeof(AnonConst),
1904     /// This means the type should be inferred instead of it having been
1905     /// specified. This can appear anywhere in a type.
1906     Infer,
1907     /// Inferred type of a `self` or `&self` argument in a method.
1908     ImplicitSelf,
1909     /// A macro in the type position.
1910     MacCall(MacCall),
1911     /// Placeholder for a kind that has failed to be defined.
1912     Err,
1913     /// Placeholder for a `va_list`.
1914     CVarArgs,
1915 }
1916
1917 impl TyKind {
1918     pub fn is_implicit_self(&self) -> bool {
1919         if let TyKind::ImplicitSelf = *self { true } else { false }
1920     }
1921
1922     pub fn is_unit(&self) -> bool {
1923         if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1924     }
1925 }
1926
1927 /// Syntax used to declare a trait object.
1928 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1929 pub enum TraitObjectSyntax {
1930     Dyn,
1931     None,
1932 }
1933
1934 /// Inline assembly operand explicit register or register class.
1935 ///
1936 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1937 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1938 pub enum InlineAsmRegOrRegClass {
1939     Reg(Symbol),
1940     RegClass(Symbol),
1941 }
1942
1943 bitflags::bitflags! {
1944     #[derive(Encodable, Decodable, HashStable_Generic)]
1945     pub struct InlineAsmOptions: u8 {
1946         const PURE = 1 << 0;
1947         const NOMEM = 1 << 1;
1948         const READONLY = 1 << 2;
1949         const PRESERVES_FLAGS = 1 << 3;
1950         const NORETURN = 1 << 4;
1951         const NOSTACK = 1 << 5;
1952         const ATT_SYNTAX = 1 << 6;
1953     }
1954 }
1955
1956 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1957 pub enum InlineAsmTemplatePiece {
1958     String(String),
1959     Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1960 }
1961
1962 impl fmt::Display for InlineAsmTemplatePiece {
1963     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1964         match self {
1965             Self::String(s) => {
1966                 for c in s.chars() {
1967                     match c {
1968                         '{' => f.write_str("{{")?,
1969                         '}' => f.write_str("}}")?,
1970                         _ => c.fmt(f)?,
1971                     }
1972                 }
1973                 Ok(())
1974             }
1975             Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
1976                 write!(f, "{{{}:{}}}", operand_idx, modifier)
1977             }
1978             Self::Placeholder { operand_idx, modifier: None, .. } => {
1979                 write!(f, "{{{}}}", operand_idx)
1980             }
1981         }
1982     }
1983 }
1984
1985 impl InlineAsmTemplatePiece {
1986     /// Rebuilds the asm template string from its pieces.
1987     pub fn to_string(s: &[Self]) -> String {
1988         use fmt::Write;
1989         let mut out = String::new();
1990         for p in s.iter() {
1991             let _ = write!(out, "{}", p);
1992         }
1993         out
1994     }
1995 }
1996
1997 /// Inline assembly operand.
1998 ///
1999 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2000 #[derive(Clone, Encodable, Decodable, Debug)]
2001 pub enum InlineAsmOperand {
2002     In {
2003         reg: InlineAsmRegOrRegClass,
2004         expr: P<Expr>,
2005     },
2006     Out {
2007         reg: InlineAsmRegOrRegClass,
2008         late: bool,
2009         expr: Option<P<Expr>>,
2010     },
2011     InOut {
2012         reg: InlineAsmRegOrRegClass,
2013         late: bool,
2014         expr: P<Expr>,
2015     },
2016     SplitInOut {
2017         reg: InlineAsmRegOrRegClass,
2018         late: bool,
2019         in_expr: P<Expr>,
2020         out_expr: Option<P<Expr>>,
2021     },
2022     Const {
2023         expr: P<Expr>,
2024     },
2025     Sym {
2026         expr: P<Expr>,
2027     },
2028 }
2029
2030 /// Inline assembly.
2031 ///
2032 /// E.g., `asm!("NOP");`.
2033 #[derive(Clone, Encodable, Decodable, Debug)]
2034 pub struct InlineAsm {
2035     pub template: Vec<InlineAsmTemplatePiece>,
2036     pub operands: Vec<(InlineAsmOperand, Span)>,
2037     pub options: InlineAsmOptions,
2038     pub line_spans: Vec<Span>,
2039 }
2040
2041 /// Inline assembly dialect.
2042 ///
2043 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2044 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2045 pub enum LlvmAsmDialect {
2046     Att,
2047     Intel,
2048 }
2049
2050 /// LLVM-style inline assembly.
2051 ///
2052 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2053 #[derive(Clone, Encodable, Decodable, Debug)]
2054 pub struct LlvmInlineAsmOutput {
2055     pub constraint: Symbol,
2056     pub expr: P<Expr>,
2057     pub is_rw: bool,
2058     pub is_indirect: bool,
2059 }
2060
2061 /// LLVM-style inline assembly.
2062 ///
2063 /// E.g., `llvm_asm!("NOP");`.
2064 #[derive(Clone, Encodable, Decodable, Debug)]
2065 pub struct LlvmInlineAsm {
2066     pub asm: Symbol,
2067     pub asm_str_style: StrStyle,
2068     pub outputs: Vec<LlvmInlineAsmOutput>,
2069     pub inputs: Vec<(Symbol, P<Expr>)>,
2070     pub clobbers: Vec<Symbol>,
2071     pub volatile: bool,
2072     pub alignstack: bool,
2073     pub dialect: LlvmAsmDialect,
2074 }
2075
2076 /// A parameter in a function header.
2077 ///
2078 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2079 #[derive(Clone, Encodable, Decodable, Debug)]
2080 pub struct Param {
2081     pub attrs: AttrVec,
2082     pub ty: P<Ty>,
2083     pub pat: P<Pat>,
2084     pub id: NodeId,
2085     pub span: Span,
2086     pub is_placeholder: bool,
2087 }
2088
2089 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2090 ///
2091 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2092 #[derive(Clone, Encodable, Decodable, Debug)]
2093 pub enum SelfKind {
2094     /// `self`, `mut self`
2095     Value(Mutability),
2096     /// `&'lt self`, `&'lt mut self`
2097     Region(Option<Lifetime>, Mutability),
2098     /// `self: TYPE`, `mut self: TYPE`
2099     Explicit(P<Ty>, Mutability),
2100 }
2101
2102 pub type ExplicitSelf = Spanned<SelfKind>;
2103
2104 impl Param {
2105     /// Attempts to cast parameter to `ExplicitSelf`.
2106     pub fn to_self(&self) -> Option<ExplicitSelf> {
2107         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2108             if ident.name == kw::SelfLower {
2109                 return match self.ty.kind {
2110                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2111                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2112                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2113                     }
2114                     _ => Some(respan(
2115                         self.pat.span.to(self.ty.span),
2116                         SelfKind::Explicit(self.ty.clone(), mutbl),
2117                     )),
2118                 };
2119             }
2120         }
2121         None
2122     }
2123
2124     /// Returns `true` if parameter is `self`.
2125     pub fn is_self(&self) -> bool {
2126         if let PatKind::Ident(_, ident, _) = self.pat.kind {
2127             ident.name == kw::SelfLower
2128         } else {
2129             false
2130         }
2131     }
2132
2133     /// Builds a `Param` object from `ExplicitSelf`.
2134     pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2135         let span = eself.span.to(eself_ident.span);
2136         let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2137         let param = |mutbl, ty| Param {
2138             attrs,
2139             pat: P(Pat {
2140                 id: DUMMY_NODE_ID,
2141                 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2142                 span,
2143                 tokens: None,
2144             }),
2145             span,
2146             ty,
2147             id: DUMMY_NODE_ID,
2148             is_placeholder: false,
2149         };
2150         match eself.node {
2151             SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2152             SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2153             SelfKind::Region(lt, mutbl) => param(
2154                 Mutability::Not,
2155                 P(Ty {
2156                     id: DUMMY_NODE_ID,
2157                     kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2158                     span,
2159                 }),
2160             ),
2161         }
2162     }
2163 }
2164
2165 /// A signature (not the body) of a function declaration.
2166 ///
2167 /// E.g., `fn foo(bar: baz)`.
2168 ///
2169 /// Please note that it's different from `FnHeader` structure
2170 /// which contains metadata about function safety, asyncness, constness and ABI.
2171 #[derive(Clone, Encodable, Decodable, Debug)]
2172 pub struct FnDecl {
2173     pub inputs: Vec<Param>,
2174     pub output: FnRetTy,
2175 }
2176
2177 impl FnDecl {
2178     pub fn get_self(&self) -> Option<ExplicitSelf> {
2179         self.inputs.get(0).and_then(Param::to_self)
2180     }
2181     pub fn has_self(&self) -> bool {
2182         self.inputs.get(0).map_or(false, Param::is_self)
2183     }
2184     pub fn c_variadic(&self) -> bool {
2185         self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2186             TyKind::CVarArgs => true,
2187             _ => false,
2188         })
2189     }
2190 }
2191
2192 /// Is the trait definition an auto trait?
2193 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2194 pub enum IsAuto {
2195     Yes,
2196     No,
2197 }
2198
2199 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2200 #[derive(HashStable_Generic)]
2201 pub enum Unsafe {
2202     Yes(Span),
2203     No,
2204 }
2205
2206 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2207 pub enum Async {
2208     Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2209     No,
2210 }
2211
2212 impl Async {
2213     pub fn is_async(self) -> bool {
2214         if let Async::Yes { .. } = self { true } else { false }
2215     }
2216
2217     /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2218     pub fn opt_return_id(self) -> Option<NodeId> {
2219         match self {
2220             Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2221             Async::No => None,
2222         }
2223     }
2224 }
2225
2226 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2227 #[derive(HashStable_Generic)]
2228 pub enum Const {
2229     Yes(Span),
2230     No,
2231 }
2232
2233 /// Item defaultness.
2234 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2235 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2236 pub enum Defaultness {
2237     Default(Span),
2238     Final,
2239 }
2240
2241 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2242 pub enum ImplPolarity {
2243     /// `impl Trait for Type`
2244     Positive,
2245     /// `impl !Trait for Type`
2246     Negative(Span),
2247 }
2248
2249 impl fmt::Debug for ImplPolarity {
2250     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2251         match *self {
2252             ImplPolarity::Positive => "positive".fmt(f),
2253             ImplPolarity::Negative(_) => "negative".fmt(f),
2254         }
2255     }
2256 }
2257
2258 #[derive(Clone, Encodable, Decodable, Debug)]
2259 pub enum FnRetTy {
2260     /// Returns type is not specified.
2261     ///
2262     /// Functions default to `()` and closures default to inference.
2263     /// Span points to where return type would be inserted.
2264     Default(Span),
2265     /// Everything else.
2266     Ty(P<Ty>),
2267 }
2268
2269 impl FnRetTy {
2270     pub fn span(&self) -> Span {
2271         match *self {
2272             FnRetTy::Default(span) => span,
2273             FnRetTy::Ty(ref ty) => ty.span,
2274         }
2275     }
2276 }
2277
2278 /// Module declaration.
2279 ///
2280 /// E.g., `mod foo;` or `mod foo { .. }`.
2281 #[derive(Clone, Encodable, Decodable, Debug, Default)]
2282 pub struct Mod {
2283     /// A span from the first token past `{` to the last token until `}`.
2284     /// For `mod foo;`, the inner span ranges from the first token
2285     /// to the last token in the external file.
2286     pub inner: Span,
2287     pub items: Vec<P<Item>>,
2288     /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2289     pub inline: bool,
2290 }
2291
2292 /// Foreign module declaration.
2293 ///
2294 /// E.g., `extern { .. }` or `extern C { .. }`.
2295 #[derive(Clone, Encodable, Decodable, Debug)]
2296 pub struct ForeignMod {
2297     pub abi: Option<StrLit>,
2298     pub items: Vec<P<ForeignItem>>,
2299 }
2300
2301 /// Global inline assembly.
2302 ///
2303 /// Also known as "module-level assembly" or "file-scoped assembly".
2304 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2305 pub struct GlobalAsm {
2306     pub asm: Symbol,
2307 }
2308
2309 #[derive(Clone, Encodable, Decodable, Debug)]
2310 pub struct EnumDef {
2311     pub variants: Vec<Variant>,
2312 }
2313 /// Enum variant.
2314 #[derive(Clone, Encodable, Decodable, Debug)]
2315 pub struct Variant {
2316     /// Attributes of the variant.
2317     pub attrs: Vec<Attribute>,
2318     /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2319     pub id: NodeId,
2320     /// Span
2321     pub span: Span,
2322     /// The visibility of the variant. Syntactically accepted but not semantically.
2323     pub vis: Visibility,
2324     /// Name of the variant.
2325     pub ident: Ident,
2326
2327     /// Fields and constructor id of the variant.
2328     pub data: VariantData,
2329     /// Explicit discriminant, e.g., `Foo = 1`.
2330     pub disr_expr: Option<AnonConst>,
2331     /// Is a macro placeholder
2332     pub is_placeholder: bool,
2333 }
2334
2335 /// Part of `use` item to the right of its prefix.
2336 #[derive(Clone, Encodable, Decodable, Debug)]
2337 pub enum UseTreeKind {
2338     /// `use prefix` or `use prefix as rename`
2339     ///
2340     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2341     /// namespace.
2342     Simple(Option<Ident>, NodeId, NodeId),
2343     /// `use prefix::{...}`
2344     Nested(Vec<(UseTree, NodeId)>),
2345     /// `use prefix::*`
2346     Glob,
2347 }
2348
2349 /// A tree of paths sharing common prefixes.
2350 /// Used in `use` items both at top-level and inside of braces in import groups.
2351 #[derive(Clone, Encodable, Decodable, Debug)]
2352 pub struct UseTree {
2353     pub prefix: Path,
2354     pub kind: UseTreeKind,
2355     pub span: Span,
2356 }
2357
2358 impl UseTree {
2359     pub fn ident(&self) -> Ident {
2360         match self.kind {
2361             UseTreeKind::Simple(Some(rename), ..) => rename,
2362             UseTreeKind::Simple(None, ..) => {
2363                 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2364             }
2365             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2366         }
2367     }
2368 }
2369
2370 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2371 /// are contained as statements within items. These two cases need to be
2372 /// distinguished for pretty-printing.
2373 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2374 pub enum AttrStyle {
2375     Outer,
2376     Inner,
2377 }
2378
2379 rustc_index::newtype_index! {
2380     pub struct AttrId {
2381         ENCODABLE = custom
2382         DEBUG_FORMAT = "AttrId({})"
2383     }
2384 }
2385
2386 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2387     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2388         s.emit_unit()
2389     }
2390 }
2391
2392 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2393     fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2394         d.read_nil().map(|_| crate::attr::mk_attr_id())
2395     }
2396 }
2397
2398 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2399 pub struct AttrItem {
2400     pub path: Path,
2401     pub args: MacArgs,
2402 }
2403
2404 /// A list of attributes.
2405 pub type AttrVec = ThinVec<Attribute>;
2406
2407 /// Metadata associated with an item.
2408 #[derive(Clone, Encodable, Decodable, Debug)]
2409 pub struct Attribute {
2410     pub kind: AttrKind,
2411     pub id: AttrId,
2412     /// Denotes if the attribute decorates the following construct (outer)
2413     /// or the construct this attribute is contained within (inner).
2414     pub style: AttrStyle,
2415     pub span: Span,
2416 }
2417
2418 #[derive(Clone, Encodable, Decodable, Debug)]
2419 pub enum AttrKind {
2420     /// A normal attribute.
2421     Normal(AttrItem),
2422
2423     /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2424     /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2425     /// variant (which is much less compact and thus more expensive).
2426     DocComment(CommentKind, Symbol),
2427 }
2428
2429 /// `TraitRef`s appear in impls.
2430 ///
2431 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2432 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2433 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2434 /// same as the impl's `NodeId`).
2435 #[derive(Clone, Encodable, Decodable, Debug)]
2436 pub struct TraitRef {
2437     pub path: Path,
2438     pub ref_id: NodeId,
2439 }
2440
2441 #[derive(Clone, Encodable, Decodable, Debug)]
2442 pub struct PolyTraitRef {
2443     /// The `'a` in `<'a> Foo<&'a T>`.
2444     pub bound_generic_params: Vec<GenericParam>,
2445
2446     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2447     pub trait_ref: TraitRef,
2448
2449     pub span: Span,
2450 }
2451
2452 impl PolyTraitRef {
2453     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2454         PolyTraitRef {
2455             bound_generic_params: generic_params,
2456             trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2457             span,
2458         }
2459     }
2460 }
2461
2462 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2463 pub enum CrateSugar {
2464     /// Source is `pub(crate)`.
2465     PubCrate,
2466
2467     /// Source is (just) `crate`.
2468     JustCrate,
2469 }
2470
2471 pub type Visibility = Spanned<VisibilityKind>;
2472
2473 #[derive(Clone, Encodable, Decodable, Debug)]
2474 pub enum VisibilityKind {
2475     Public,
2476     Crate(CrateSugar),
2477     Restricted { path: P<Path>, id: NodeId },
2478     Inherited,
2479 }
2480
2481 impl VisibilityKind {
2482     pub fn is_pub(&self) -> bool {
2483         if let VisibilityKind::Public = *self { true } else { false }
2484     }
2485 }
2486
2487 /// Field of a struct.
2488 ///
2489 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2490 #[derive(Clone, Encodable, Decodable, Debug)]
2491 pub struct StructField {
2492     pub attrs: Vec<Attribute>,
2493     pub id: NodeId,
2494     pub span: Span,
2495     pub vis: Visibility,
2496     pub ident: Option<Ident>,
2497
2498     pub ty: P<Ty>,
2499     pub is_placeholder: bool,
2500 }
2501
2502 /// Fields and constructor ids of enum variants and structs.
2503 #[derive(Clone, Encodable, Decodable, Debug)]
2504 pub enum VariantData {
2505     /// Struct variant.
2506     ///
2507     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2508     Struct(Vec<StructField>, bool),
2509     /// Tuple variant.
2510     ///
2511     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2512     Tuple(Vec<StructField>, NodeId),
2513     /// Unit variant.
2514     ///
2515     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2516     Unit(NodeId),
2517 }
2518
2519 impl VariantData {
2520     /// Return the fields of this variant.
2521     pub fn fields(&self) -> &[StructField] {
2522         match *self {
2523             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2524             _ => &[],
2525         }
2526     }
2527
2528     /// Return the `NodeId` of this variant's constructor, if it has one.
2529     pub fn ctor_id(&self) -> Option<NodeId> {
2530         match *self {
2531             VariantData::Struct(..) => None,
2532             VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2533         }
2534     }
2535 }
2536
2537 /// An item definition.
2538 #[derive(Clone, Encodable, Decodable, Debug)]
2539 pub struct Item<K = ItemKind> {
2540     pub attrs: Vec<Attribute>,
2541     pub id: NodeId,
2542     pub span: Span,
2543     pub vis: Visibility,
2544     /// The name of the item.
2545     /// It might be a dummy name in case of anonymous items.
2546     pub ident: Ident,
2547
2548     pub kind: K,
2549
2550     /// Original tokens this item was parsed from. This isn't necessarily
2551     /// available for all items, although over time more and more items should
2552     /// have this be `Some`. Right now this is primarily used for procedural
2553     /// macros, notably custom attributes.
2554     ///
2555     /// Note that the tokens here do not include the outer attributes, but will
2556     /// include inner attributes.
2557     pub tokens: Option<TokenStream>,
2558 }
2559
2560 impl Item {
2561     /// Return the span that encompasses the attributes.
2562     pub fn span_with_attributes(&self) -> Span {
2563         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2564     }
2565 }
2566
2567 impl<K: Into<ItemKind>> Item<K> {
2568     pub fn into_item(self) -> Item {
2569         let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2570         Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2571     }
2572 }
2573
2574 /// `extern` qualifier on a function item or function type.
2575 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2576 pub enum Extern {
2577     None,
2578     Implicit,
2579     Explicit(StrLit),
2580 }
2581
2582 impl Extern {
2583     pub fn from_abi(abi: Option<StrLit>) -> Extern {
2584         abi.map_or(Extern::Implicit, Extern::Explicit)
2585     }
2586 }
2587
2588 /// A function header.
2589 ///
2590 /// All the information between the visibility and the name of the function is
2591 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2592 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2593 pub struct FnHeader {
2594     pub unsafety: Unsafe,
2595     pub asyncness: Async,
2596     pub constness: Const,
2597     pub ext: Extern,
2598 }
2599
2600 impl FnHeader {
2601     /// Does this function header have any qualifiers or is it empty?
2602     pub fn has_qualifiers(&self) -> bool {
2603         let Self { unsafety, asyncness, constness, ext } = self;
2604         matches!(unsafety, Unsafe::Yes(_))
2605             || asyncness.is_async()
2606             || matches!(constness, Const::Yes(_))
2607             || !matches!(ext, Extern::None)
2608     }
2609 }
2610
2611 impl Default for FnHeader {
2612     fn default() -> FnHeader {
2613         FnHeader {
2614             unsafety: Unsafe::No,
2615             asyncness: Async::No,
2616             constness: Const::No,
2617             ext: Extern::None,
2618         }
2619     }
2620 }
2621
2622 #[derive(Clone, Encodable, Decodable, Debug)]
2623 pub enum ItemKind {
2624     /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2625     ///
2626     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2627     ExternCrate(Option<Symbol>),
2628     /// A use declaration item (`use`).
2629     ///
2630     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2631     Use(P<UseTree>),
2632     /// A static item (`static`).
2633     ///
2634     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2635     Static(P<Ty>, Mutability, Option<P<Expr>>),
2636     /// A constant item (`const`).
2637     ///
2638     /// E.g., `const FOO: i32 = 42;`.
2639     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2640     /// A function declaration (`fn`).
2641     ///
2642     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2643     Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2644     /// A module declaration (`mod`).
2645     ///
2646     /// E.g., `mod foo;` or `mod foo { .. }`.
2647     Mod(Mod),
2648     /// An external module (`extern`).
2649     ///
2650     /// E.g., `extern {}` or `extern "C" {}`.
2651     ForeignMod(ForeignMod),
2652     /// Module-level inline assembly (from `global_asm!()`).
2653     GlobalAsm(P<GlobalAsm>),
2654     /// A type alias (`type`).
2655     ///
2656     /// E.g., `type Foo = Bar<u8>;`.
2657     TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2658     /// An enum definition (`enum`).
2659     ///
2660     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2661     Enum(EnumDef, Generics),
2662     /// A struct definition (`struct`).
2663     ///
2664     /// E.g., `struct Foo<A> { x: A }`.
2665     Struct(VariantData, Generics),
2666     /// A union definition (`union`).
2667     ///
2668     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2669     Union(VariantData, Generics),
2670     /// A trait declaration (`trait`).
2671     ///
2672     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2673     Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2674     /// Trait alias
2675     ///
2676     /// E.g., `trait Foo = Bar + Quux;`.
2677     TraitAlias(Generics, GenericBounds),
2678     /// An implementation.
2679     ///
2680     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2681     Impl {
2682         unsafety: Unsafe,
2683         polarity: ImplPolarity,
2684         defaultness: Defaultness,
2685         constness: Const,
2686         generics: Generics,
2687
2688         /// The trait being implemented, if any.
2689         of_trait: Option<TraitRef>,
2690
2691         self_ty: P<Ty>,
2692         items: Vec<P<AssocItem>>,
2693     },
2694     /// A macro invocation.
2695     ///
2696     /// E.g., `foo!(..)`.
2697     MacCall(MacCall),
2698
2699     /// A macro definition.
2700     MacroDef(MacroDef),
2701 }
2702
2703 impl ItemKind {
2704     pub fn article(&self) -> &str {
2705         use ItemKind::*;
2706         match self {
2707             Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2708             | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2709             ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2710         }
2711     }
2712
2713     pub fn descr(&self) -> &str {
2714         match self {
2715             ItemKind::ExternCrate(..) => "extern crate",
2716             ItemKind::Use(..) => "`use` import",
2717             ItemKind::Static(..) => "static item",
2718             ItemKind::Const(..) => "constant item",
2719             ItemKind::Fn(..) => "function",
2720             ItemKind::Mod(..) => "module",
2721             ItemKind::ForeignMod(..) => "extern block",
2722             ItemKind::GlobalAsm(..) => "global asm item",
2723             ItemKind::TyAlias(..) => "type alias",
2724             ItemKind::Enum(..) => "enum",
2725             ItemKind::Struct(..) => "struct",
2726             ItemKind::Union(..) => "union",
2727             ItemKind::Trait(..) => "trait",
2728             ItemKind::TraitAlias(..) => "trait alias",
2729             ItemKind::MacCall(..) => "item macro invocation",
2730             ItemKind::MacroDef(..) => "macro definition",
2731             ItemKind::Impl { .. } => "implementation",
2732         }
2733     }
2734
2735     pub fn generics(&self) -> Option<&Generics> {
2736         match self {
2737             Self::Fn(_, _, generics, _)
2738             | Self::TyAlias(_, generics, ..)
2739             | Self::Enum(_, generics)
2740             | Self::Struct(_, generics)
2741             | Self::Union(_, generics)
2742             | Self::Trait(_, _, generics, ..)
2743             | Self::TraitAlias(generics, _)
2744             | Self::Impl { generics, .. } => Some(generics),
2745             _ => None,
2746         }
2747     }
2748 }
2749
2750 /// Represents associated items.
2751 /// These include items in `impl` and `trait` definitions.
2752 pub type AssocItem = Item<AssocItemKind>;
2753
2754 /// Represents associated item kinds.
2755 ///
2756 /// The term "provided" in the variants below refers to the item having a default
2757 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2758 /// In an implementation, all items must be provided.
2759 /// The `Option`s below denote the bodies, where `Some(_)`
2760 /// means "provided" and conversely `None` means "required".
2761 #[derive(Clone, Encodable, Decodable, Debug)]
2762 pub enum AssocItemKind {
2763     /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2764     /// If `def` is parsed, then the constant is provided, and otherwise required.
2765     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2766     /// An associated function.
2767     Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2768     /// An associated type.
2769     TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2770     /// A macro expanding to associated items.
2771     MacCall(MacCall),
2772 }
2773
2774 impl AssocItemKind {
2775     pub fn defaultness(&self) -> Defaultness {
2776         match *self {
2777             Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def,
2778             Self::MacCall(..) => Defaultness::Final,
2779         }
2780     }
2781 }
2782
2783 impl From<AssocItemKind> for ItemKind {
2784     fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2785         match assoc_item_kind {
2786             AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2787             AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2788             AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2789             AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2790         }
2791     }
2792 }
2793
2794 impl TryFrom<ItemKind> for AssocItemKind {
2795     type Error = ItemKind;
2796
2797     fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2798         Ok(match item_kind {
2799             ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2800             ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
2801             ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
2802             ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2803             _ => return Err(item_kind),
2804         })
2805     }
2806 }
2807
2808 /// An item in `extern` block.
2809 #[derive(Clone, Encodable, Decodable, Debug)]
2810 pub enum ForeignItemKind {
2811     /// A foreign static item (`static FOO: u8`).
2812     Static(P<Ty>, Mutability, Option<P<Expr>>),
2813     /// A foreign function.
2814     Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2815     /// A foreign type.
2816     TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2817     /// A macro expanding to foreign items.
2818     MacCall(MacCall),
2819 }
2820
2821 impl From<ForeignItemKind> for ItemKind {
2822     fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2823         match foreign_item_kind {
2824             ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2825             ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2826             ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2827             ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2828         }
2829     }
2830 }
2831
2832 impl TryFrom<ItemKind> for ForeignItemKind {
2833     type Error = ItemKind;
2834
2835     fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2836         Ok(match item_kind {
2837             ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2838             ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
2839             ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
2840             ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2841             _ => return Err(item_kind),
2842         })
2843     }
2844 }
2845
2846 pub type ForeignItem = Item<ForeignItemKind>;