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