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