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