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