]> git.proxmox.com Git - rustc.git/blob - src/librustc/hir/mod.rs
New upstream version 1.28.0~beta.14+dfsg1
[rustc.git] / src / librustc / hir / mod.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // The Rust HIR.
12
13 pub use self::BinOp_::*;
14 pub use self::BlockCheckMode::*;
15 pub use self::CaptureClause::*;
16 pub use self::Decl_::*;
17 pub use self::Expr_::*;
18 pub use self::FunctionRetTy::*;
19 pub use self::ForeignItem_::*;
20 pub use self::Item_::*;
21 pub use self::Mutability::*;
22 pub use self::PrimTy::*;
23 pub use self::Stmt_::*;
24 pub use self::Ty_::*;
25 pub use self::TyParamBound::*;
26 pub use self::UnOp::*;
27 pub use self::UnsafeSource::*;
28 pub use self::Visibility::{Public, Inherited};
29
30 use hir::def::Def;
31 use hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
32 use util::nodemap::{NodeMap, FxHashSet};
33 use mir::mono::Linkage;
34
35 use syntax_pos::{Span, DUMMY_SP};
36 use syntax::codemap::{self, Spanned};
37 use rustc_target::spec::abi::Abi;
38 use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, DUMMY_NODE_ID, AsmDialect};
39 use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, MetaItem};
40 use syntax::attr::InlineAttr;
41 use syntax::ext::hygiene::SyntaxContext;
42 use syntax::ptr::P;
43 use syntax::symbol::{Symbol, keywords};
44 use syntax::tokenstream::TokenStream;
45 use syntax::util::ThinVec;
46 use syntax::util::parser::ExprPrecedence;
47 use ty::AdtKind;
48 use ty::query::Providers;
49
50 use rustc_data_structures::indexed_vec;
51 use rustc_data_structures::sync::{ParallelIterator, par_iter, Send, Sync, scope};
52
53 use serialize::{self, Encoder, Encodable, Decoder, Decodable};
54 use std::collections::BTreeMap;
55 use std::fmt;
56 use std::iter;
57 use std::slice;
58
59 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
60 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
61 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
62 /// of `Vec` to avoid keeping extra capacity.
63 pub type HirVec<T> = P<[T]>;
64
65 macro_rules! hir_vec {
66 ($elem:expr; $n:expr) => (
67 $crate::hir::HirVec::from(vec![$elem; $n])
68 );
69 ($($x:expr),*) => (
70 $crate::hir::HirVec::from(vec![$($x),*])
71 );
72 ($($x:expr,)*) => (hir_vec![$($x),*])
73 }
74
75 pub mod check_attr;
76 pub mod def;
77 pub mod def_id;
78 pub mod intravisit;
79 pub mod itemlikevisit;
80 pub mod lowering;
81 pub mod map;
82 pub mod pat_util;
83 pub mod print;
84 pub mod svh;
85
86 /// A HirId uniquely identifies a node in the HIR of the current crate. It is
87 /// composed of the `owner`, which is the DefIndex of the directly enclosing
88 /// hir::Item, hir::TraitItem, or hir::ImplItem (i.e. the closest "item-like"),
89 /// and the `local_id` which is unique within the given owner.
90 ///
91 /// This two-level structure makes for more stable values: One can move an item
92 /// around within the source code, or add or remove stuff before it, without
93 /// the local_id part of the HirId changing, which is a very useful property in
94 /// incremental compilation where we have to persist things through changes to
95 /// the code base.
96 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
97 pub struct HirId {
98 pub owner: DefIndex,
99 pub local_id: ItemLocalId,
100 }
101
102 impl HirId {
103 pub fn owner_def_id(self) -> DefId {
104 DefId::local(self.owner)
105 }
106
107 pub fn owner_local_def_id(self) -> LocalDefId {
108 LocalDefId::from_def_id(DefId::local(self.owner))
109 }
110 }
111
112 impl serialize::UseSpecializedEncodable for HirId {
113 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
114 let HirId {
115 owner,
116 local_id,
117 } = *self;
118
119 owner.encode(s)?;
120 local_id.encode(s)
121 }
122 }
123
124 impl serialize::UseSpecializedDecodable for HirId {
125 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
126 let owner = DefIndex::decode(d)?;
127 let local_id = ItemLocalId::decode(d)?;
128
129 Ok(HirId {
130 owner,
131 local_id
132 })
133 }
134 }
135
136
137 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
138 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
139 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
140 /// the node's position within the owning item in any way, but there is a
141 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
142 /// integers starting at zero, so a mapping that maps all or most nodes within
143 /// an "item-like" to something else can be implement by a `Vec` instead of a
144 /// tree or hash map.
145 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug,
146 RustcEncodable, RustcDecodable)]
147 pub struct ItemLocalId(pub u32);
148
149 impl ItemLocalId {
150 pub fn as_usize(&self) -> usize {
151 self.0 as usize
152 }
153 }
154
155 impl indexed_vec::Idx for ItemLocalId {
156 fn new(idx: usize) -> Self {
157 debug_assert!((idx as u32) as usize == idx);
158 ItemLocalId(idx as u32)
159 }
160
161 fn index(self) -> usize {
162 self.0 as usize
163 }
164 }
165
166 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
167 pub const CRATE_HIR_ID: HirId = HirId {
168 owner: CRATE_DEF_INDEX,
169 local_id: ItemLocalId(0)
170 };
171
172 pub const DUMMY_HIR_ID: HirId = HirId {
173 owner: CRATE_DEF_INDEX,
174 local_id: DUMMY_ITEM_LOCAL_ID,
175 };
176
177 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId(!0);
178
179 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
180 pub struct Label {
181 pub name: Name,
182 pub span: Span,
183 }
184
185 impl fmt::Debug for Label {
186 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
187 write!(f, "label({:?})", self.name)
188 }
189 }
190
191 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
192 pub struct Lifetime {
193 pub id: NodeId,
194 pub span: Span,
195
196 /// Either "'a", referring to a named lifetime definition,
197 /// or "" (aka keywords::Invalid), for elision placeholders.
198 ///
199 /// HIR lowering inserts these placeholders in type paths that
200 /// refer to type definitions needing lifetime parameters,
201 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
202 pub name: LifetimeName,
203 }
204
205 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
206 pub enum LifetimeName {
207 /// User typed nothing. e.g. the lifetime in `&u32`.
208 Implicit,
209
210 /// User typed `'_`.
211 Underscore,
212
213 /// Synthetic name generated when user elided a lifetime in an impl header,
214 /// e.g. the lifetimes in cases like these:
215 ///
216 /// impl Foo for &u32
217 /// impl Foo<'_> for u32
218 ///
219 /// in that case, we rewrite to
220 ///
221 /// impl<'f> Foo for &'f u32
222 /// impl<'f> Foo<'f> for u32
223 ///
224 /// where `'f` is something like `Fresh(0)`. The indices are
225 /// unique per impl, but not necessarily continuous.
226 Fresh(usize),
227
228 /// User wrote `'static`
229 Static,
230
231 /// Some user-given name like `'x`
232 Name(Name),
233 }
234
235 impl LifetimeName {
236 pub fn name(&self) -> Name {
237 use self::LifetimeName::*;
238 match *self {
239 Implicit => keywords::Invalid.name(),
240 Fresh(_) | Underscore => keywords::UnderscoreLifetime.name(),
241 Static => keywords::StaticLifetime.name(),
242 Name(name) => name,
243 }
244 }
245 }
246
247 impl fmt::Debug for Lifetime {
248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
249 write!(f,
250 "lifetime({}: {})",
251 self.id,
252 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
253 }
254 }
255
256 impl Lifetime {
257 pub fn is_elided(&self) -> bool {
258 use self::LifetimeName::*;
259 match self.name {
260 Implicit | Underscore => true,
261
262 // It might seem surprising that `Fresh(_)` counts as
263 // *not* elided -- but this is because, as far as the code
264 // in the compiler is concerned -- `Fresh(_)` variants act
265 // equivalently to "some fresh name". They correspond to
266 // early-bound regions on an impl, in other words.
267 Fresh(_) | Static | Name(_) => false,
268 }
269 }
270
271 pub fn is_static(&self) -> bool {
272 self.name == LifetimeName::Static
273 }
274 }
275
276 /// A lifetime definition, eg `'a: 'b+'c+'d`
277 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
278 pub struct LifetimeDef {
279 pub lifetime: Lifetime,
280 pub bounds: HirVec<Lifetime>,
281 pub pure_wrt_drop: bool,
282 // Indicates that the lifetime definition was synthetically added
283 // as a result of an in-band lifetime usage like
284 // `fn foo(x: &'a u8) -> &'a u8 { x }`
285 pub in_band: bool,
286 }
287
288 /// A "Path" is essentially Rust's notion of a name; for instance:
289 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
290 /// along with a bunch of supporting information.
291 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
292 pub struct Path {
293 pub span: Span,
294 /// The definition that the path resolved to.
295 pub def: Def,
296 /// The segments in the path: the things separated by `::`.
297 pub segments: HirVec<PathSegment>,
298 }
299
300 impl Path {
301 pub fn is_global(&self) -> bool {
302 !self.segments.is_empty() && self.segments[0].name == keywords::CrateRoot.name()
303 }
304 }
305
306 impl fmt::Debug for Path {
307 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
308 write!(f, "path({})", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
309 }
310 }
311
312 impl fmt::Display for Path {
313 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
314 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
315 }
316 }
317
318 /// A segment of a path: an identifier, an optional lifetime, and a set of
319 /// types.
320 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
321 pub struct PathSegment {
322 /// The identifier portion of this path segment.
323 pub name: Name,
324
325 /// Type/lifetime parameters attached to this path. They come in
326 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
327 /// this is more than just simple syntactic sugar; the use of
328 /// parens affects the region binding rules, so we preserve the
329 /// distinction.
330 pub parameters: Option<P<PathParameters>>,
331
332 /// Whether to infer remaining type parameters, if any.
333 /// This only applies to expression and pattern paths, and
334 /// out of those only the segments with no type parameters
335 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
336 pub infer_types: bool,
337 }
338
339 impl PathSegment {
340 /// Convert an identifier to the corresponding segment.
341 pub fn from_name(name: Name) -> PathSegment {
342 PathSegment {
343 name,
344 infer_types: true,
345 parameters: None
346 }
347 }
348
349 pub fn new(name: Name, parameters: PathParameters, infer_types: bool) -> Self {
350 PathSegment {
351 name,
352 infer_types,
353 parameters: if parameters.is_empty() {
354 None
355 } else {
356 Some(P(parameters))
357 }
358 }
359 }
360
361 // FIXME: hack required because you can't create a static
362 // PathParameters, so you can't just return a &PathParameters.
363 pub fn with_parameters<F, R>(&self, f: F) -> R
364 where F: FnOnce(&PathParameters) -> R
365 {
366 let dummy = PathParameters::none();
367 f(if let Some(ref params) = self.parameters {
368 &params
369 } else {
370 &dummy
371 })
372 }
373 }
374
375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
376 pub struct PathParameters {
377 /// The lifetime parameters for this path segment.
378 pub lifetimes: HirVec<Lifetime>,
379 /// The type parameters for this path segment, if present.
380 pub types: HirVec<P<Ty>>,
381 /// Bindings (equality constraints) on associated types, if present.
382 /// E.g., `Foo<A=Bar>`.
383 pub bindings: HirVec<TypeBinding>,
384 /// Were parameters written in parenthesized form `Fn(T) -> U`?
385 /// This is required mostly for pretty-printing and diagnostics,
386 /// but also for changing lifetime elision rules to be "function-like".
387 pub parenthesized: bool,
388 }
389
390 impl PathParameters {
391 pub fn none() -> Self {
392 Self {
393 lifetimes: HirVec::new(),
394 types: HirVec::new(),
395 bindings: HirVec::new(),
396 parenthesized: false,
397 }
398 }
399
400 pub fn is_empty(&self) -> bool {
401 self.lifetimes.is_empty() && self.types.is_empty() &&
402 self.bindings.is_empty() && !self.parenthesized
403 }
404
405 pub fn inputs(&self) -> &[P<Ty>] {
406 if self.parenthesized {
407 if let Some(ref ty) = self.types.get(0) {
408 if let TyTup(ref tys) = ty.node {
409 return tys;
410 }
411 }
412 }
413 bug!("PathParameters::inputs: not a `Fn(T) -> U`");
414 }
415 }
416
417 /// The AST represents all type param bounds as types.
418 /// typeck::collect::compute_bounds matches these against
419 /// the "special" built-in traits (see middle::lang_items) and
420 /// detects Copy, Send and Sync.
421 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
422 pub enum TyParamBound {
423 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
424 RegionTyParamBound(Lifetime),
425 }
426
427 impl TyParamBound {
428 pub fn span(&self) -> Span {
429 match self {
430 &TraitTyParamBound(ref t, ..) => t.span,
431 &RegionTyParamBound(ref l) => l.span,
432 }
433 }
434 }
435
436 /// A modifier on a bound, currently this is only used for `?Sized`, where the
437 /// modifier is `Maybe`. Negative bounds should also be handled here.
438 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
439 pub enum TraitBoundModifier {
440 None,
441 Maybe,
442 }
443
444 pub type TyParamBounds = HirVec<TyParamBound>;
445
446 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
447 pub struct TyParam {
448 pub name: Name,
449 pub id: NodeId,
450 pub bounds: TyParamBounds,
451 pub default: Option<P<Ty>>,
452 pub span: Span,
453 pub pure_wrt_drop: bool,
454 pub synthetic: Option<SyntheticTyParamKind>,
455 pub attrs: HirVec<Attribute>,
456 }
457
458 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
459 pub enum GenericParam {
460 Lifetime(LifetimeDef),
461 Type(TyParam),
462 }
463
464 impl GenericParam {
465 pub fn is_lifetime_param(&self) -> bool {
466 match *self {
467 GenericParam::Lifetime(_) => true,
468 _ => false,
469 }
470 }
471
472 pub fn is_type_param(&self) -> bool {
473 match *self {
474 GenericParam::Type(_) => true,
475 _ => false,
476 }
477 }
478 }
479
480 pub trait GenericParamsExt {
481 fn lifetimes<'a>(&'a self) -> iter::FilterMap<
482 slice::Iter<GenericParam>,
483 fn(&GenericParam) -> Option<&LifetimeDef>,
484 >;
485
486 fn ty_params<'a>(&'a self) -> iter::FilterMap<
487 slice::Iter<GenericParam>,
488 fn(&GenericParam) -> Option<&TyParam>,
489 >;
490 }
491
492 impl GenericParamsExt for [GenericParam] {
493 fn lifetimes<'a>(&'a self) -> iter::FilterMap<
494 slice::Iter<GenericParam>,
495 fn(&GenericParam) -> Option<&LifetimeDef>,
496 > {
497 self.iter().filter_map(|param| match *param {
498 GenericParam::Lifetime(ref l) => Some(l),
499 _ => None,
500 })
501 }
502
503 fn ty_params<'a>(&'a self) -> iter::FilterMap<
504 slice::Iter<GenericParam>,
505 fn(&GenericParam) -> Option<&TyParam>,
506 > {
507 self.iter().filter_map(|param| match *param {
508 GenericParam::Type(ref t) => Some(t),
509 _ => None,
510 })
511 }
512 }
513
514 /// Represents lifetimes and type parameters attached to a declaration
515 /// of a function, enum, trait, etc.
516 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
517 pub struct Generics {
518 pub params: HirVec<GenericParam>,
519 pub where_clause: WhereClause,
520 pub span: Span,
521 }
522
523 impl Generics {
524 pub fn empty() -> Generics {
525 Generics {
526 params: HirVec::new(),
527 where_clause: WhereClause {
528 id: DUMMY_NODE_ID,
529 predicates: HirVec::new(),
530 },
531 span: DUMMY_SP,
532 }
533 }
534
535 pub fn is_lt_parameterized(&self) -> bool {
536 self.params.iter().any(|param| param.is_lifetime_param())
537 }
538
539 pub fn is_type_parameterized(&self) -> bool {
540 self.params.iter().any(|param| param.is_type_param())
541 }
542
543 pub fn lifetimes<'a>(&'a self) -> impl Iterator<Item = &'a LifetimeDef> {
544 self.params.lifetimes()
545 }
546
547 pub fn ty_params<'a>(&'a self) -> impl Iterator<Item = &'a TyParam> {
548 self.params.ty_params()
549 }
550 }
551
552 pub enum UnsafeGeneric {
553 Region(LifetimeDef, &'static str),
554 Type(TyParam, &'static str),
555 }
556
557 impl UnsafeGeneric {
558 pub fn attr_name(&self) -> &'static str {
559 match *self {
560 UnsafeGeneric::Region(_, s) => s,
561 UnsafeGeneric::Type(_, s) => s,
562 }
563 }
564 }
565
566 impl Generics {
567 pub fn carries_unsafe_attr(&self) -> Option<UnsafeGeneric> {
568 for param in &self.params {
569 match *param {
570 GenericParam::Lifetime(ref l) => {
571 if l.pure_wrt_drop {
572 return Some(UnsafeGeneric::Region(l.clone(), "may_dangle"));
573 }
574 }
575 GenericParam::Type(ref t) => {
576 if t.pure_wrt_drop {
577 return Some(UnsafeGeneric::Type(t.clone(), "may_dangle"));
578 }
579 }
580 }
581 }
582
583 None
584 }
585 }
586
587 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
588 /// to track the original form they had. Useful for error messages.
589 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
590 pub enum SyntheticTyParamKind {
591 ImplTrait
592 }
593
594 /// A `where` clause in a definition
595 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
596 pub struct WhereClause {
597 pub id: NodeId,
598 pub predicates: HirVec<WherePredicate>,
599 }
600
601 impl WhereClause {
602 pub fn span(&self) -> Option<Span> {
603 self.predicates.iter().map(|predicate| predicate.span())
604 .fold(None, |acc, i| match (acc, i) {
605 (None, i) => Some(i),
606 (Some(acc), i) => {
607 Some(acc.to(i))
608 }
609 })
610 }
611 }
612
613 /// A single predicate in a `where` clause
614 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
615 pub enum WherePredicate {
616 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
617 BoundPredicate(WhereBoundPredicate),
618 /// A lifetime predicate, e.g. `'a: 'b+'c`
619 RegionPredicate(WhereRegionPredicate),
620 /// An equality predicate (unsupported)
621 EqPredicate(WhereEqPredicate),
622 }
623
624 impl WherePredicate {
625 pub fn span(&self) -> Span {
626 match self {
627 &WherePredicate::BoundPredicate(ref p) => p.span,
628 &WherePredicate::RegionPredicate(ref p) => p.span,
629 &WherePredicate::EqPredicate(ref p) => p.span,
630 }
631 }
632 }
633
634 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
636 pub struct WhereBoundPredicate {
637 pub span: Span,
638 /// Any generics from a `for` binding
639 pub bound_generic_params: HirVec<GenericParam>,
640 /// The type being bounded
641 pub bounded_ty: P<Ty>,
642 /// Trait and lifetime bounds (`Clone+Send+'static`)
643 pub bounds: TyParamBounds,
644 }
645
646 /// A lifetime predicate, e.g. `'a: 'b+'c`
647 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
648 pub struct WhereRegionPredicate {
649 pub span: Span,
650 pub lifetime: Lifetime,
651 pub bounds: HirVec<Lifetime>,
652 }
653
654 /// An equality predicate (unsupported), e.g. `T=int`
655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
656 pub struct WhereEqPredicate {
657 pub id: NodeId,
658 pub span: Span,
659 pub lhs_ty: P<Ty>,
660 pub rhs_ty: P<Ty>,
661 }
662
663 pub type CrateConfig = HirVec<P<MetaItem>>;
664
665 /// The top-level data structure that stores the entire contents of
666 /// the crate currently being compiled.
667 ///
668 /// For more details, see the [rustc guide].
669 ///
670 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/hir.html
671 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
672 pub struct Crate {
673 pub module: Mod,
674 pub attrs: HirVec<Attribute>,
675 pub span: Span,
676 pub exported_macros: HirVec<MacroDef>,
677
678 // NB: We use a BTreeMap here so that `visit_all_items` iterates
679 // over the ids in increasing order. In principle it should not
680 // matter what order we visit things in, but in *practice* it
681 // does, because it can affect the order in which errors are
682 // detected, which in turn can make compile-fail tests yield
683 // slightly different results.
684 pub items: BTreeMap<NodeId, Item>,
685
686 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
687 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
688 pub bodies: BTreeMap<BodyId, Body>,
689 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
690 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
691
692 /// A list of the body ids written out in the order in which they
693 /// appear in the crate. If you're going to process all the bodies
694 /// in the crate, you should iterate over this list rather than the keys
695 /// of bodies.
696 pub body_ids: Vec<BodyId>,
697 }
698
699 impl Crate {
700 pub fn item(&self, id: NodeId) -> &Item {
701 &self.items[&id]
702 }
703
704 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
705 &self.trait_items[&id]
706 }
707
708 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
709 &self.impl_items[&id]
710 }
711
712 /// Visits all items in the crate in some deterministic (but
713 /// unspecified) order. If you just need to process every item,
714 /// but don't care about nesting, this method is the best choice.
715 ///
716 /// If you do care about nesting -- usually because your algorithm
717 /// follows lexical scoping rules -- then you want a different
718 /// approach. You should override `visit_nested_item` in your
719 /// visitor and then call `intravisit::walk_crate` instead.
720 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
721 where V: itemlikevisit::ItemLikeVisitor<'hir>
722 {
723 for (_, item) in &self.items {
724 visitor.visit_item(item);
725 }
726
727 for (_, trait_item) in &self.trait_items {
728 visitor.visit_trait_item(trait_item);
729 }
730
731 for (_, impl_item) in &self.impl_items {
732 visitor.visit_impl_item(impl_item);
733 }
734 }
735
736 /// A parallel version of visit_all_item_likes
737 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
738 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
739 {
740 scope(|s| {
741 s.spawn(|_| {
742 par_iter(&self.items).for_each(|(_, item)| {
743 visitor.visit_item(item);
744 });
745 });
746
747 s.spawn(|_| {
748 par_iter(&self.trait_items).for_each(|(_, trait_item)| {
749 visitor.visit_trait_item(trait_item);
750 });
751 });
752
753 s.spawn(|_| {
754 par_iter(&self.impl_items).for_each(|(_, impl_item)| {
755 visitor.visit_impl_item(impl_item);
756 });
757 });
758 });
759 }
760
761 pub fn body(&self, id: BodyId) -> &Body {
762 &self.bodies[&id]
763 }
764 }
765
766 /// A macro definition, in this crate or imported from another.
767 ///
768 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
769 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
770 pub struct MacroDef {
771 pub name: Name,
772 pub vis: Visibility,
773 pub attrs: HirVec<Attribute>,
774 pub id: NodeId,
775 pub span: Span,
776 pub body: TokenStream,
777 pub legacy: bool,
778 }
779
780 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
781 pub struct Block {
782 /// Statements in a block
783 pub stmts: HirVec<Stmt>,
784 /// An expression at the end of the block
785 /// without a semicolon, if any
786 pub expr: Option<P<Expr>>,
787 pub id: NodeId,
788 pub hir_id: HirId,
789 /// Distinguishes between `unsafe { ... }` and `{ ... }`
790 pub rules: BlockCheckMode,
791 pub span: Span,
792 /// If true, then there may exist `break 'a` values that aim to
793 /// break out of this block early.
794 /// Used by `'label: {}` blocks and by `catch` statements.
795 pub targeted_by_break: bool,
796 /// If true, don't emit return value type errors as the parser had
797 /// to recover from a parse error so this block will not have an
798 /// appropriate type. A parse error will have been emitted so the
799 /// compilation will never succeed if this is true.
800 pub recovered: bool,
801 }
802
803 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
804 pub struct Pat {
805 pub id: NodeId,
806 pub hir_id: HirId,
807 pub node: PatKind,
808 pub span: Span,
809 }
810
811 impl fmt::Debug for Pat {
812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
813 write!(f, "pat({}: {})", self.id,
814 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
815 }
816 }
817
818 impl Pat {
819 // FIXME(#19596) this is a workaround, but there should be a better way
820 fn walk_<G>(&self, it: &mut G) -> bool
821 where G: FnMut(&Pat) -> bool
822 {
823 if !it(self) {
824 return false;
825 }
826
827 match self.node {
828 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
829 PatKind::Struct(_, ref fields, _) => {
830 fields.iter().all(|field| field.node.pat.walk_(it))
831 }
832 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
833 s.iter().all(|p| p.walk_(it))
834 }
835 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
836 s.walk_(it)
837 }
838 PatKind::Slice(ref before, ref slice, ref after) => {
839 before.iter().all(|p| p.walk_(it)) &&
840 slice.iter().all(|p| p.walk_(it)) &&
841 after.iter().all(|p| p.walk_(it))
842 }
843 PatKind::Wild |
844 PatKind::Lit(_) |
845 PatKind::Range(..) |
846 PatKind::Binding(..) |
847 PatKind::Path(_) => {
848 true
849 }
850 }
851 }
852
853 pub fn walk<F>(&self, mut it: F) -> bool
854 where F: FnMut(&Pat) -> bool
855 {
856 self.walk_(&mut it)
857 }
858 }
859
860 /// A single field in a struct pattern
861 ///
862 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
863 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
864 /// except is_shorthand is true
865 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
866 pub struct FieldPat {
867 pub id: NodeId,
868 /// The identifier for the field
869 pub ident: Ident,
870 /// The pattern the field is destructured to
871 pub pat: P<Pat>,
872 pub is_shorthand: bool,
873 }
874
875 /// Explicit binding annotations given in the HIR for a binding. Note
876 /// that this is not the final binding *mode* that we infer after type
877 /// inference.
878 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
879 pub enum BindingAnnotation {
880 /// No binding annotation given: this means that the final binding mode
881 /// will depend on whether we have skipped through a `&` reference
882 /// when matching. For example, the `x` in `Some(x)` will have binding
883 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
884 /// ultimately be inferred to be by-reference.
885 ///
886 /// Note that implicit reference skipping is not implemented yet (#42640).
887 Unannotated,
888
889 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
890 Mutable,
891
892 /// Annotated as `ref`, like `ref x`
893 Ref,
894
895 /// Annotated as `ref mut x`.
896 RefMut,
897 }
898
899 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
900 pub enum RangeEnd {
901 Included,
902 Excluded,
903 }
904
905 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
906 pub enum PatKind {
907 /// Represents a wildcard pattern (`_`)
908 Wild,
909
910 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
911 /// The `NodeId` is the canonical ID for the variable being bound,
912 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
913 /// which is the pattern ID of the first `x`.
914 Binding(BindingAnnotation, NodeId, Spanned<Name>, Option<P<Pat>>),
915
916 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
917 /// The `bool` is `true` in the presence of a `..`.
918 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
919
920 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
921 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
922 /// 0 <= position <= subpats.len()
923 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
924
925 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
926 Path(QPath),
927
928 /// A tuple pattern `(a, b)`.
929 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
930 /// 0 <= position <= subpats.len()
931 Tuple(HirVec<P<Pat>>, Option<usize>),
932 /// A `box` pattern
933 Box(P<Pat>),
934 /// A reference pattern, e.g. `&mut (a, b)`
935 Ref(P<Pat>, Mutability),
936 /// A literal
937 Lit(P<Expr>),
938 /// A range pattern, e.g. `1...2` or `1..2`
939 Range(P<Expr>, P<Expr>, RangeEnd),
940 /// `[a, b, ..i, y, z]` is represented as:
941 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
942 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
943 }
944
945 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
946 pub enum Mutability {
947 MutMutable,
948 MutImmutable,
949 }
950
951 impl Mutability {
952 /// Return MutMutable only if both arguments are mutable.
953 pub fn and(self, other: Self) -> Self {
954 match self {
955 MutMutable => other,
956 MutImmutable => MutImmutable,
957 }
958 }
959 }
960
961 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
962 pub enum BinOp_ {
963 /// The `+` operator (addition)
964 BiAdd,
965 /// The `-` operator (subtraction)
966 BiSub,
967 /// The `*` operator (multiplication)
968 BiMul,
969 /// The `/` operator (division)
970 BiDiv,
971 /// The `%` operator (modulus)
972 BiRem,
973 /// The `&&` operator (logical and)
974 BiAnd,
975 /// The `||` operator (logical or)
976 BiOr,
977 /// The `^` operator (bitwise xor)
978 BiBitXor,
979 /// The `&` operator (bitwise and)
980 BiBitAnd,
981 /// The `|` operator (bitwise or)
982 BiBitOr,
983 /// The `<<` operator (shift left)
984 BiShl,
985 /// The `>>` operator (shift right)
986 BiShr,
987 /// The `==` operator (equality)
988 BiEq,
989 /// The `<` operator (less than)
990 BiLt,
991 /// The `<=` operator (less than or equal to)
992 BiLe,
993 /// The `!=` operator (not equal to)
994 BiNe,
995 /// The `>=` operator (greater than or equal to)
996 BiGe,
997 /// The `>` operator (greater than)
998 BiGt,
999 }
1000
1001 impl BinOp_ {
1002 pub fn as_str(self) -> &'static str {
1003 match self {
1004 BiAdd => "+",
1005 BiSub => "-",
1006 BiMul => "*",
1007 BiDiv => "/",
1008 BiRem => "%",
1009 BiAnd => "&&",
1010 BiOr => "||",
1011 BiBitXor => "^",
1012 BiBitAnd => "&",
1013 BiBitOr => "|",
1014 BiShl => "<<",
1015 BiShr => ">>",
1016 BiEq => "==",
1017 BiLt => "<",
1018 BiLe => "<=",
1019 BiNe => "!=",
1020 BiGe => ">=",
1021 BiGt => ">",
1022 }
1023 }
1024
1025 pub fn is_lazy(self) -> bool {
1026 match self {
1027 BiAnd | BiOr => true,
1028 _ => false,
1029 }
1030 }
1031
1032 pub fn is_shift(self) -> bool {
1033 match self {
1034 BiShl | BiShr => true,
1035 _ => false,
1036 }
1037 }
1038
1039 pub fn is_comparison(self) -> bool {
1040 match self {
1041 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
1042 BiAnd |
1043 BiOr |
1044 BiAdd |
1045 BiSub |
1046 BiMul |
1047 BiDiv |
1048 BiRem |
1049 BiBitXor |
1050 BiBitAnd |
1051 BiBitOr |
1052 BiShl |
1053 BiShr => false,
1054 }
1055 }
1056
1057 /// Returns `true` if the binary operator takes its arguments by value
1058 pub fn is_by_value(self) -> bool {
1059 !self.is_comparison()
1060 }
1061 }
1062
1063 impl Into<ast::BinOpKind> for BinOp_ {
1064 fn into(self) -> ast::BinOpKind {
1065 match self {
1066 BiAdd => ast::BinOpKind::Add,
1067 BiSub => ast::BinOpKind::Sub,
1068 BiMul => ast::BinOpKind::Mul,
1069 BiDiv => ast::BinOpKind::Div,
1070 BiRem => ast::BinOpKind::Rem,
1071 BiAnd => ast::BinOpKind::And,
1072 BiOr => ast::BinOpKind::Or,
1073 BiBitXor => ast::BinOpKind::BitXor,
1074 BiBitAnd => ast::BinOpKind::BitAnd,
1075 BiBitOr => ast::BinOpKind::BitOr,
1076 BiShl => ast::BinOpKind::Shl,
1077 BiShr => ast::BinOpKind::Shr,
1078 BiEq => ast::BinOpKind::Eq,
1079 BiLt => ast::BinOpKind::Lt,
1080 BiLe => ast::BinOpKind::Le,
1081 BiNe => ast::BinOpKind::Ne,
1082 BiGe => ast::BinOpKind::Ge,
1083 BiGt => ast::BinOpKind::Gt,
1084 }
1085 }
1086 }
1087
1088 pub type BinOp = Spanned<BinOp_>;
1089
1090 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1091 pub enum UnOp {
1092 /// The `*` operator for dereferencing
1093 UnDeref,
1094 /// The `!` operator for logical inversion
1095 UnNot,
1096 /// The `-` operator for negation
1097 UnNeg,
1098 }
1099
1100 impl UnOp {
1101 pub fn as_str(self) -> &'static str {
1102 match self {
1103 UnDeref => "*",
1104 UnNot => "!",
1105 UnNeg => "-",
1106 }
1107 }
1108
1109 /// Returns `true` if the unary operator takes its argument by value
1110 pub fn is_by_value(self) -> bool {
1111 match self {
1112 UnNeg | UnNot => true,
1113 _ => false,
1114 }
1115 }
1116 }
1117
1118 /// A statement
1119 pub type Stmt = Spanned<Stmt_>;
1120
1121 impl fmt::Debug for Stmt_ {
1122 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1123 // Sadness.
1124 let spanned = codemap::dummy_spanned(self.clone());
1125 write!(f,
1126 "stmt({}: {})",
1127 spanned.node.id(),
1128 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
1129 }
1130 }
1131
1132 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1133 pub enum Stmt_ {
1134 /// Could be an item or a local (let) binding:
1135 StmtDecl(P<Decl>, NodeId),
1136
1137 /// Expr without trailing semi-colon (must have unit type):
1138 StmtExpr(P<Expr>, NodeId),
1139
1140 /// Expr with trailing semi-colon (may have any type):
1141 StmtSemi(P<Expr>, NodeId),
1142 }
1143
1144 impl Stmt_ {
1145 pub fn attrs(&self) -> &[Attribute] {
1146 match *self {
1147 StmtDecl(ref d, _) => d.node.attrs(),
1148 StmtExpr(ref e, _) |
1149 StmtSemi(ref e, _) => &e.attrs,
1150 }
1151 }
1152
1153 pub fn id(&self) -> NodeId {
1154 match *self {
1155 StmtDecl(_, id) => id,
1156 StmtExpr(_, id) => id,
1157 StmtSemi(_, id) => id,
1158 }
1159 }
1160 }
1161
1162 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
1163 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1164 pub struct Local {
1165 pub pat: P<Pat>,
1166 pub ty: Option<P<Ty>>,
1167 /// Initializer expression to set the value, if any
1168 pub init: Option<P<Expr>>,
1169 pub id: NodeId,
1170 pub hir_id: HirId,
1171 pub span: Span,
1172 pub attrs: ThinVec<Attribute>,
1173 pub source: LocalSource,
1174 }
1175
1176 pub type Decl = Spanned<Decl_>;
1177
1178 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1179 pub enum Decl_ {
1180 /// A local (let) binding:
1181 DeclLocal(P<Local>),
1182 /// An item binding:
1183 DeclItem(ItemId),
1184 }
1185
1186 impl Decl_ {
1187 pub fn attrs(&self) -> &[Attribute] {
1188 match *self {
1189 DeclLocal(ref l) => &l.attrs,
1190 DeclItem(_) => &[]
1191 }
1192 }
1193
1194 pub fn is_local(&self) -> bool {
1195 match *self {
1196 Decl_::DeclLocal(_) => true,
1197 _ => false,
1198 }
1199 }
1200 }
1201
1202 /// represents one arm of a 'match'
1203 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1204 pub struct Arm {
1205 pub attrs: HirVec<Attribute>,
1206 pub pats: HirVec<P<Pat>>,
1207 pub guard: Option<P<Expr>>,
1208 pub body: P<Expr>,
1209 }
1210
1211 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1212 pub struct Field {
1213 pub id: NodeId,
1214 pub ident: Ident,
1215 pub expr: P<Expr>,
1216 pub span: Span,
1217 pub is_shorthand: bool,
1218 }
1219
1220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1221 pub enum BlockCheckMode {
1222 DefaultBlock,
1223 UnsafeBlock(UnsafeSource),
1224 PushUnsafeBlock(UnsafeSource),
1225 PopUnsafeBlock(UnsafeSource),
1226 }
1227
1228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1229 pub enum UnsafeSource {
1230 CompilerGenerated,
1231 UserProvided,
1232 }
1233
1234 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1235 pub struct BodyId {
1236 pub node_id: NodeId,
1237 }
1238
1239 /// The body of a function, closure, or constant value. In the case of
1240 /// a function, the body contains not only the function body itself
1241 /// (which is an expression), but also the argument patterns, since
1242 /// those are something that the caller doesn't really care about.
1243 ///
1244 /// # Examples
1245 ///
1246 /// ```
1247 /// fn foo((x, y): (u32, u32)) -> u32 {
1248 /// x + y
1249 /// }
1250 /// ```
1251 ///
1252 /// Here, the `Body` associated with `foo()` would contain:
1253 ///
1254 /// - an `arguments` array containing the `(x, y)` pattern
1255 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1256 /// - `is_generator` would be false
1257 ///
1258 /// All bodies have an **owner**, which can be accessed via the HIR
1259 /// map using `body_owner_def_id()`.
1260 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1261 pub struct Body {
1262 pub arguments: HirVec<Arg>,
1263 pub value: Expr,
1264 pub is_generator: bool,
1265 }
1266
1267 impl Body {
1268 pub fn id(&self) -> BodyId {
1269 BodyId {
1270 node_id: self.value.id
1271 }
1272 }
1273 }
1274
1275 #[derive(Copy, Clone, Debug)]
1276 pub enum BodyOwnerKind {
1277 /// Functions and methods.
1278 Fn,
1279
1280 /// Constants and associated constants.
1281 Const,
1282
1283 /// Initializer of a `static` item.
1284 Static(Mutability),
1285 }
1286
1287 /// A constant (expression) that's not an item or associated item,
1288 /// but needs its own `DefId` for type-checking, const-eval, etc.
1289 /// These are usually found nested inside types (e.g. array lengths)
1290 /// or expressions (e.g. repeat counts), and also used to define
1291 /// explicit discriminant values for enum variants.
1292 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1293 pub struct AnonConst {
1294 pub id: NodeId,
1295 pub hir_id: HirId,
1296 pub body: BodyId,
1297 }
1298
1299 /// An expression
1300 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1301 pub struct Expr {
1302 pub id: NodeId,
1303 pub span: Span,
1304 pub node: Expr_,
1305 pub attrs: ThinVec<Attribute>,
1306 pub hir_id: HirId,
1307 }
1308
1309 impl Expr {
1310 pub fn precedence(&self) -> ExprPrecedence {
1311 match self.node {
1312 ExprBox(_) => ExprPrecedence::Box,
1313 ExprArray(_) => ExprPrecedence::Array,
1314 ExprCall(..) => ExprPrecedence::Call,
1315 ExprMethodCall(..) => ExprPrecedence::MethodCall,
1316 ExprTup(_) => ExprPrecedence::Tup,
1317 ExprBinary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1318 ExprUnary(..) => ExprPrecedence::Unary,
1319 ExprLit(_) => ExprPrecedence::Lit,
1320 ExprType(..) | ExprCast(..) => ExprPrecedence::Cast,
1321 ExprIf(..) => ExprPrecedence::If,
1322 ExprWhile(..) => ExprPrecedence::While,
1323 ExprLoop(..) => ExprPrecedence::Loop,
1324 ExprMatch(..) => ExprPrecedence::Match,
1325 ExprClosure(..) => ExprPrecedence::Closure,
1326 ExprBlock(..) => ExprPrecedence::Block,
1327 ExprAssign(..) => ExprPrecedence::Assign,
1328 ExprAssignOp(..) => ExprPrecedence::AssignOp,
1329 ExprField(..) => ExprPrecedence::Field,
1330 ExprIndex(..) => ExprPrecedence::Index,
1331 ExprPath(..) => ExprPrecedence::Path,
1332 ExprAddrOf(..) => ExprPrecedence::AddrOf,
1333 ExprBreak(..) => ExprPrecedence::Break,
1334 ExprAgain(..) => ExprPrecedence::Continue,
1335 ExprRet(..) => ExprPrecedence::Ret,
1336 ExprInlineAsm(..) => ExprPrecedence::InlineAsm,
1337 ExprStruct(..) => ExprPrecedence::Struct,
1338 ExprRepeat(..) => ExprPrecedence::Repeat,
1339 ExprYield(..) => ExprPrecedence::Yield,
1340 }
1341 }
1342 }
1343
1344 impl fmt::Debug for Expr {
1345 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1346 write!(f, "expr({}: {})", self.id,
1347 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1348 }
1349 }
1350
1351 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1352 pub enum Expr_ {
1353 /// A `box x` expression.
1354 ExprBox(P<Expr>),
1355 /// An array (`[a, b, c, d]`)
1356 ExprArray(HirVec<Expr>),
1357 /// A function call
1358 ///
1359 /// The first field resolves to the function itself (usually an `ExprPath`),
1360 /// and the second field is the list of arguments.
1361 /// This also represents calling the constructor of
1362 /// tuple-like ADTs such as tuple structs and enum variants.
1363 ExprCall(P<Expr>, HirVec<Expr>),
1364 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1365 ///
1366 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1367 /// (within the angle brackets).
1368 /// The first element of the vector of `Expr`s is the expression that evaluates
1369 /// to the object on which the method is being called on (the receiver),
1370 /// and the remaining elements are the rest of the arguments.
1371 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1372 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1373 ExprMethodCall(PathSegment, Span, HirVec<Expr>),
1374 /// A tuple (`(a, b, c ,d)`)
1375 ExprTup(HirVec<Expr>),
1376 /// A binary operation (For example: `a + b`, `a * b`)
1377 ExprBinary(BinOp, P<Expr>, P<Expr>),
1378 /// A unary operation (For example: `!x`, `*x`)
1379 ExprUnary(UnOp, P<Expr>),
1380 /// A literal (For example: `1`, `"foo"`)
1381 ExprLit(P<Lit>),
1382 /// A cast (`foo as f64`)
1383 ExprCast(P<Expr>, P<Ty>),
1384 ExprType(P<Expr>, P<Ty>),
1385 /// An `if` block, with an optional else block
1386 ///
1387 /// `if expr { expr } else { expr }`
1388 ExprIf(P<Expr>, P<Expr>, Option<P<Expr>>),
1389 /// A while loop, with an optional label
1390 ///
1391 /// `'label: while expr { block }`
1392 ExprWhile(P<Expr>, P<Block>, Option<Label>),
1393 /// Conditionless loop (can be exited with break, continue, or return)
1394 ///
1395 /// `'label: loop { block }`
1396 ExprLoop(P<Block>, Option<Label>, LoopSource),
1397 /// A `match` block, with a source that indicates whether or not it is
1398 /// the result of a desugaring, and if so, which kind.
1399 ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
1400 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1401 ///
1402 /// The final span is the span of the argument block `|...|`
1403 ///
1404 /// This may also be a generator literal, indicated by the final boolean,
1405 /// in that case there is an GeneratorClause.
1406 ExprClosure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1407 /// A block (`'label: { ... }`)
1408 ExprBlock(P<Block>, Option<Label>),
1409
1410 /// An assignment (`a = foo()`)
1411 ExprAssign(P<Expr>, P<Expr>),
1412 /// An assignment with an operator
1413 ///
1414 /// For example, `a += 1`.
1415 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
1416 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct or tuple field
1417 ExprField(P<Expr>, Ident),
1418 /// An indexing operation (`foo[2]`)
1419 ExprIndex(P<Expr>, P<Expr>),
1420
1421 /// Path to a definition, possibly containing lifetime or type parameters.
1422 ExprPath(QPath),
1423
1424 /// A referencing operation (`&a` or `&mut a`)
1425 ExprAddrOf(Mutability, P<Expr>),
1426 /// A `break`, with an optional label to break
1427 ExprBreak(Destination, Option<P<Expr>>),
1428 /// A `continue`, with an optional label
1429 ExprAgain(Destination),
1430 /// A `return`, with an optional value to be returned
1431 ExprRet(Option<P<Expr>>),
1432
1433 /// Inline assembly (from `asm!`), with its outputs and inputs.
1434 ExprInlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1435
1436 /// A struct or struct-like variant literal expression.
1437 ///
1438 /// For example, `Foo {x: 1, y: 2}`, or
1439 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1440 ExprStruct(QPath, HirVec<Field>, Option<P<Expr>>),
1441
1442 /// An array literal constructed from one repeated element.
1443 ///
1444 /// For example, `[1; 5]`. The first expression is the element
1445 /// to be repeated; the second is the number of times to repeat it.
1446 ExprRepeat(P<Expr>, AnonConst),
1447
1448 /// A suspension point for generators. This is `yield <expr>` in Rust.
1449 ExprYield(P<Expr>),
1450 }
1451
1452 /// Optionally `Self`-qualified value/type path or associated extension.
1453 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1454 pub enum QPath {
1455 /// Path to a definition, optionally "fully-qualified" with a `Self`
1456 /// type, if the path points to an associated item in a trait.
1457 ///
1458 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1459 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1460 /// even though they both have the same two-segment `Clone::clone` `Path`.
1461 Resolved(Option<P<Ty>>, P<Path>),
1462
1463 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1464 /// Will be resolved by type-checking to an associated item.
1465 ///
1466 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1467 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1468 /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1469 TypeRelative(P<Ty>, P<PathSegment>)
1470 }
1471
1472 /// Hints at the original code for a let statement
1473 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1474 pub enum LocalSource {
1475 /// A `match _ { .. }`
1476 Normal,
1477 /// A desugared `for _ in _ { .. }` loop
1478 ForLoopDesugar,
1479 }
1480
1481 /// Hints at the original code for a `match _ { .. }`
1482 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1483 pub enum MatchSource {
1484 /// A `match _ { .. }`
1485 Normal,
1486 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1487 IfLetDesugar {
1488 contains_else_clause: bool,
1489 },
1490 /// A `while let _ = _ { .. }` (which was desugared to a
1491 /// `loop { match _ { .. } }`)
1492 WhileLetDesugar,
1493 /// A desugared `for _ in _ { .. }` loop
1494 ForLoopDesugar,
1495 /// A desugared `?` operator
1496 TryDesugar,
1497 }
1498
1499 /// The loop type that yielded an ExprLoop
1500 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1501 pub enum LoopSource {
1502 /// A `loop { .. }` loop
1503 Loop,
1504 /// A `while let _ = _ { .. }` loop
1505 WhileLet,
1506 /// A `for _ in _ { .. }` loop
1507 ForLoop,
1508 }
1509
1510 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1511 pub enum LoopIdError {
1512 OutsideLoopScope,
1513 UnlabeledCfInWhileCondition,
1514 UnresolvedLabel,
1515 }
1516
1517 impl fmt::Display for LoopIdError {
1518 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1519 fmt::Display::fmt(match *self {
1520 LoopIdError::OutsideLoopScope => "not inside loop scope",
1521 LoopIdError::UnlabeledCfInWhileCondition =>
1522 "unlabeled control flow (break or continue) in while condition",
1523 LoopIdError::UnresolvedLabel => "label not found",
1524 }, f)
1525 }
1526 }
1527
1528 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1529 pub struct Destination {
1530 // This is `Some(_)` iff there is an explicit user-specified `label
1531 pub label: Option<Label>,
1532
1533 // These errors are caught and then reported during the diagnostics pass in
1534 // librustc_passes/loops.rs
1535 pub target_id: Result<NodeId, LoopIdError>,
1536 }
1537
1538 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1539 pub enum GeneratorMovability {
1540 Static,
1541 Movable,
1542 }
1543
1544 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1545 pub enum CaptureClause {
1546 CaptureByValue,
1547 CaptureByRef,
1548 }
1549
1550 // NB: If you change this, you'll probably want to change the corresponding
1551 // type structure in middle/ty.rs as well.
1552 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1553 pub struct MutTy {
1554 pub ty: P<Ty>,
1555 pub mutbl: Mutability,
1556 }
1557
1558 /// Represents a method's signature in a trait declaration or implementation.
1559 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1560 pub struct MethodSig {
1561 pub unsafety: Unsafety,
1562 pub constness: Constness,
1563 pub abi: Abi,
1564 pub decl: P<FnDecl>,
1565 }
1566
1567 // The bodies for items are stored "out of line", in a separate
1568 // hashmap in the `Crate`. Here we just record the node-id of the item
1569 // so it can fetched later.
1570 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1571 pub struct TraitItemId {
1572 pub node_id: NodeId,
1573 }
1574
1575 /// Represents an item declaration within a trait declaration,
1576 /// possibly including a default implementation. A trait item is
1577 /// either required (meaning it doesn't have an implementation, just a
1578 /// signature) or provided (meaning it has a default implementation).
1579 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1580 pub struct TraitItem {
1581 pub id: NodeId,
1582 pub name: Name,
1583 pub hir_id: HirId,
1584 pub attrs: HirVec<Attribute>,
1585 pub generics: Generics,
1586 pub node: TraitItemKind,
1587 pub span: Span,
1588 }
1589
1590 /// A trait method's body (or just argument names).
1591 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1592 pub enum TraitMethod {
1593 /// No default body in the trait, just a signature.
1594 Required(HirVec<Spanned<Name>>),
1595
1596 /// Both signature and body are provided in the trait.
1597 Provided(BodyId),
1598 }
1599
1600 /// Represents a trait method or associated constant or type
1601 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1602 pub enum TraitItemKind {
1603 /// An associated constant with an optional value (otherwise `impl`s
1604 /// must contain a value)
1605 Const(P<Ty>, Option<BodyId>),
1606 /// A method with an optional body
1607 Method(MethodSig, TraitMethod),
1608 /// An associated type with (possibly empty) bounds and optional concrete
1609 /// type
1610 Type(TyParamBounds, Option<P<Ty>>),
1611 }
1612
1613 // The bodies for items are stored "out of line", in a separate
1614 // hashmap in the `Crate`. Here we just record the node-id of the item
1615 // so it can fetched later.
1616 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1617 pub struct ImplItemId {
1618 pub node_id: NodeId,
1619 }
1620
1621 /// Represents anything within an `impl` block
1622 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1623 pub struct ImplItem {
1624 pub id: NodeId,
1625 pub name: Name,
1626 pub hir_id: HirId,
1627 pub vis: Visibility,
1628 pub defaultness: Defaultness,
1629 pub attrs: HirVec<Attribute>,
1630 pub generics: Generics,
1631 pub node: ImplItemKind,
1632 pub span: Span,
1633 }
1634
1635 /// Represents different contents within `impl`s
1636 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1637 pub enum ImplItemKind {
1638 /// An associated constant of the given type, set to the constant result
1639 /// of the expression
1640 Const(P<Ty>, BodyId),
1641 /// A method implementation with the given signature and body
1642 Method(MethodSig, BodyId),
1643 /// An associated type
1644 Type(P<Ty>),
1645 }
1646
1647 // Bind a type to an associated type: `A=Foo`.
1648 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1649 pub struct TypeBinding {
1650 pub id: NodeId,
1651 pub name: Name,
1652 pub ty: P<Ty>,
1653 pub span: Span,
1654 }
1655
1656
1657 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1658 pub struct Ty {
1659 pub id: NodeId,
1660 pub node: Ty_,
1661 pub span: Span,
1662 pub hir_id: HirId,
1663 }
1664
1665 impl fmt::Debug for Ty {
1666 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1667 write!(f, "type({})",
1668 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1669 }
1670 }
1671
1672 /// Not represented directly in the AST, referred to by name through a ty_path.
1673 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1674 pub enum PrimTy {
1675 TyInt(IntTy),
1676 TyUint(UintTy),
1677 TyFloat(FloatTy),
1678 TyStr,
1679 TyBool,
1680 TyChar,
1681 }
1682
1683 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1684 pub struct BareFnTy {
1685 pub unsafety: Unsafety,
1686 pub abi: Abi,
1687 pub generic_params: HirVec<GenericParam>,
1688 pub decl: P<FnDecl>,
1689 pub arg_names: HirVec<Spanned<Name>>,
1690 }
1691
1692 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1693 pub struct ExistTy {
1694 pub generics: Generics,
1695 pub bounds: TyParamBounds,
1696 pub impl_trait_fn: Option<DefId>,
1697 }
1698
1699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1700 /// The different kinds of types recognized by the compiler
1701 pub enum Ty_ {
1702 /// A variable length slice (`[T]`)
1703 TySlice(P<Ty>),
1704 /// A fixed length array (`[T; n]`)
1705 TyArray(P<Ty>, AnonConst),
1706 /// A raw pointer (`*const T` or `*mut T`)
1707 TyPtr(MutTy),
1708 /// A reference (`&'a T` or `&'a mut T`)
1709 TyRptr(Lifetime, MutTy),
1710 /// A bare function (e.g. `fn(usize) -> bool`)
1711 TyBareFn(P<BareFnTy>),
1712 /// The never type (`!`)
1713 TyNever,
1714 /// A tuple (`(A, B, C, D,...)`)
1715 TyTup(HirVec<P<Ty>>),
1716 /// A path to a type definition (`module::module::...::Type`), or an
1717 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1718 ///
1719 /// Type parameters may be stored in each `PathSegment`.
1720 TyPath(QPath),
1721 /// A trait object type `Bound1 + Bound2 + Bound3`
1722 /// where `Bound` is a trait or a lifetime.
1723 TyTraitObject(HirVec<PolyTraitRef>, Lifetime),
1724 /// An existentially quantified (there exists a type satisfying) `impl
1725 /// Bound1 + Bound2 + Bound3` type where `Bound` is a trait or a lifetime.
1726 ///
1727 /// The `Item` is the generated
1728 /// `existential type Foo<'a, 'b>: MyTrait<'a, 'b>;`.
1729 ///
1730 /// The `HirVec<Lifetime>` is the list of lifetimes applied as parameters
1731 /// to the `abstract type`, e.g. the `'c` and `'d` in `-> Foo<'c, 'd>`.
1732 /// This list is only a list of lifetimes and not type parameters
1733 /// because all in-scope type parameters are captured by `impl Trait`,
1734 /// so they are resolved directly through the parent `Generics`.
1735 TyImplTraitExistential(ItemId, DefId, HirVec<Lifetime>),
1736 /// Unused for now
1737 TyTypeof(AnonConst),
1738 /// TyInfer means the type should be inferred instead of it having been
1739 /// specified. This can appear anywhere in a type.
1740 TyInfer,
1741 /// Placeholder for a type that has failed to be defined.
1742 TyErr,
1743 }
1744
1745 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1746 pub struct InlineAsmOutput {
1747 pub constraint: Symbol,
1748 pub is_rw: bool,
1749 pub is_indirect: bool,
1750 }
1751
1752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1753 pub struct InlineAsm {
1754 pub asm: Symbol,
1755 pub asm_str_style: StrStyle,
1756 pub outputs: HirVec<InlineAsmOutput>,
1757 pub inputs: HirVec<Symbol>,
1758 pub clobbers: HirVec<Symbol>,
1759 pub volatile: bool,
1760 pub alignstack: bool,
1761 pub dialect: AsmDialect,
1762 pub ctxt: SyntaxContext,
1763 }
1764
1765 /// represents an argument in a function header
1766 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1767 pub struct Arg {
1768 pub pat: P<Pat>,
1769 pub id: NodeId,
1770 pub hir_id: HirId,
1771 }
1772
1773 /// Represents the header (not the body) of a function declaration
1774 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1775 pub struct FnDecl {
1776 pub inputs: HirVec<P<Ty>>,
1777 pub output: FunctionRetTy,
1778 pub variadic: bool,
1779 /// True if this function has an `self`, `&self` or `&mut self` receiver
1780 /// (but not a `self: Xxx` one).
1781 pub has_implicit_self: bool,
1782 }
1783
1784 /// Is the trait definition an auto trait?
1785 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1786 pub enum IsAuto {
1787 Yes,
1788 No
1789 }
1790
1791 #[derive(Copy, Clone, PartialEq, Eq,PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1792 pub enum Unsafety {
1793 Unsafe,
1794 Normal,
1795 }
1796
1797 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1798 pub enum Constness {
1799 Const,
1800 NotConst,
1801 }
1802
1803 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1804 pub enum Defaultness {
1805 Default { has_value: bool },
1806 Final,
1807 }
1808
1809 impl Defaultness {
1810 pub fn has_value(&self) -> bool {
1811 match *self {
1812 Defaultness::Default { has_value, .. } => has_value,
1813 Defaultness::Final => true,
1814 }
1815 }
1816
1817 pub fn is_final(&self) -> bool {
1818 *self == Defaultness::Final
1819 }
1820
1821 pub fn is_default(&self) -> bool {
1822 match *self {
1823 Defaultness::Default { .. } => true,
1824 _ => false,
1825 }
1826 }
1827 }
1828
1829 impl fmt::Display for Unsafety {
1830 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1831 fmt::Display::fmt(match *self {
1832 Unsafety::Normal => "normal",
1833 Unsafety::Unsafe => "unsafe",
1834 },
1835 f)
1836 }
1837 }
1838
1839 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1840 pub enum ImplPolarity {
1841 /// `impl Trait for Type`
1842 Positive,
1843 /// `impl !Trait for Type`
1844 Negative,
1845 }
1846
1847 impl fmt::Debug for ImplPolarity {
1848 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1849 match *self {
1850 ImplPolarity::Positive => "positive".fmt(f),
1851 ImplPolarity::Negative => "negative".fmt(f),
1852 }
1853 }
1854 }
1855
1856
1857 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1858 pub enum FunctionRetTy {
1859 /// Return type is not specified.
1860 ///
1861 /// Functions default to `()` and
1862 /// closures default to inference. Span points to where return
1863 /// type would be inserted.
1864 DefaultReturn(Span),
1865 /// Everything else
1866 Return(P<Ty>),
1867 }
1868
1869 impl FunctionRetTy {
1870 pub fn span(&self) -> Span {
1871 match *self {
1872 DefaultReturn(span) => span,
1873 Return(ref ty) => ty.span,
1874 }
1875 }
1876 }
1877
1878 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1879 pub struct Mod {
1880 /// A span from the first token past `{` to the last token until `}`.
1881 /// For `mod foo;`, the inner span ranges from the first token
1882 /// to the last token in the external file.
1883 pub inner: Span,
1884 pub item_ids: HirVec<ItemId>,
1885 }
1886
1887 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1888 pub struct ForeignMod {
1889 pub abi: Abi,
1890 pub items: HirVec<ForeignItem>,
1891 }
1892
1893 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1894 pub struct GlobalAsm {
1895 pub asm: Symbol,
1896 pub ctxt: SyntaxContext,
1897 }
1898
1899 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1900 pub struct EnumDef {
1901 pub variants: HirVec<Variant>,
1902 }
1903
1904 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1905 pub struct Variant_ {
1906 pub name: Name,
1907 pub attrs: HirVec<Attribute>,
1908 pub data: VariantData,
1909 /// Explicit discriminant, eg `Foo = 1`
1910 pub disr_expr: Option<AnonConst>,
1911 }
1912
1913 pub type Variant = Spanned<Variant_>;
1914
1915 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1916 pub enum UseKind {
1917 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1918 /// Also produced for each element of a list `use`, e.g.
1919 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1920 Single,
1921
1922 /// Glob import, e.g. `use foo::*`.
1923 Glob,
1924
1925 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1926 /// an additional `use foo::{}` for performing checks such as
1927 /// unstable feature gating. May be removed in the future.
1928 ListStem,
1929 }
1930
1931 /// TraitRef's appear in impls.
1932 ///
1933 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1934 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1935 /// trait being referred to but just a unique NodeId that serves as a key
1936 /// within the DefMap.
1937 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1938 pub struct TraitRef {
1939 pub path: Path,
1940 pub ref_id: NodeId,
1941 }
1942
1943 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1944 pub struct PolyTraitRef {
1945 /// The `'a` in `<'a> Foo<&'a T>`
1946 pub bound_generic_params: HirVec<GenericParam>,
1947
1948 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1949 pub trait_ref: TraitRef,
1950
1951 pub span: Span,
1952 }
1953
1954 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1955 pub enum Visibility {
1956 Public,
1957 Crate(CrateSugar),
1958 Restricted { path: P<Path>, id: NodeId },
1959 Inherited,
1960 }
1961
1962 impl Visibility {
1963 pub fn is_pub_restricted(&self) -> bool {
1964 use self::Visibility::*;
1965 match self {
1966 &Public |
1967 &Inherited => false,
1968 &Crate(_) |
1969 &Restricted { .. } => true,
1970 }
1971 }
1972 }
1973
1974 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1975 pub struct StructField {
1976 pub span: Span,
1977 pub ident: Ident,
1978 pub vis: Visibility,
1979 pub id: NodeId,
1980 pub ty: P<Ty>,
1981 pub attrs: HirVec<Attribute>,
1982 }
1983
1984 impl StructField {
1985 // Still necessary in couple of places
1986 pub fn is_positional(&self) -> bool {
1987 let first = self.ident.as_str().as_bytes()[0];
1988 first >= b'0' && first <= b'9'
1989 }
1990 }
1991
1992 /// Fields and Ids of enum variants and structs
1993 ///
1994 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1995 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1996 /// One shared Id can be successfully used for these two purposes.
1997 /// Id of the whole enum lives in `Item`.
1998 ///
1999 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2000 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2001 /// the variant itself" from enum variants.
2002 /// Id of the whole struct lives in `Item`.
2003 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2004 pub enum VariantData {
2005 Struct(HirVec<StructField>, NodeId),
2006 Tuple(HirVec<StructField>, NodeId),
2007 Unit(NodeId),
2008 }
2009
2010 impl VariantData {
2011 pub fn fields(&self) -> &[StructField] {
2012 match *self {
2013 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2014 _ => &[],
2015 }
2016 }
2017 pub fn id(&self) -> NodeId {
2018 match *self {
2019 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2020 }
2021 }
2022 pub fn is_struct(&self) -> bool {
2023 if let VariantData::Struct(..) = *self {
2024 true
2025 } else {
2026 false
2027 }
2028 }
2029 pub fn is_tuple(&self) -> bool {
2030 if let VariantData::Tuple(..) = *self {
2031 true
2032 } else {
2033 false
2034 }
2035 }
2036 pub fn is_unit(&self) -> bool {
2037 if let VariantData::Unit(..) = *self {
2038 true
2039 } else {
2040 false
2041 }
2042 }
2043 }
2044
2045 // The bodies for items are stored "out of line", in a separate
2046 // hashmap in the `Crate`. Here we just record the node-id of the item
2047 // so it can fetched later.
2048 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2049 pub struct ItemId {
2050 pub id: NodeId,
2051 }
2052
2053 /// An item
2054 ///
2055 /// The name might be a dummy name in case of anonymous items
2056 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2057 pub struct Item {
2058 pub name: Name,
2059 pub id: NodeId,
2060 pub hir_id: HirId,
2061 pub attrs: HirVec<Attribute>,
2062 pub node: Item_,
2063 pub vis: Visibility,
2064 pub span: Span,
2065 }
2066
2067 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2068 pub enum Item_ {
2069 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2070 ///
2071 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2072 ItemExternCrate(Option<Name>),
2073
2074 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2075 ///
2076 /// or just
2077 ///
2078 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2079 ItemUse(P<Path>, UseKind),
2080
2081 /// A `static` item
2082 ItemStatic(P<Ty>, Mutability, BodyId),
2083 /// A `const` item
2084 ItemConst(P<Ty>, BodyId),
2085 /// A function declaration
2086 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, BodyId),
2087 /// A module
2088 ItemMod(Mod),
2089 /// An external module
2090 ItemForeignMod(ForeignMod),
2091 /// Module-level inline assembly (from global_asm!)
2092 ItemGlobalAsm(P<GlobalAsm>),
2093 /// A type alias, e.g. `type Foo = Bar<u8>`
2094 ItemTy(P<Ty>, Generics),
2095 /// A type alias, e.g. `type Foo = Bar<u8>`
2096 ItemExistential(ExistTy),
2097 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2098 ItemEnum(EnumDef, Generics),
2099 /// A struct definition, e.g. `struct Foo<A> {x: A}`
2100 ItemStruct(VariantData, Generics),
2101 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
2102 ItemUnion(VariantData, Generics),
2103 /// Represents a Trait Declaration
2104 ItemTrait(IsAuto, Unsafety, Generics, TyParamBounds, HirVec<TraitItemRef>),
2105 /// Represents a Trait Alias Declaration
2106 ItemTraitAlias(Generics, TyParamBounds),
2107
2108 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2109 ItemImpl(Unsafety,
2110 ImplPolarity,
2111 Defaultness,
2112 Generics,
2113 Option<TraitRef>, // (optional) trait this impl implements
2114 P<Ty>, // self
2115 HirVec<ImplItemRef>),
2116 }
2117
2118 impl Item_ {
2119 pub fn descriptive_variant(&self) -> &str {
2120 match *self {
2121 ItemExternCrate(..) => "extern crate",
2122 ItemUse(..) => "use",
2123 ItemStatic(..) => "static item",
2124 ItemConst(..) => "constant item",
2125 ItemFn(..) => "function",
2126 ItemMod(..) => "module",
2127 ItemForeignMod(..) => "foreign module",
2128 ItemGlobalAsm(..) => "global asm",
2129 ItemTy(..) => "type alias",
2130 ItemExistential(..) => "existential type",
2131 ItemEnum(..) => "enum",
2132 ItemStruct(..) => "struct",
2133 ItemUnion(..) => "union",
2134 ItemTrait(..) => "trait",
2135 ItemTraitAlias(..) => "trait alias",
2136 ItemImpl(..) => "item",
2137 }
2138 }
2139
2140 pub fn adt_kind(&self) -> Option<AdtKind> {
2141 match *self {
2142 ItemStruct(..) => Some(AdtKind::Struct),
2143 ItemUnion(..) => Some(AdtKind::Union),
2144 ItemEnum(..) => Some(AdtKind::Enum),
2145 _ => None,
2146 }
2147 }
2148
2149 pub fn generics(&self) -> Option<&Generics> {
2150 Some(match *self {
2151 ItemFn(_, _, _, _, ref generics, _) |
2152 ItemTy(_, ref generics) |
2153 ItemEnum(_, ref generics) |
2154 ItemStruct(_, ref generics) |
2155 ItemUnion(_, ref generics) |
2156 ItemTrait(_, _, ref generics, _, _) |
2157 ItemImpl(_, _, _, ref generics, _, _, _)=> generics,
2158 _ => return None
2159 })
2160 }
2161 }
2162
2163 /// A reference from an trait to one of its associated items. This
2164 /// contains the item's id, naturally, but also the item's name and
2165 /// some other high-level details (like whether it is an associated
2166 /// type or method, and whether it is public). This allows other
2167 /// passes to find the impl they want without loading the id (which
2168 /// means fewer edges in the incremental compilation graph).
2169 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2170 pub struct TraitItemRef {
2171 pub id: TraitItemId,
2172 pub name: Name,
2173 pub kind: AssociatedItemKind,
2174 pub span: Span,
2175 pub defaultness: Defaultness,
2176 }
2177
2178 /// A reference from an impl to one of its associated items. This
2179 /// contains the item's id, naturally, but also the item's name and
2180 /// some other high-level details (like whether it is an associated
2181 /// type or method, and whether it is public). This allows other
2182 /// passes to find the impl they want without loading the id (which
2183 /// means fewer edges in the incremental compilation graph).
2184 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2185 pub struct ImplItemRef {
2186 pub id: ImplItemId,
2187 pub name: Name,
2188 pub kind: AssociatedItemKind,
2189 pub span: Span,
2190 pub vis: Visibility,
2191 pub defaultness: Defaultness,
2192 }
2193
2194 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2195 pub enum AssociatedItemKind {
2196 Const,
2197 Method { has_self: bool },
2198 Type,
2199 }
2200
2201 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2202 pub struct ForeignItem {
2203 pub name: Name,
2204 pub attrs: HirVec<Attribute>,
2205 pub node: ForeignItem_,
2206 pub id: NodeId,
2207 pub span: Span,
2208 pub vis: Visibility,
2209 }
2210
2211 /// An item within an `extern` block
2212 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2213 pub enum ForeignItem_ {
2214 /// A foreign function
2215 ForeignItemFn(P<FnDecl>, HirVec<Spanned<Name>>, Generics),
2216 /// A foreign static item (`static ext: u8`), with optional mutability
2217 /// (the boolean is true when mutable)
2218 ForeignItemStatic(P<Ty>, bool),
2219 /// A foreign type
2220 ForeignItemType,
2221 }
2222
2223 impl ForeignItem_ {
2224 pub fn descriptive_variant(&self) -> &str {
2225 match *self {
2226 ForeignItemFn(..) => "foreign function",
2227 ForeignItemStatic(..) => "foreign static item",
2228 ForeignItemType => "foreign type",
2229 }
2230 }
2231 }
2232
2233 /// A free variable referred to in a function.
2234 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2235 pub struct Freevar {
2236 /// The variable being accessed free.
2237 pub def: Def,
2238
2239 // First span where it is accessed (there can be multiple).
2240 pub span: Span
2241 }
2242
2243 impl Freevar {
2244 pub fn var_id(&self) -> NodeId {
2245 match self.def {
2246 Def::Local(id) | Def::Upvar(id, ..) => id,
2247 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2248 }
2249 }
2250 }
2251
2252 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2253
2254 pub type CaptureModeMap = NodeMap<CaptureClause>;
2255
2256 #[derive(Clone, Debug)]
2257 pub struct TraitCandidate {
2258 pub def_id: DefId,
2259 pub import_id: Option<NodeId>,
2260 }
2261
2262 // Trait method resolution
2263 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2264
2265 // Map from the NodeId of a glob import to a list of items which are actually
2266 // imported.
2267 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2268
2269
2270 pub fn provide(providers: &mut Providers) {
2271 providers.describe_def = map::describe_def;
2272 }
2273
2274 #[derive(Clone, RustcEncodable, RustcDecodable, Hash)]
2275 pub struct CodegenFnAttrs {
2276 pub flags: CodegenFnAttrFlags,
2277 pub inline: InlineAttr,
2278 pub export_name: Option<Symbol>,
2279 pub target_features: Vec<Symbol>,
2280 pub linkage: Option<Linkage>,
2281 }
2282
2283 bitflags! {
2284 #[derive(RustcEncodable, RustcDecodable)]
2285 pub struct CodegenFnAttrFlags: u8 {
2286 const COLD = 0b0000_0001;
2287 const ALLOCATOR = 0b0000_0010;
2288 const UNWIND = 0b0000_0100;
2289 const RUSTC_ALLOCATOR_NOUNWIND = 0b0000_1000;
2290 const NAKED = 0b0001_0000;
2291 const NO_MANGLE = 0b0010_0000;
2292 const RUSTC_STD_INTERNAL_SYMBOL = 0b0100_0000;
2293 const NO_DEBUG = 0b1000_0000;
2294 }
2295 }
2296
2297 impl CodegenFnAttrs {
2298 pub fn new() -> CodegenFnAttrs {
2299 CodegenFnAttrs {
2300 flags: CodegenFnAttrFlags::empty(),
2301 inline: InlineAttr::None,
2302 export_name: None,
2303 target_features: vec![],
2304 linkage: None,
2305 }
2306 }
2307
2308 /// True if `#[inline]` or `#[inline(always)]` is present.
2309 pub fn requests_inline(&self) -> bool {
2310 match self.inline {
2311 InlineAttr::Hint | InlineAttr::Always => true,
2312 InlineAttr::None | InlineAttr::Never => false,
2313 }
2314 }
2315
2316 /// True if `#[no_mangle]` or `#[export_name(...)]` is present.
2317 pub fn contains_extern_indicator(&self) -> bool {
2318 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) || self.export_name.is_some()
2319 }
2320 }