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.
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.
11 // Lowers the AST to the HIR.
13 // Since the AST and HIR are fairly similar, this is mostly a simple procedure,
14 // much like a fold. Where lowering involves a bit more work things get more
15 // interesting and there are some invariants you should know about. These mostly
16 // concern spans and ids.
18 // Spans are assigned to AST nodes during parsing and then are modified during
19 // expansion to indicate the origin of a node and the process it went through
20 // being expanded. Ids are assigned to AST nodes just before lowering.
22 // For the simpler lowering steps, ids and spans should be preserved. Unlike
23 // expansion we do not preserve the process of lowering in the spans, so spans
24 // should not be modified here. When creating a new node (as opposed to
25 // 'folding' an existing one), then you create a new id using `next_id()`.
27 // You must ensure that ids are unique. That means that you should only use the
28 // id from an AST node in a single HIR node (you can assume that AST node ids
29 // are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
30 // If you do, you must then set the new node's id to a fresh one.
32 // Spans are used for error messages and for tools to map semantics back to
33 // source code. It is therefore not as important with spans as ids to be strict
34 // about use (you can't break the compiler by screwing up a span). Obviously, a
35 // HIR node can only have a single span. But multiple nodes can have the same
36 // span and spans don't need to be kept in order, etc. Where code is preserved
37 // by lowering, it should have the same span as in the AST. Where HIR nodes are
38 // new it is probably best to give a span for the whole AST node being lowered.
39 // All nodes should have real spans, don't use dummy spans. Tools are likely to
40 // get confused if the spans from leaf AST nodes occur in multiple places
41 // in the HIR, especially for multiple identifiers.
44 use hir::map::{Definitions, DefKey, REGULAR_SPACE};
45 use hir::map::definitions::DefPathData;
46 use hir::def_id::{DefIndex, DefId, CRATE_DEF_INDEX};
47 use hir::def::{Def, PathResolution};
48 use rustc_data_structures::indexed_vec::IndexVec;
50 use util::nodemap::{DefIdMap, NodeMap};
52 use std::collections::BTreeMap;
61 use syntax::codemap::{self, respan, Spanned};
62 use syntax::std_inject;
63 use syntax::symbol::{Symbol, keywords};
64 use syntax::util::small_vector::SmallVector;
65 use syntax::visit::{self, Visitor};
68 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
70 pub struct LoweringContext<'a> {
71 crate_root: Option<&'static str>,
72 // Use to assign ids to hir nodes that do not directly correspond to an ast node
74 // As we walk the AST we must keep track of the current 'parent' def id (in
75 // the form of a DefIndex) so that if we create a new node which introduces
76 // a definition, then we can properly create the def id.
77 parent_def: Option<DefIndex>,
78 resolver: &'a mut Resolver,
80 /// The items being lowered are collected here.
81 items: BTreeMap<NodeId, hir::Item>,
83 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
84 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
85 bodies: BTreeMap<hir::BodyId, hir::Body>,
86 exported_macros: Vec<hir::MacroDef>,
88 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
89 trait_default_impl: BTreeMap<DefId, NodeId>,
91 catch_scopes: Vec<NodeId>,
92 loop_scopes: Vec<NodeId>,
93 is_in_loop_condition: bool,
95 type_def_lifetime_params: DefIdMap<usize>,
97 current_hir_id_owner: Vec<(DefIndex, u32)>,
98 item_local_id_counters: NodeMap<u32>,
99 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
103 // Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
104 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
106 // Obtain the resolution for a node id
107 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
109 // We must keep the set of definitions up to date as we add nodes that weren't in the AST.
110 // This should only return `None` during testing.
111 fn definitions(&mut self) -> &mut Definitions;
114 pub fn lower_crate(sess: &Session,
116 resolver: &mut Resolver)
118 // We're constructing the HIR here; we don't care what we will
119 // read, since we haven't even constructed the *input* to
121 let _ignore = sess.dep_graph.in_ignore();
124 crate_root: std_inject::injected_crate_name(krate),
128 items: BTreeMap::new(),
129 trait_items: BTreeMap::new(),
130 impl_items: BTreeMap::new(),
131 bodies: BTreeMap::new(),
132 trait_impls: BTreeMap::new(),
133 trait_default_impl: BTreeMap::new(),
134 exported_macros: Vec::new(),
135 catch_scopes: Vec::new(),
136 loop_scopes: Vec::new(),
137 is_in_loop_condition: false,
138 type_def_lifetime_params: DefIdMap(),
139 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
140 item_local_id_counters: NodeMap(),
141 node_id_to_hir_id: IndexVec::new(),
145 #[derive(Copy, Clone, PartialEq, Eq)]
147 /// Any path in a type context.
149 /// The `module::Type` in `module::Type::method` in an expression.
153 impl<'a> LoweringContext<'a> {
154 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
155 /// Full-crate AST visitor that inserts into a fresh
156 /// `LoweringContext` any information that may be
157 /// needed from arbitrary locations in the crate.
158 /// E.g. The number of lifetime generic parameters
159 /// declared for every type and trait definition.
160 struct MiscCollector<'lcx, 'interner: 'lcx> {
161 lctx: &'lcx mut LoweringContext<'interner>,
164 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
165 fn visit_item(&mut self, item: &'lcx Item) {
166 self.lctx.allocate_hir_id_counter(item.id, item);
169 ItemKind::Struct(_, ref generics) |
170 ItemKind::Union(_, ref generics) |
171 ItemKind::Enum(_, ref generics) |
172 ItemKind::Ty(_, ref generics) |
173 ItemKind::Trait(_, ref generics, ..) => {
174 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
175 let count = generics.lifetimes.len();
176 self.lctx.type_def_lifetime_params.insert(def_id, count);
180 visit::walk_item(self, item);
183 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
184 self.lctx.allocate_hir_id_counter(item.id, item);
185 visit::walk_trait_item(self, item);
188 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
189 self.lctx.allocate_hir_id_counter(item.id, item);
190 visit::walk_impl_item(self, item);
194 struct ItemLowerer<'lcx, 'interner: 'lcx> {
195 lctx: &'lcx mut LoweringContext<'interner>,
198 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
199 fn visit_item(&mut self, item: &'lcx Item) {
200 let mut item_lowered = true;
201 self.lctx.with_hir_id_owner(item.id, |lctx| {
202 if let Some(hir_item) = lctx.lower_item(item) {
203 lctx.items.insert(item.id, hir_item);
205 item_lowered = false;
210 visit::walk_item(self, item);
214 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
215 self.lctx.with_hir_id_owner(item.id, |lctx| {
216 let id = hir::TraitItemId { node_id: item.id };
217 let hir_item = lctx.lower_trait_item(item);
218 lctx.trait_items.insert(id, hir_item);
221 visit::walk_trait_item(self, item);
224 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
225 self.lctx.with_hir_id_owner(item.id, |lctx| {
226 let id = hir::ImplItemId { node_id: item.id };
227 let hir_item = lctx.lower_impl_item(item);
228 lctx.impl_items.insert(id, hir_item);
230 visit::walk_impl_item(self, item);
234 self.lower_node_id(CRATE_NODE_ID);
235 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
237 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
238 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
240 let module = self.lower_mod(&c.module);
241 let attrs = self.lower_attrs(&c.attrs);
242 let body_ids = body_ids(&self.bodies);
246 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
252 exported_macros: hir::HirVec::from(self.exported_macros),
254 trait_items: self.trait_items,
255 impl_items: self.impl_items,
258 trait_impls: self.trait_impls,
259 trait_default_impl: self.trait_default_impl,
263 fn allocate_hir_id_counter<T: Debug>(&mut self,
266 if self.item_local_id_counters.insert(owner, 0).is_some() {
267 bug!("Tried to allocate item_local_id_counter for {:?} twice", debug);
269 // Always allocate the first HirId for the owner itself
270 self.lower_node_id_with_owner(owner, owner);
273 fn lower_node_id_generic<F>(&mut self,
277 where F: FnOnce(&mut Self) -> hir::HirId
279 if ast_node_id == DUMMY_NODE_ID {
283 let min_size = ast_node_id.as_usize() + 1;
285 if min_size > self.node_id_to_hir_id.len() {
286 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
289 if self.node_id_to_hir_id[ast_node_id] == hir::DUMMY_HIR_ID {
290 // Generate a new HirId
291 self.node_id_to_hir_id[ast_node_id] = alloc_hir_id(self);
297 fn with_hir_id_owner<F>(&mut self, owner: NodeId, f: F)
298 where F: FnOnce(&mut Self)
300 let counter = self.item_local_id_counters
301 .insert(owner, HIR_ID_COUNTER_LOCKED)
303 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
304 self.current_hir_id_owner.push((def_index, counter));
306 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
308 debug_assert!(def_index == new_def_index);
309 debug_assert!(new_counter >= counter);
311 let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
312 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
315 /// This method allocates a new HirId for the given NodeId and stores it in
316 /// the LoweringContext's NodeId => HirId map.
317 /// Take care not to call this method if the resulting HirId is then not
318 /// actually used in the HIR, as that would trigger an assertion in the
319 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
320 /// properly. Calling the method twice with the same NodeId is fine though.
321 fn lower_node_id(&mut self, ast_node_id: NodeId) -> NodeId {
322 self.lower_node_id_generic(ast_node_id, |this| {
323 let &mut (def_index, ref mut local_id_counter) = this.current_hir_id_owner
326 let local_id = *local_id_counter;
327 *local_id_counter += 1;
330 local_id: hir::ItemLocalId(local_id),
335 fn lower_node_id_with_owner(&mut self,
339 self.lower_node_id_generic(ast_node_id, |this| {
340 let local_id_counter = this.item_local_id_counters
343 let local_id = *local_id_counter;
345 // We want to be sure not to modify the counter in the map while it
346 // is also on the stack. Otherwise we'll get lost updates when writing
347 // back from the stack to the map.
348 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
350 *local_id_counter += 1;
351 let def_index = this.resolver.definitions().opt_def_index(owner).unwrap();
355 local_id: hir::ItemLocalId(local_id),
360 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>)
362 let body = hir::Body {
363 arguments: decl.map_or(hir_vec![], |decl| {
364 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
369 self.bodies.insert(id, body);
373 fn next_id(&mut self) -> NodeId {
374 self.lower_node_id(self.sess.next_node_id())
377 fn expect_full_def(&mut self, id: NodeId) -> Def {
378 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
379 if pr.unresolved_segments() != 0 {
380 bug!("path not fully resolved: {:?}", pr);
386 fn diagnostic(&self) -> &errors::Handler {
387 self.sess.diagnostic()
390 fn str_to_ident(&self, s: &'static str) -> Name {
394 fn allow_internal_unstable(&self, reason: &'static str, mut span: Span) -> Span {
395 span.expn_id = self.sess.codemap().record_expansion(codemap::ExpnInfo {
397 callee: codemap::NameAndSpan {
398 format: codemap::CompilerDesugaring(Symbol::intern(reason)),
400 allow_internal_unstable: true,
406 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
407 where F: FnOnce(&mut LoweringContext) -> T
409 let len = self.catch_scopes.len();
410 self.catch_scopes.push(catch_id);
412 let result = f(self);
413 assert_eq!(len + 1, self.catch_scopes.len(),
414 "catch scopes should be added and removed in stack order");
416 self.catch_scopes.pop().unwrap();
421 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
422 where F: FnOnce(&mut LoweringContext) -> T
424 // We're no longer in the base loop's condition; we're in another loop.
425 let was_in_loop_condition = self.is_in_loop_condition;
426 self.is_in_loop_condition = false;
428 let len = self.loop_scopes.len();
429 self.loop_scopes.push(loop_id);
431 let result = f(self);
432 assert_eq!(len + 1, self.loop_scopes.len(),
433 "Loop scopes should be added and removed in stack order");
435 self.loop_scopes.pop().unwrap();
437 self.is_in_loop_condition = was_in_loop_condition;
442 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
443 where F: FnOnce(&mut LoweringContext) -> T
445 let was_in_loop_condition = self.is_in_loop_condition;
446 self.is_in_loop_condition = true;
448 let result = f(self);
450 self.is_in_loop_condition = was_in_loop_condition;
455 fn with_new_scopes<T, F>(&mut self, f: F) -> T
456 where F: FnOnce(&mut LoweringContext) -> T
458 let was_in_loop_condition = self.is_in_loop_condition;
459 self.is_in_loop_condition = false;
461 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
462 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
463 let result = f(self);
464 self.catch_scopes = catch_scopes;
465 self.loop_scopes = loop_scopes;
467 self.is_in_loop_condition = was_in_loop_condition;
472 fn with_parent_def<T, F>(&mut self, parent_id: NodeId, f: F) -> T
473 where F: FnOnce(&mut LoweringContext) -> T
475 let old_def = self.parent_def;
477 let defs = self.resolver.definitions();
478 Some(defs.opt_def_index(parent_id).unwrap())
481 let result = f(self);
483 self.parent_def = old_def;
487 fn def_key(&mut self, id: DefId) -> DefKey {
489 self.resolver.definitions().def_key(id.index)
491 self.sess.cstore.def_key(id)
495 fn lower_opt_sp_ident(&mut self, o_id: Option<Spanned<Ident>>) -> Option<Spanned<Name>> {
496 o_id.map(|sp_ident| respan(sp_ident.span, sp_ident.node.name))
499 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Spanned<Ident>)>)
503 Some((id, label_ident)) => {
504 let target = if let Def::Label(loop_id) = self.expect_full_def(id) {
505 hir::LoopIdResult::Ok(self.lower_node_id(loop_id))
507 hir::LoopIdResult::Err(hir::LoopIdError::UnresolvedLabel)
510 ident: Some(label_ident),
511 target_id: hir::ScopeTarget::Loop(target),
515 let loop_id = self.loop_scopes
517 .map(|innermost_loop_id| *innermost_loop_id);
521 target_id: hir::ScopeTarget::Loop(
522 loop_id.map(|id| Ok(self.lower_node_id(id)))
523 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
530 fn lower_attrs(&mut self, attrs: &Vec<Attribute>) -> hir::HirVec<Attribute> {
534 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
536 attrs: self.lower_attrs(&arm.attrs),
537 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
538 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
539 body: P(self.lower_expr(&arm.body)),
543 fn lower_ty_binding(&mut self, b: &TypeBinding) -> hir::TypeBinding {
545 id: self.lower_node_id(b.id),
547 ty: self.lower_ty(&b.ty),
552 fn lower_ty(&mut self, t: &Ty) -> P<hir::Ty> {
553 let kind = match t.node {
554 TyKind::Infer => hir::TyInfer,
555 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty)),
556 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt)),
557 TyKind::Rptr(ref region, ref mt) => {
558 let span = Span { hi: t.span.lo, ..t.span };
559 let lifetime = match *region {
560 Some(ref lt) => self.lower_lifetime(lt),
561 None => self.elided_lifetime(span)
563 hir::TyRptr(lifetime, self.lower_mt(mt))
565 TyKind::BareFn(ref f) => {
566 hir::TyBareFn(P(hir::BareFnTy {
567 lifetimes: self.lower_lifetime_defs(&f.lifetimes),
568 unsafety: self.lower_unsafety(f.unsafety),
570 decl: self.lower_fn_decl(&f.decl),
573 TyKind::Never => hir::TyNever,
574 TyKind::Tup(ref tys) => {
575 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty)).collect())
577 TyKind::Paren(ref ty) => {
578 return self.lower_ty(ty);
580 TyKind::Path(ref qself, ref path) => {
581 let id = self.lower_node_id(t.id);
582 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit);
583 return self.ty_path(id, t.span, qpath);
585 TyKind::ImplicitSelf => {
586 hir::TyPath(hir::QPath::Resolved(None, P(hir::Path {
587 def: self.expect_full_def(t.id),
588 segments: hir_vec![hir::PathSegment {
589 name: keywords::SelfType.name(),
590 parameters: hir::PathParameters::none()
595 TyKind::Array(ref ty, ref length) => {
596 let length = self.lower_expr(length);
597 hir::TyArray(self.lower_ty(ty),
598 self.record_body(length, None))
600 TyKind::Typeof(ref expr) => {
601 let expr = self.lower_expr(expr);
602 hir::TyTypeof(self.record_body(expr, None))
604 TyKind::TraitObject(ref bounds) => {
605 let mut lifetime_bound = None;
606 let bounds = bounds.iter().filter_map(|bound| {
608 TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
609 Some(self.lower_poly_trait_ref(ty))
611 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
612 RegionTyParamBound(ref lifetime) => {
613 if lifetime_bound.is_none() {
614 lifetime_bound = Some(self.lower_lifetime(lifetime));
620 let lifetime_bound = lifetime_bound.unwrap_or_else(|| {
621 self.elided_lifetime(t.span)
623 hir::TyTraitObject(bounds, lifetime_bound)
625 TyKind::ImplTrait(ref bounds) => {
626 hir::TyImplTrait(self.lower_bounds(bounds))
628 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
632 id: self.lower_node_id(t.id),
638 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
641 items: fm.items.iter().map(|x| self.lower_foreign_item(x)).collect(),
645 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
647 node: hir::Variant_ {
648 name: v.node.name.name,
649 attrs: self.lower_attrs(&v.node.attrs),
650 data: self.lower_variant_data(&v.node.data),
651 disr_expr: v.node.disr_expr.as_ref().map(|e| {
652 let e = self.lower_expr(e);
653 self.record_body(e, None)
660 fn lower_qpath(&mut self,
662 qself: &Option<QSelf>,
664 param_mode: ParamMode)
666 let qself_position = qself.as_ref().map(|q| q.position);
667 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty));
669 let resolution = self.resolver.get_resolution(id)
670 .unwrap_or(PathResolution::new(Def::Err));
672 let proj_start = p.segments.len() - resolution.unresolved_segments();
673 let path = P(hir::Path {
674 def: resolution.base_def(),
675 segments: p.segments[..proj_start].iter().enumerate().map(|(i, segment)| {
676 let param_mode = match (qself_position, param_mode) {
677 (Some(j), ParamMode::Optional) if i < j => {
678 // This segment is part of the trait path in a
679 // qualified path - one of `a`, `b` or `Trait`
680 // in `<X as a::b::Trait>::T::U::method`.
686 // Figure out if this is a type/trait segment,
687 // which may need lifetime elision performed.
688 let parent_def_id = |this: &mut Self, def_id: DefId| {
691 index: this.def_key(def_id).parent.expect("missing parent")
694 let type_def_id = match resolution.base_def() {
695 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
696 Some(parent_def_id(self, def_id))
698 Def::Variant(def_id) if i + 1 == proj_start => {
699 Some(parent_def_id(self, def_id))
701 Def::Struct(def_id) |
704 Def::TyAlias(def_id) |
705 Def::Trait(def_id) if i + 1 == proj_start => Some(def_id),
709 let num_lifetimes = type_def_id.map_or(0, |def_id| {
710 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
713 assert!(!def_id.is_local());
714 let n = self.sess.cstore.item_generics_cloned(def_id).regions.len();
715 self.type_def_lifetime_params.insert(def_id, n);
718 self.lower_path_segment(p.span, segment, param_mode, num_lifetimes)
723 // Simple case, either no projections, or only fully-qualified.
724 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
725 if resolution.unresolved_segments() == 0 {
726 return hir::QPath::Resolved(qself, path);
729 // Create the innermost type that we're projecting from.
730 let mut ty = if path.segments.is_empty() {
731 // If the base path is empty that means there exists a
732 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
733 qself.expect("missing QSelf for <T>::...")
735 // Otherwise, the base path is an implicit `Self` type path,
736 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
737 // `<I as Iterator>::Item::default`.
738 let new_id = self.next_id();
739 self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
742 // Anything after the base path are associated "extensions",
743 // out of which all but the last one are associated types,
744 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
745 // * base path is `std::vec::Vec<T>`
746 // * "extensions" are `IntoIter`, `Item` and `clone`
748 // 1. `std::vec::Vec<T>` (created above)
749 // 2. `<std::vec::Vec<T>>::IntoIter`
750 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
751 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
752 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
753 let segment = P(self.lower_path_segment(p.span, segment, param_mode, 0));
754 let qpath = hir::QPath::TypeRelative(ty, segment);
756 // It's finished, return the extension of the right node type.
757 if i == p.segments.len() - 1 {
761 // Wrap the associated extension in another type node.
762 let new_id = self.next_id();
763 ty = self.ty_path(new_id, p.span, qpath);
766 // Should've returned in the for loop above.
767 span_bug!(p.span, "lower_qpath: no final extension segment in {}..{}",
768 proj_start, p.segments.len())
771 fn lower_path_extra(&mut self,
775 param_mode: ParamMode,
776 defaults_to_global: bool)
778 let mut segments = p.segments.iter();
779 if defaults_to_global && p.is_global() {
784 def: self.expect_full_def(id),
785 segments: segments.map(|segment| {
786 self.lower_path_segment(p.span, segment, param_mode, 0)
787 }).chain(name.map(|name| {
790 parameters: hir::PathParameters::none()
797 fn lower_path(&mut self,
800 param_mode: ParamMode,
801 defaults_to_global: bool)
803 self.lower_path_extra(id, p, None, param_mode, defaults_to_global)
806 fn lower_path_segment(&mut self,
808 segment: &PathSegment,
809 param_mode: ParamMode,
810 expected_lifetimes: usize)
811 -> hir::PathSegment {
812 let mut parameters = if let Some(ref parameters) = segment.parameters {
814 PathParameters::AngleBracketed(ref data) => {
815 let data = self.lower_angle_bracketed_parameter_data(data, param_mode);
816 hir::AngleBracketedParameters(data)
818 PathParameters::Parenthesized(ref data) => {
819 hir::ParenthesizedParameters(self.lower_parenthesized_parameter_data(data))
823 let data = self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode);
824 hir::AngleBracketedParameters(data)
827 if let hir::AngleBracketedParameters(ref mut data) = parameters {
828 if data.lifetimes.is_empty() {
829 data.lifetimes = (0..expected_lifetimes).map(|_| {
830 self.elided_lifetime(path_span)
836 name: segment.identifier.name,
837 parameters: parameters,
841 fn lower_angle_bracketed_parameter_data(&mut self,
842 data: &AngleBracketedParameterData,
843 param_mode: ParamMode)
844 -> hir::AngleBracketedParameterData {
845 let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
846 hir::AngleBracketedParameterData {
847 lifetimes: self.lower_lifetimes(lifetimes),
848 types: types.iter().map(|ty| self.lower_ty(ty)).collect(),
849 infer_types: types.is_empty() && param_mode == ParamMode::Optional,
850 bindings: bindings.iter().map(|b| self.lower_ty_binding(b)).collect(),
854 fn lower_parenthesized_parameter_data(&mut self,
855 data: &ParenthesizedParameterData)
856 -> hir::ParenthesizedParameterData {
857 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
858 hir::ParenthesizedParameterData {
859 inputs: inputs.iter().map(|ty| self.lower_ty(ty)).collect(),
860 output: output.as_ref().map(|ty| self.lower_ty(ty)),
865 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
867 id: self.lower_node_id(l.id),
868 ty: l.ty.as_ref().map(|t| self.lower_ty(t)),
869 pat: self.lower_pat(&l.pat),
870 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
872 attrs: l.attrs.clone(),
876 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
878 Mutability::Mutable => hir::MutMutable,
879 Mutability::Immutable => hir::MutImmutable,
883 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
885 id: self.lower_node_id(arg.id),
886 pat: self.lower_pat(&arg.pat),
890 fn lower_fn_args_to_names(&mut self, decl: &FnDecl)
891 -> hir::HirVec<Spanned<Name>> {
892 decl.inputs.iter().map(|arg| {
894 PatKind::Ident(_, ident, None) => {
895 respan(ident.span, ident.node.name)
897 _ => respan(arg.pat.span, keywords::Invalid.name()),
902 fn lower_fn_decl(&mut self, decl: &FnDecl) -> P<hir::FnDecl> {
904 inputs: decl.inputs.iter().map(|arg| self.lower_ty(&arg.ty)).collect(),
905 output: match decl.output {
906 FunctionRetTy::Ty(ref ty) => hir::Return(self.lower_ty(ty)),
907 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
909 variadic: decl.variadic,
910 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| {
912 TyKind::ImplicitSelf => true,
913 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
920 fn lower_ty_param_bound(&mut self, tpb: &TyParamBound) -> hir::TyParamBound {
922 TraitTyParamBound(ref ty, modifier) => {
923 hir::TraitTyParamBound(self.lower_poly_trait_ref(ty),
924 self.lower_trait_bound_modifier(modifier))
926 RegionTyParamBound(ref lifetime) => {
927 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
932 fn lower_ty_param(&mut self, tp: &TyParam, add_bounds: &[TyParamBound]) -> hir::TyParam {
933 let mut name = tp.ident.name;
935 // Don't expose `Self` (recovered "keyword used as ident" parse error).
936 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
937 // Instead, use gensym("Self") to create a distinct name that looks the same.
938 if name == keywords::SelfType.name() {
939 name = Symbol::gensym("Self");
942 let mut bounds = self.lower_bounds(&tp.bounds);
943 if !add_bounds.is_empty() {
944 bounds = bounds.into_iter().chain(self.lower_bounds(add_bounds).into_iter()).collect();
948 id: self.lower_node_id(tp.id),
951 default: tp.default.as_ref().map(|x| self.lower_ty(x)),
953 pure_wrt_drop: tp.attrs.iter().any(|attr| attr.check_name("may_dangle")),
957 fn lower_ty_params(&mut self, tps: &Vec<TyParam>, add_bounds: &NodeMap<Vec<TyParamBound>>)
958 -> hir::HirVec<hir::TyParam> {
959 tps.iter().map(|tp| {
960 self.lower_ty_param(tp, add_bounds.get(&tp.id).map_or(&[][..], |x| &x))
964 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
966 id: self.lower_node_id(l.id),
972 fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef {
974 lifetime: self.lower_lifetime(&l.lifetime),
975 bounds: self.lower_lifetimes(&l.bounds),
976 pure_wrt_drop: l.attrs.iter().any(|attr| attr.check_name("may_dangle")),
980 fn lower_lifetimes(&mut self, lts: &Vec<Lifetime>) -> hir::HirVec<hir::Lifetime> {
981 lts.iter().map(|l| self.lower_lifetime(l)).collect()
984 fn lower_lifetime_defs(&mut self, lts: &Vec<LifetimeDef>) -> hir::HirVec<hir::LifetimeDef> {
985 lts.iter().map(|l| self.lower_lifetime_def(l)).collect()
988 fn lower_generics(&mut self, g: &Generics) -> hir::Generics {
989 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
990 let mut add_bounds = NodeMap();
991 for pred in &g.where_clause.predicates {
992 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
993 'next_bound: for bound in &bound_pred.bounds {
994 if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
995 let report_error = |this: &mut Self| {
996 this.diagnostic().span_err(bound_pred.bounded_ty.span,
997 "`?Trait` bounds are only permitted at the \
998 point where a type parameter is declared");
1000 // Check if the where clause type is a plain type parameter.
1001 match bound_pred.bounded_ty.node {
1002 TyKind::Path(None, ref path)
1003 if path.segments.len() == 1 &&
1004 bound_pred.bound_lifetimes.is_empty() => {
1005 if let Some(Def::TyParam(def_id)) =
1006 self.resolver.get_resolution(bound_pred.bounded_ty.id)
1007 .map(|d| d.base_def()) {
1008 if let Some(node_id) =
1009 self.resolver.definitions().as_local_node_id(def_id) {
1010 for ty_param in &g.ty_params {
1011 if node_id == ty_param.id {
1012 add_bounds.entry(ty_param.id).or_insert(Vec::new())
1013 .push(bound.clone());
1014 continue 'next_bound;
1021 _ => report_error(self)
1029 ty_params: self.lower_ty_params(&g.ty_params, &add_bounds),
1030 lifetimes: self.lower_lifetime_defs(&g.lifetimes),
1031 where_clause: self.lower_where_clause(&g.where_clause),
1036 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
1038 id: self.lower_node_id(wc.id),
1039 predicates: wc.predicates
1041 .map(|predicate| self.lower_where_predicate(predicate))
1046 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
1048 WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
1052 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1053 bound_lifetimes: self.lower_lifetime_defs(bound_lifetimes),
1054 bounded_ty: self.lower_ty(bounded_ty),
1055 bounds: bounds.iter().filter_map(|bound| match *bound {
1056 // Ignore `?Trait` bounds, they were copied into type parameters already.
1057 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1058 _ => Some(self.lower_ty_param_bound(bound))
1063 WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
1066 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1068 lifetime: self.lower_lifetime(lifetime),
1069 bounds: bounds.iter().map(|bound| self.lower_lifetime(bound)).collect(),
1072 WherePredicate::EqPredicate(WhereEqPredicate{ id,
1076 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1077 id: self.lower_node_id(id),
1078 lhs_ty: self.lower_ty(lhs_ty),
1079 rhs_ty: self.lower_ty(rhs_ty),
1086 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
1088 VariantData::Struct(ref fields, id) => {
1089 hir::VariantData::Struct(fields.iter()
1091 .map(|f| self.lower_struct_field(f))
1093 self.lower_node_id(id))
1095 VariantData::Tuple(ref fields, id) => {
1096 hir::VariantData::Tuple(fields.iter()
1098 .map(|f| self.lower_struct_field(f))
1100 self.lower_node_id(id))
1102 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id)),
1106 fn lower_trait_ref(&mut self, p: &TraitRef) -> hir::TraitRef {
1107 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit) {
1108 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
1109 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath)
1113 ref_id: self.lower_node_id(p.ref_id),
1117 fn lower_poly_trait_ref(&mut self, p: &PolyTraitRef) -> hir::PolyTraitRef {
1119 bound_lifetimes: self.lower_lifetime_defs(&p.bound_lifetimes),
1120 trait_ref: self.lower_trait_ref(&p.trait_ref),
1125 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
1128 id: self.lower_node_id(f.id),
1129 name: f.ident.map(|ident| ident.name).unwrap_or(Symbol::intern(&index.to_string())),
1130 vis: self.lower_visibility(&f.vis, None),
1131 ty: self.lower_ty(&f.ty),
1132 attrs: self.lower_attrs(&f.attrs),
1136 fn lower_field(&mut self, f: &Field) -> hir::Field {
1138 name: respan(f.ident.span, f.ident.node.name),
1139 expr: P(self.lower_expr(&f.expr)),
1141 is_shorthand: f.is_shorthand,
1145 fn lower_mt(&mut self, mt: &MutTy) -> hir::MutTy {
1147 ty: self.lower_ty(&mt.ty),
1148 mutbl: self.lower_mutability(mt.mutbl),
1152 fn lower_bounds(&mut self, bounds: &[TyParamBound]) -> hir::TyParamBounds {
1153 bounds.iter().map(|bound| self.lower_ty_param_bound(bound)).collect()
1156 fn lower_block(&mut self, b: &Block, break_to: Option<NodeId>) -> P<hir::Block> {
1157 let mut expr = None;
1159 let mut stmts = vec![];
1161 for (index, stmt) in b.stmts.iter().enumerate() {
1162 if index == b.stmts.len() - 1 {
1163 if let StmtKind::Expr(ref e) = stmt.node {
1164 expr = Some(P(self.lower_expr(e)));
1166 stmts.extend(self.lower_stmt(stmt));
1169 stmts.extend(self.lower_stmt(stmt));
1174 id: self.lower_node_id(b.id),
1175 stmts: stmts.into(),
1177 rules: self.lower_block_check_mode(&b.rules),
1179 break_to_expr_id: break_to,
1183 fn lower_item_kind(&mut self,
1186 attrs: &hir::HirVec<Attribute>,
1187 vis: &mut hir::Visibility,
1191 ItemKind::ExternCrate(string) => hir::ItemExternCrate(string),
1192 ItemKind::Use(ref view_path) => {
1193 let path = match view_path.node {
1194 ViewPathSimple(_, ref path) => path,
1195 ViewPathGlob(ref path) => path,
1196 ViewPathList(ref path, ref path_list_idents) => {
1197 for &Spanned { node: ref import, span } in path_list_idents {
1198 // `use a::{self as x, b as y};` lowers to
1199 // `use a as x; use a::b as y;`
1200 let mut ident = import.name;
1201 let suffix = if ident.name == keywords::SelfValue.name() {
1202 if let Some(last) = path.segments.last() {
1203 ident = last.identifier;
1210 let mut path = self.lower_path_extra(import.id, path, suffix,
1211 ParamMode::Explicit, true);
1214 self.allocate_hir_id_counter(import.id, import);
1215 self.with_hir_id_owner(import.id, |this| {
1216 let vis = match *vis {
1217 hir::Visibility::Public => hir::Visibility::Public,
1218 hir::Visibility::Crate => hir::Visibility::Crate,
1219 hir::Visibility::Inherited => hir::Visibility::Inherited,
1220 hir::Visibility::Restricted { ref path, id: _ } => {
1221 hir::Visibility::Restricted {
1223 // We are allocating a new NodeId here
1229 this.items.insert(import.id, hir::Item {
1231 name: import.rename.unwrap_or(ident).name,
1232 attrs: attrs.clone(),
1233 node: hir::ItemUse(P(path), hir::UseKind::Single),
1242 let path = P(self.lower_path(id, path, ParamMode::Explicit, true));
1243 let kind = match view_path.node {
1244 ViewPathSimple(ident, _) => {
1246 hir::UseKind::Single
1248 ViewPathGlob(_) => {
1251 ViewPathList(..) => {
1252 // Privatize the degenerate import base, used only to check
1253 // the stability of `use a::{};`, to avoid it showing up as
1254 // a reexport by accident when `pub`, e.g. in documentation.
1255 *vis = hir::Inherited;
1256 hir::UseKind::ListStem
1259 hir::ItemUse(path, kind)
1261 ItemKind::Static(ref t, m, ref e) => {
1262 let value = self.lower_expr(e);
1263 hir::ItemStatic(self.lower_ty(t),
1264 self.lower_mutability(m),
1265 self.record_body(value, None))
1267 ItemKind::Const(ref t, ref e) => {
1268 let value = self.lower_expr(e);
1269 hir::ItemConst(self.lower_ty(t),
1270 self.record_body(value, None))
1272 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
1273 self.with_new_scopes(|this| {
1274 let body = this.lower_block(body, None);
1275 let body = this.expr_block(body, ThinVec::new());
1276 let body_id = this.record_body(body, Some(decl));
1277 hir::ItemFn(this.lower_fn_decl(decl),
1278 this.lower_unsafety(unsafety),
1279 this.lower_constness(constness),
1281 this.lower_generics(generics),
1285 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
1286 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
1287 ItemKind::Ty(ref t, ref generics) => {
1288 hir::ItemTy(self.lower_ty(t), self.lower_generics(generics))
1290 ItemKind::Enum(ref enum_definition, ref generics) => {
1291 hir::ItemEnum(hir::EnumDef {
1292 variants: enum_definition.variants
1294 .map(|x| self.lower_variant(x))
1297 self.lower_generics(generics))
1299 ItemKind::Struct(ref struct_def, ref generics) => {
1300 let struct_def = self.lower_variant_data(struct_def);
1301 hir::ItemStruct(struct_def, self.lower_generics(generics))
1303 ItemKind::Union(ref vdata, ref generics) => {
1304 let vdata = self.lower_variant_data(vdata);
1305 hir::ItemUnion(vdata, self.lower_generics(generics))
1307 ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1308 let trait_ref = self.lower_trait_ref(trait_ref);
1310 if let Def::Trait(def_id) = trait_ref.path.def {
1311 self.trait_default_impl.insert(def_id, id);
1314 hir::ItemDefaultImpl(self.lower_unsafety(unsafety),
1317 ItemKind::Impl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
1318 let new_impl_items = impl_items.iter()
1319 .map(|item| self.lower_impl_item_ref(item))
1321 let ifce = ifce.as_ref().map(|trait_ref| self.lower_trait_ref(trait_ref));
1323 if let Some(ref trait_ref) = ifce {
1324 if let Def::Trait(def_id) = trait_ref.path.def {
1325 self.trait_impls.entry(def_id).or_insert(vec![]).push(id);
1329 hir::ItemImpl(self.lower_unsafety(unsafety),
1330 self.lower_impl_polarity(polarity),
1331 self.lower_generics(generics),
1336 ItemKind::Trait(unsafety, ref generics, ref bounds, ref items) => {
1337 let bounds = self.lower_bounds(bounds);
1338 let items = items.iter().map(|item| self.lower_trait_item_ref(item)).collect();
1339 hir::ItemTrait(self.lower_unsafety(unsafety),
1340 self.lower_generics(generics),
1344 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
1348 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
1349 self.with_parent_def(i.id, |this| {
1351 id: this.lower_node_id(i.id),
1353 attrs: this.lower_attrs(&i.attrs),
1354 node: match i.node {
1355 TraitItemKind::Const(ref ty, ref default) => {
1356 hir::TraitItemKind::Const(this.lower_ty(ty),
1357 default.as_ref().map(|x| {
1358 let value = this.lower_expr(x);
1359 this.record_body(value, None)
1362 TraitItemKind::Method(ref sig, None) => {
1363 let names = this.lower_fn_args_to_names(&sig.decl);
1364 hir::TraitItemKind::Method(this.lower_method_sig(sig),
1365 hir::TraitMethod::Required(names))
1367 TraitItemKind::Method(ref sig, Some(ref body)) => {
1368 let body = this.lower_block(body, None);
1369 let expr = this.expr_block(body, ThinVec::new());
1370 let body_id = this.record_body(expr, Some(&sig.decl));
1371 hir::TraitItemKind::Method(this.lower_method_sig(sig),
1372 hir::TraitMethod::Provided(body_id))
1374 TraitItemKind::Type(ref bounds, ref default) => {
1375 hir::TraitItemKind::Type(this.lower_bounds(bounds),
1376 default.as_ref().map(|x| this.lower_ty(x)))
1378 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
1385 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
1386 let (kind, has_default) = match i.node {
1387 TraitItemKind::Const(_, ref default) => {
1388 (hir::AssociatedItemKind::Const, default.is_some())
1390 TraitItemKind::Type(_, ref default) => {
1391 (hir::AssociatedItemKind::Type, default.is_some())
1393 TraitItemKind::Method(ref sig, ref default) => {
1394 (hir::AssociatedItemKind::Method {
1395 has_self: sig.decl.has_self(),
1396 }, default.is_some())
1398 TraitItemKind::Macro(..) => unimplemented!(),
1401 id: hir::TraitItemId { node_id: i.id },
1404 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
1409 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
1410 self.with_parent_def(i.id, |this| {
1412 id: this.lower_node_id(i.id),
1414 attrs: this.lower_attrs(&i.attrs),
1415 vis: this.lower_visibility(&i.vis, None),
1416 defaultness: this.lower_defaultness(i.defaultness, true /* [1] */),
1417 node: match i.node {
1418 ImplItemKind::Const(ref ty, ref expr) => {
1419 let value = this.lower_expr(expr);
1420 let body_id = this.record_body(value, None);
1421 hir::ImplItemKind::Const(this.lower_ty(ty), body_id)
1423 ImplItemKind::Method(ref sig, ref body) => {
1424 let body = this.lower_block(body, None);
1425 let expr = this.expr_block(body, ThinVec::new());
1426 let body_id = this.record_body(expr, Some(&sig.decl));
1427 hir::ImplItemKind::Method(this.lower_method_sig(sig), body_id)
1429 ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(this.lower_ty(ty)),
1430 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
1436 // [1] since `default impl` is not yet implemented, this is always true in impls
1439 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
1441 id: hir::ImplItemId { node_id: i.id },
1444 vis: self.lower_visibility(&i.vis, Some(i.id)),
1445 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
1446 kind: match i.node {
1447 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
1448 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
1449 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
1450 has_self: sig.decl.has_self(),
1452 ImplItemKind::Macro(..) => unimplemented!(),
1456 // [1] since `default impl` is not yet implemented, this is always true in impls
1459 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
1462 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
1466 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
1468 ItemKind::Use(ref view_path) => {
1469 if let ViewPathList(_, ref imports) = view_path.node {
1470 return iter::once(i.id).chain(imports.iter().map(|import| import.node.id))
1471 .map(|id| hir::ItemId { id: id }).collect();
1474 ItemKind::MacroDef(..) => return SmallVector::new(),
1477 SmallVector::one(hir::ItemId { id: i.id })
1480 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
1481 let mut name = i.ident.name;
1482 let attrs = self.lower_attrs(&i.attrs);
1483 if let ItemKind::MacroDef(ref tts) = i.node {
1484 if i.attrs.iter().any(|attr| attr.path == "macro_export") {
1485 self.exported_macros.push(hir::MacroDef {
1486 name: name, attrs: attrs, id: i.id, span: i.span, body: tts.clone().into(),
1492 let mut vis = self.lower_visibility(&i.vis, None);
1493 let node = self.with_parent_def(i.id, |this| {
1494 this.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node)
1498 id: self.lower_node_id(i.id),
1507 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
1508 self.with_parent_def(i.id, |this| {
1510 id: this.lower_node_id(i.id),
1512 attrs: this.lower_attrs(&i.attrs),
1513 node: match i.node {
1514 ForeignItemKind::Fn(ref fdec, ref generics) => {
1515 hir::ForeignItemFn(this.lower_fn_decl(fdec),
1516 this.lower_fn_args_to_names(fdec),
1517 this.lower_generics(generics))
1519 ForeignItemKind::Static(ref t, m) => {
1520 hir::ForeignItemStatic(this.lower_ty(t), m)
1523 vis: this.lower_visibility(&i.vis, None),
1529 fn lower_method_sig(&mut self, sig: &MethodSig) -> hir::MethodSig {
1531 generics: self.lower_generics(&sig.generics),
1533 unsafety: self.lower_unsafety(sig.unsafety),
1534 constness: self.lower_constness(sig.constness),
1535 decl: self.lower_fn_decl(&sig.decl),
1539 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
1541 Unsafety::Unsafe => hir::Unsafety::Unsafe,
1542 Unsafety::Normal => hir::Unsafety::Normal,
1546 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
1548 Constness::Const => hir::Constness::Const,
1549 Constness::NotConst => hir::Constness::NotConst,
1553 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
1555 UnOp::Deref => hir::UnDeref,
1556 UnOp::Not => hir::UnNot,
1557 UnOp::Neg => hir::UnNeg,
1561 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
1563 node: match b.node {
1564 BinOpKind::Add => hir::BiAdd,
1565 BinOpKind::Sub => hir::BiSub,
1566 BinOpKind::Mul => hir::BiMul,
1567 BinOpKind::Div => hir::BiDiv,
1568 BinOpKind::Rem => hir::BiRem,
1569 BinOpKind::And => hir::BiAnd,
1570 BinOpKind::Or => hir::BiOr,
1571 BinOpKind::BitXor => hir::BiBitXor,
1572 BinOpKind::BitAnd => hir::BiBitAnd,
1573 BinOpKind::BitOr => hir::BiBitOr,
1574 BinOpKind::Shl => hir::BiShl,
1575 BinOpKind::Shr => hir::BiShr,
1576 BinOpKind::Eq => hir::BiEq,
1577 BinOpKind::Lt => hir::BiLt,
1578 BinOpKind::Le => hir::BiLe,
1579 BinOpKind::Ne => hir::BiNe,
1580 BinOpKind::Ge => hir::BiGe,
1581 BinOpKind::Gt => hir::BiGt,
1587 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
1589 id: self.lower_node_id(p.id),
1590 node: match p.node {
1591 PatKind::Wild => hir::PatKind::Wild,
1592 PatKind::Ident(ref binding_mode, pth1, ref sub) => {
1593 self.with_parent_def(p.id, |this| {
1594 match this.resolver.get_resolution(p.id).map(|d| d.base_def()) {
1595 // `None` can occur in body-less function signatures
1596 def @ None | def @ Some(Def::Local(_)) => {
1597 let def_id = def.map(|d| d.def_id()).unwrap_or_else(|| {
1598 this.resolver.definitions().local_def_id(p.id)
1600 hir::PatKind::Binding(this.lower_binding_mode(binding_mode),
1602 respan(pth1.span, pth1.node.name),
1603 sub.as_ref().map(|x| this.lower_pat(x)))
1606 hir::PatKind::Path(hir::QPath::Resolved(None, P(hir::Path {
1610 hir::PathSegment::from_name(pth1.node.name)
1617 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
1618 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
1619 let qpath = self.lower_qpath(p.id, &None, path, ParamMode::Optional);
1620 hir::PatKind::TupleStruct(qpath,
1621 pats.iter().map(|x| self.lower_pat(x)).collect(),
1624 PatKind::Path(ref qself, ref path) => {
1625 hir::PatKind::Path(self.lower_qpath(p.id, qself, path, ParamMode::Optional))
1627 PatKind::Struct(ref path, ref fields, etc) => {
1628 let qpath = self.lower_qpath(p.id, &None, path, ParamMode::Optional);
1630 let fs = fields.iter()
1634 node: hir::FieldPat {
1635 name: f.node.ident.name,
1636 pat: self.lower_pat(&f.node.pat),
1637 is_shorthand: f.node.is_shorthand,
1642 hir::PatKind::Struct(qpath, fs, etc)
1644 PatKind::Tuple(ref elts, ddpos) => {
1645 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
1647 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
1648 PatKind::Ref(ref inner, mutbl) => {
1649 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
1651 PatKind::Range(ref e1, ref e2, ref end) => {
1652 hir::PatKind::Range(P(self.lower_expr(e1)),
1653 P(self.lower_expr(e2)),
1654 self.lower_range_end(end))
1656 PatKind::Slice(ref before, ref slice, ref after) => {
1657 hir::PatKind::Slice(before.iter().map(|x| self.lower_pat(x)).collect(),
1658 slice.as_ref().map(|x| self.lower_pat(x)),
1659 after.iter().map(|x| self.lower_pat(x)).collect())
1661 PatKind::Mac(_) => panic!("Shouldn't exist here"),
1667 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
1669 RangeEnd::Included => hir::RangeEnd::Included,
1670 RangeEnd::Excluded => hir::RangeEnd::Excluded,
1674 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
1675 let kind = match e.node {
1677 // Eventually a desugaring for `box EXPR`
1678 // (similar to the desugaring above for `in PLACE BLOCK`)
1679 // should go here, desugaring
1683 // let mut place = BoxPlace::make_place();
1684 // let raw_place = Place::pointer(&mut place);
1685 // let value = $value;
1687 // ::std::ptr::write(raw_place, value);
1688 // Boxed::finalize(place)
1691 // But for now there are type-inference issues doing that.
1692 ExprKind::Box(ref inner) => {
1693 hir::ExprBox(P(self.lower_expr(inner)))
1696 // Desugar ExprBox: `in (PLACE) EXPR`
1697 ExprKind::InPlace(ref placer, ref value_expr) => {
1701 // let mut place = Placer::make_place(p);
1702 // let raw_place = Place::pointer(&mut place);
1704 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1705 // InPlace::finalize(place)
1707 let placer_expr = P(self.lower_expr(placer));
1708 let value_expr = P(self.lower_expr(value_expr));
1710 let placer_ident = self.str_to_ident("placer");
1711 let place_ident = self.str_to_ident("place");
1712 let p_ptr_ident = self.str_to_ident("p_ptr");
1714 let make_place = ["ops", "Placer", "make_place"];
1715 let place_pointer = ["ops", "Place", "pointer"];
1716 let move_val_init = ["intrinsics", "move_val_init"];
1717 let inplace_finalize = ["ops", "InPlace", "finalize"];
1719 let unstable_span = self.allow_internal_unstable("<-", e.span);
1720 let make_call = |this: &mut LoweringContext, p, args| {
1721 let path = P(this.expr_std_path(unstable_span, p, ThinVec::new()));
1722 P(this.expr_call(e.span, path, args))
1725 let mk_stmt_let = |this: &mut LoweringContext, bind, expr| {
1726 this.stmt_let(e.span, false, bind, expr)
1729 let mk_stmt_let_mut = |this: &mut LoweringContext, bind, expr| {
1730 this.stmt_let(e.span, true, bind, expr)
1733 // let placer = <placer_expr> ;
1734 let (s1, placer_binding) = {
1735 mk_stmt_let(self, placer_ident, placer_expr)
1738 // let mut place = Placer::make_place(placer);
1739 let (s2, place_binding) = {
1740 let placer = self.expr_ident(e.span, placer_ident, placer_binding);
1741 let call = make_call(self, &make_place, hir_vec![placer]);
1742 mk_stmt_let_mut(self, place_ident, call)
1745 // let p_ptr = Place::pointer(&mut place);
1746 let (s3, p_ptr_binding) = {
1747 let agent = P(self.expr_ident(e.span, place_ident, place_binding));
1748 let args = hir_vec![self.expr_mut_addr_of(e.span, agent)];
1749 let call = make_call(self, &place_pointer, args);
1750 mk_stmt_let(self, p_ptr_ident, call)
1753 // pop_unsafe!(EXPR));
1754 let pop_unsafe_expr = {
1755 self.signal_block_expr(hir_vec![],
1758 hir::PopUnsafeBlock(hir::CompilerGenerated),
1763 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1764 // InPlace::finalize(place)
1767 let ptr = self.expr_ident(e.span, p_ptr_ident, p_ptr_binding);
1768 let call_move_val_init =
1770 make_call(self, &move_val_init, hir_vec![ptr, pop_unsafe_expr]),
1772 let call_move_val_init = respan(e.span, call_move_val_init);
1774 let place = self.expr_ident(e.span, place_ident, place_binding);
1775 let call = make_call(self, &inplace_finalize, hir_vec![place]);
1776 P(self.signal_block_expr(hir_vec![call_move_val_init],
1779 hir::PushUnsafeBlock(hir::CompilerGenerated),
1783 let block = self.block_all(e.span, hir_vec![s1, s2, s3], Some(expr));
1784 hir::ExprBlock(P(block))
1787 ExprKind::Array(ref exprs) => {
1788 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
1790 ExprKind::Repeat(ref expr, ref count) => {
1791 let expr = P(self.lower_expr(expr));
1792 let count = self.lower_expr(count);
1793 hir::ExprRepeat(expr, self.record_body(count, None))
1795 ExprKind::Tup(ref elts) => {
1796 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
1798 ExprKind::Call(ref f, ref args) => {
1799 let f = P(self.lower_expr(f));
1800 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
1802 ExprKind::MethodCall(i, ref tps, ref args) => {
1803 let tps = tps.iter().map(|x| self.lower_ty(x)).collect();
1804 let args = args.iter().map(|x| self.lower_expr(x)).collect();
1805 hir::ExprMethodCall(respan(i.span, i.node.name), tps, args)
1807 ExprKind::Binary(binop, ref lhs, ref rhs) => {
1808 let binop = self.lower_binop(binop);
1809 let lhs = P(self.lower_expr(lhs));
1810 let rhs = P(self.lower_expr(rhs));
1811 hir::ExprBinary(binop, lhs, rhs)
1813 ExprKind::Unary(op, ref ohs) => {
1814 let op = self.lower_unop(op);
1815 let ohs = P(self.lower_expr(ohs));
1816 hir::ExprUnary(op, ohs)
1818 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
1819 ExprKind::Cast(ref expr, ref ty) => {
1820 let expr = P(self.lower_expr(expr));
1821 hir::ExprCast(expr, self.lower_ty(ty))
1823 ExprKind::Type(ref expr, ref ty) => {
1824 let expr = P(self.lower_expr(expr));
1825 hir::ExprType(expr, self.lower_ty(ty))
1827 ExprKind::AddrOf(m, ref ohs) => {
1828 let m = self.lower_mutability(m);
1829 let ohs = P(self.lower_expr(ohs));
1830 hir::ExprAddrOf(m, ohs)
1832 // More complicated than you might expect because the else branch
1833 // might be `if let`.
1834 ExprKind::If(ref cond, ref blk, ref else_opt) => {
1835 let else_opt = else_opt.as_ref().map(|els| {
1837 ExprKind::IfLet(..) => {
1838 // wrap the if-let expr in a block
1839 let span = els.span;
1840 let els = P(self.lower_expr(els));
1841 let id = self.next_id();
1842 let blk = P(hir::Block {
1846 rules: hir::DefaultBlock,
1848 break_to_expr_id: None,
1850 P(self.expr_block(blk, ThinVec::new()))
1852 _ => P(self.lower_expr(els)),
1856 hir::ExprIf(P(self.lower_expr(cond)), self.lower_block(blk, None), else_opt)
1858 ExprKind::While(ref cond, ref body, opt_ident) => {
1859 self.with_loop_scope(e.id, |this|
1861 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
1862 this.lower_block(body, None),
1863 this.lower_opt_sp_ident(opt_ident)))
1865 ExprKind::Loop(ref body, opt_ident) => {
1866 self.with_loop_scope(e.id, |this|
1867 hir::ExprLoop(this.lower_block(body, None),
1868 this.lower_opt_sp_ident(opt_ident),
1869 hir::LoopSource::Loop))
1871 ExprKind::Catch(ref body) => {
1872 self.with_catch_scope(e.id, |this|
1873 hir::ExprBlock(this.lower_block(body, Some(e.id))))
1875 ExprKind::Match(ref expr, ref arms) => {
1876 hir::ExprMatch(P(self.lower_expr(expr)),
1877 arms.iter().map(|x| self.lower_arm(x)).collect(),
1878 hir::MatchSource::Normal)
1880 ExprKind::Closure(capture_clause, ref decl, ref body, fn_decl_span) => {
1881 self.with_new_scopes(|this| {
1882 this.with_parent_def(e.id, |this| {
1883 let expr = this.lower_expr(body);
1884 hir::ExprClosure(this.lower_capture_clause(capture_clause),
1885 this.lower_fn_decl(decl),
1886 this.record_body(expr, Some(decl)),
1891 ExprKind::Block(ref blk) => hir::ExprBlock(self.lower_block(blk, None)),
1892 ExprKind::Assign(ref el, ref er) => {
1893 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
1895 ExprKind::AssignOp(op, ref el, ref er) => {
1896 hir::ExprAssignOp(self.lower_binop(op),
1897 P(self.lower_expr(el)),
1898 P(self.lower_expr(er)))
1900 ExprKind::Field(ref el, ident) => {
1901 hir::ExprField(P(self.lower_expr(el)), respan(ident.span, ident.node.name))
1903 ExprKind::TupField(ref el, ident) => {
1904 hir::ExprTupField(P(self.lower_expr(el)), ident)
1906 ExprKind::Index(ref el, ref er) => {
1907 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
1909 ExprKind::Range(ref e1, ref e2, lims) => {
1910 use syntax::ast::RangeLimits::*;
1912 let (path, variant) = match (e1, e2, lims) {
1913 (&None, &None, HalfOpen) => ("RangeFull", None),
1914 (&Some(..), &None, HalfOpen) => ("RangeFrom", None),
1915 (&None, &Some(..), HalfOpen) => ("RangeTo", None),
1916 (&Some(..), &Some(..), HalfOpen) => ("Range", None),
1917 (&None, &Some(..), Closed) => ("RangeToInclusive", None),
1918 (&Some(..), &Some(..), Closed) => ("RangeInclusive", Some("NonEmpty")),
1919 (_, &None, Closed) =>
1920 panic!(self.diagnostic().span_fatal(
1921 e.span, "inclusive range with no end")),
1925 e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e)))
1927 let expr = P(self.lower_expr(&e));
1928 let unstable_span = self.allow_internal_unstable("...", e.span);
1929 self.field(Symbol::intern(s), expr, unstable_span)
1930 }).collect::<P<[hir::Field]>>();
1932 let is_unit = fields.is_empty();
1933 let unstable_span = self.allow_internal_unstable("...", e.span);
1935 iter::once("ops").chain(iter::once(path)).chain(variant)
1936 .collect::<Vec<_>>();
1937 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
1938 let struct_path = hir::QPath::Resolved(None, P(struct_path));
1941 id: self.lower_node_id(e.id),
1943 hir::ExprPath(struct_path)
1945 hir::ExprStruct(struct_path, fields, None)
1947 span: unstable_span,
1948 attrs: e.attrs.clone(),
1951 ExprKind::Path(ref qself, ref path) => {
1952 hir::ExprPath(self.lower_qpath(e.id, qself, path, ParamMode::Optional))
1954 ExprKind::Break(opt_ident, ref opt_expr) => {
1955 let label_result = if self.is_in_loop_condition && opt_ident.is_none() {
1958 target_id: hir::ScopeTarget::Loop(
1959 Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into()),
1962 self.lower_loop_destination(opt_ident.map(|ident| (e.id, ident)))
1966 opt_expr.as_ref().map(|x| P(self.lower_expr(x))))
1968 ExprKind::Continue(opt_ident) =>
1970 if self.is_in_loop_condition && opt_ident.is_none() {
1973 target_id: hir::ScopeTarget::Loop(Err(
1974 hir::LoopIdError::UnlabeledCfInWhileCondition).into()),
1977 self.lower_loop_destination(opt_ident.map( |ident| (e.id, ident)))
1979 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
1980 ExprKind::InlineAsm(ref asm) => {
1981 let hir_asm = hir::InlineAsm {
1982 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
1983 outputs: asm.outputs.iter().map(|out| {
1984 hir::InlineAsmOutput {
1985 constraint: out.constraint.clone(),
1987 is_indirect: out.is_indirect,
1990 asm: asm.asm.clone(),
1991 asm_str_style: asm.asm_str_style,
1992 clobbers: asm.clobbers.clone().into(),
1993 volatile: asm.volatile,
1994 alignstack: asm.alignstack,
1995 dialect: asm.dialect,
1996 expn_id: asm.expn_id,
1999 asm.outputs.iter().map(|out| self.lower_expr(&out.expr)).collect();
2001 asm.inputs.iter().map(|&(_, ref input)| self.lower_expr(input)).collect();
2002 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
2004 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
2005 hir::ExprStruct(self.lower_qpath(e.id, &None, path, ParamMode::Optional),
2006 fields.iter().map(|x| self.lower_field(x)).collect(),
2007 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))))
2009 ExprKind::Paren(ref ex) => {
2010 let mut ex = self.lower_expr(ex);
2011 // include parens in span, but only if it is a super-span.
2012 if e.span.contains(ex.span) {
2015 // merge attributes into the inner expression.
2016 let mut attrs = e.attrs.clone();
2017 attrs.extend::<Vec<_>>(ex.attrs.into());
2022 // Desugar ExprIfLet
2023 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
2024 ExprKind::IfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
2027 // match <sub_expr> {
2029 // [_ if <else_opt_if_cond> => <else_opt_if_body>,]
2030 // _ => [<else_opt> | ()]
2033 let mut arms = vec![];
2035 // `<pat> => <body>`
2037 let body = self.lower_block(body, None);
2038 let body_expr = P(self.expr_block(body, ThinVec::new()));
2039 let pat = self.lower_pat(pat);
2040 arms.push(self.arm(hir_vec![pat], body_expr));
2043 // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
2044 // `_ => [<else_opt> | ()]`
2046 let mut current: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
2047 let mut else_exprs: Vec<Option<&Expr>> = vec![current];
2049 // First, we traverse the AST and recursively collect all
2050 // `else` branches into else_exprs, e.g.:
2052 // if let Some(_) = x {
2054 // } else if ... { // Expr1
2056 // } else if ... { // Expr2
2058 // } else { // Expr3
2062 // ... results in else_exprs = [Some(&Expr1),
2066 // Because there also the case there is no `else`, these
2067 // entries can also be `None`, as in:
2069 // if let Some(_) = x {
2071 // } else if ... { // Expr1
2073 // } else if ... { // Expr2
2077 // ... results in else_exprs = [Some(&Expr1),
2081 // The last entry in this list is always translated into
2082 // the final "unguard" wildcard arm of the `match`. In the
2083 // case of a `None`, it becomes `_ => ()`.
2085 if let Some(e) = current {
2086 // There is an else branch at this level
2087 if let ExprKind::If(_, _, ref else_opt) = e.node {
2088 // The else branch is again an if-expr
2089 current = else_opt.as_ref().map(|p| &**p);
2090 else_exprs.push(current);
2092 // The last item in the list is not an if-expr,
2097 // We have no more else branch
2102 // Now translate the list of nested else-branches into the
2103 // arms of the match statement.
2104 for else_expr in else_exprs {
2105 if let Some(else_expr) = else_expr {
2106 let (guard, body) = if let ExprKind::If(ref cond,
2108 _) = else_expr.node {
2109 let then = self.lower_block(then, None);
2111 self.expr_block(then, ThinVec::new()))
2114 self.lower_expr(else_expr))
2117 arms.push(hir::Arm {
2119 pats: hir_vec![self.pat_wild(e.span)],
2120 guard: guard.map(|e| P(self.lower_expr(e))),
2124 // There was no else-branch, push a noop
2125 let pat_under = self.pat_wild(e.span);
2126 let unit = self.expr_tuple(e.span, hir_vec![]);
2127 arms.push(self.arm(hir_vec![pat_under], unit));
2132 let contains_else_clause = else_opt.is_some();
2134 let sub_expr = P(self.lower_expr(sub_expr));
2139 hir::MatchSource::IfLetDesugar {
2140 contains_else_clause: contains_else_clause,
2144 // Desugar ExprWhileLet
2145 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
2146 ExprKind::WhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
2149 // [opt_ident]: loop {
2150 // match <sub_expr> {
2156 // Note that the block AND the condition are evaluated in the loop scope.
2157 // This is done to allow `break` from inside the condition of the loop.
2158 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| (
2159 this.lower_block(body, None),
2160 this.expr_break(e.span, ThinVec::new()),
2161 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
2164 // `<pat> => <body>`
2166 let body_expr = P(self.expr_block(body, ThinVec::new()));
2167 let pat = self.lower_pat(pat);
2168 self.arm(hir_vec![pat], body_expr)
2173 let pat_under = self.pat_wild(e.span);
2174 self.arm(hir_vec![pat_under], break_expr)
2177 // `match <sub_expr> { ... }`
2178 let arms = hir_vec![pat_arm, break_arm];
2179 let match_expr = self.expr(e.span,
2180 hir::ExprMatch(sub_expr,
2182 hir::MatchSource::WhileLetDesugar),
2185 // `[opt_ident]: loop { ... }`
2186 let loop_block = P(self.block_expr(P(match_expr)));
2187 let loop_expr = hir::ExprLoop(loop_block, self.lower_opt_sp_ident(opt_ident),
2188 hir::LoopSource::WhileLet);
2189 // add attributes to the outer returned expr node
2193 // Desugar ExprForLoop
2194 // From: `[opt_ident]: for <pat> in <head> <body>`
2195 ExprKind::ForLoop(ref pat, ref head, ref body, opt_ident) => {
2199 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
2201 // [opt_ident]: loop {
2202 // match ::std::iter::Iterator::next(&mut iter) {
2203 // ::std::option::Option::Some(<pat>) => <body>,
2204 // ::std::option::Option::None => break
2213 let head = self.lower_expr(head);
2215 let iter = self.str_to_ident("iter");
2217 // `::std::option::Option::Some(<pat>) => <body>`
2219 let body_block = self.with_loop_scope(e.id,
2220 |this| this.lower_block(body, None));
2221 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
2222 let pat = self.lower_pat(pat);
2223 let some_pat = self.pat_some(e.span, pat);
2225 self.arm(hir_vec![some_pat], body_expr)
2228 // `::std::option::Option::None => break`
2230 let break_expr = self.with_loop_scope(e.id, |this|
2231 this.expr_break(e.span, ThinVec::new()));
2232 let pat = self.pat_none(e.span);
2233 self.arm(hir_vec![pat], break_expr)
2237 let iter_pat = self.pat_ident_binding_mode(e.span, iter,
2238 hir::BindByValue(hir::MutMutable));
2240 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
2242 let iter = P(self.expr_ident(e.span, iter, iter_pat.id));
2243 let ref_mut_iter = self.expr_mut_addr_of(e.span, iter);
2244 let next_path = &["iter", "Iterator", "next"];
2245 let next_path = P(self.expr_std_path(e.span, next_path, ThinVec::new()));
2246 let next_expr = P(self.expr_call(e.span, next_path,
2247 hir_vec![ref_mut_iter]));
2248 let arms = hir_vec![pat_arm, break_arm];
2251 hir::ExprMatch(next_expr, arms,
2252 hir::MatchSource::ForLoopDesugar),
2256 // `[opt_ident]: loop { ... }`
2257 let loop_block = P(self.block_expr(match_expr));
2258 let loop_expr = hir::ExprLoop(loop_block, self.lower_opt_sp_ident(opt_ident),
2259 hir::LoopSource::ForLoop);
2260 let loop_expr = P(hir::Expr {
2261 id: self.lower_node_id(e.id),
2264 attrs: ThinVec::new(),
2267 // `mut iter => { ... }`
2268 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
2270 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
2271 let into_iter_expr = {
2272 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
2273 let into_iter = P(self.expr_std_path(e.span, into_iter_path,
2275 P(self.expr_call(e.span, into_iter, hir_vec![head]))
2278 let match_expr = P(self.expr_match(e.span,
2281 hir::MatchSource::ForLoopDesugar));
2283 // `{ let _result = ...; _result }`
2284 // underscore prevents an unused_variables lint if the head diverges
2285 let result_ident = self.str_to_ident("_result");
2286 let (let_stmt, let_stmt_binding) =
2287 self.stmt_let(e.span, false, result_ident, match_expr);
2289 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
2290 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
2291 // add the attributes to the outer returned expr node
2292 return self.expr_block(block, e.attrs.clone());
2295 // Desugar ExprKind::Try
2297 ExprKind::Try(ref sub_expr) => {
2300 // match Carrier::translate(<expr>) {
2301 // Ok(val) => #[allow(unreachable_code)] val,
2302 // Err(err) => #[allow(unreachable_code)]
2303 // // If there is an enclosing `catch {...}`
2304 // break 'catch_target Carrier::from_error(From::from(err)),
2306 // return Carrier::from_error(From::from(err)),
2309 let unstable_span = self.allow_internal_unstable("?", e.span);
2311 // Carrier::translate(<expr>)
2314 let sub_expr = self.lower_expr(sub_expr);
2316 let path = &["ops", "Carrier", "translate"];
2317 let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
2318 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
2321 // #[allow(unreachable_code)]
2323 // allow(unreachable_code)
2325 let allow_ident = self.str_to_ident("allow");
2326 let uc_ident = self.str_to_ident("unreachable_code");
2327 let uc_meta_item = attr::mk_spanned_word_item(e.span, uc_ident);
2328 let uc_nested = NestedMetaItemKind::MetaItem(uc_meta_item);
2329 let uc_spanned = respan(e.span, uc_nested);
2330 attr::mk_spanned_list_item(e.span, allow_ident, vec![uc_spanned])
2332 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
2334 let attrs = vec![attr];
2336 // Ok(val) => #[allow(unreachable_code)] val,
2338 let val_ident = self.str_to_ident("val");
2339 let val_pat = self.pat_ident(e.span, val_ident);
2340 let val_expr = P(self.expr_ident_with_attrs(e.span,
2343 ThinVec::from(attrs.clone())));
2344 let ok_pat = self.pat_ok(e.span, val_pat);
2346 self.arm(hir_vec![ok_pat], val_expr)
2349 // Err(err) => #[allow(unreachable_code)]
2350 // return Carrier::from_error(From::from(err)),
2352 let err_ident = self.str_to_ident("err");
2353 let err_local = self.pat_ident(e.span, err_ident);
2355 let path = &["convert", "From", "from"];
2356 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
2357 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
2359 self.expr_call(e.span, from, hir_vec![err_expr])
2361 let from_err_expr = {
2362 let path = &["ops", "Carrier", "from_error"];
2363 let from_err = P(self.expr_std_path(unstable_span, path,
2365 P(self.expr_call(e.span, from_err, hir_vec![from_expr]))
2368 let thin_attrs = ThinVec::from(attrs);
2369 let catch_scope = self.catch_scopes.last().map(|x| *x);
2370 let ret_expr = if let Some(catch_node) = catch_scope {
2376 target_id: hir::ScopeTarget::Block(catch_node),
2383 hir::Expr_::ExprRet(Some(from_err_expr)),
2388 let err_pat = self.pat_err(e.span, err_local);
2389 self.arm(hir_vec![err_pat], ret_expr)
2392 hir::ExprMatch(discr,
2393 hir_vec![err_arm, ok_arm],
2394 hir::MatchSource::TryDesugar)
2397 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
2401 id: self.lower_node_id(e.id),
2404 attrs: e.attrs.clone(),
2408 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
2409 SmallVector::one(match s.node {
2410 StmtKind::Local(ref l) => Spanned {
2411 node: hir::StmtDecl(P(Spanned {
2412 node: hir::DeclLocal(self.lower_local(l)),
2414 }), self.lower_node_id(s.id)),
2417 StmtKind::Item(ref it) => {
2418 // Can only use the ID once.
2419 let mut id = Some(s.id);
2420 return self.lower_item_id(it).into_iter().map(|item_id| Spanned {
2421 node: hir::StmtDecl(P(Spanned {
2422 node: hir::DeclItem(item_id),
2425 .map(|id| self.lower_node_id(id))
2426 .unwrap_or_else(|| self.next_id())),
2430 StmtKind::Expr(ref e) => {
2432 node: hir::StmtExpr(P(self.lower_expr(e)),
2433 self.lower_node_id(s.id)),
2437 StmtKind::Semi(ref e) => {
2439 node: hir::StmtSemi(P(self.lower_expr(e)),
2440 self.lower_node_id(s.id)),
2444 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
2448 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
2450 CaptureBy::Value => hir::CaptureByValue,
2451 CaptureBy::Ref => hir::CaptureByRef,
2455 /// If an `explicit_owner` is given, this method allocates the `HirId` in
2456 /// the address space of that item instead of the item currently being
2457 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
2458 /// lower a `Visibility` value although we haven't lowered the owning
2459 /// `ImplItem` in question yet.
2460 fn lower_visibility(&mut self,
2462 explicit_owner: Option<NodeId>)
2463 -> hir::Visibility {
2465 Visibility::Public => hir::Public,
2466 Visibility::Crate(_) => hir::Visibility::Crate,
2467 Visibility::Restricted { ref path, id } => {
2468 hir::Visibility::Restricted {
2469 path: P(self.lower_path(id, path, ParamMode::Explicit, true)),
2470 id: if let Some(owner) = explicit_owner {
2471 self.lower_node_id_with_owner(id, owner)
2473 self.lower_node_id(id)
2477 Visibility::Inherited => hir::Inherited,
2481 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
2483 Defaultness::Default => hir::Defaultness::Default { has_value: has_value },
2484 Defaultness::Final => {
2486 hir::Defaultness::Final
2491 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
2493 BlockCheckMode::Default => hir::DefaultBlock,
2494 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
2498 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingMode {
2500 BindingMode::ByRef(m) => hir::BindByRef(self.lower_mutability(m)),
2501 BindingMode::ByValue(m) => hir::BindByValue(self.lower_mutability(m)),
2505 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2507 CompilerGenerated => hir::CompilerGenerated,
2508 UserProvided => hir::UserProvided,
2512 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
2514 ImplPolarity::Positive => hir::ImplPolarity::Positive,
2515 ImplPolarity::Negative => hir::ImplPolarity::Negative,
2519 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2521 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2522 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
2526 // Helper methods for building HIR.
2528 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
2537 fn field(&mut self, name: Name, expr: P<hir::Expr>, span: Span) -> hir::Field {
2545 is_shorthand: false,
2549 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
2550 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
2551 P(self.expr(span, expr_break, attrs))
2554 fn expr_call(&mut self, span: Span, e: P<hir::Expr>, args: hir::HirVec<hir::Expr>)
2556 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
2559 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
2560 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
2563 fn expr_ident_with_attrs(&mut self, span: Span,
2566 attrs: ThinVec<Attribute>) -> hir::Expr {
2568 let defs = self.resolver.definitions();
2569 Def::Local(defs.local_def_id(binding))
2572 let expr_path = hir::ExprPath(hir::QPath::Resolved(None, P(hir::Path {
2575 segments: hir_vec![hir::PathSegment::from_name(id)],
2578 self.expr(span, expr_path, attrs)
2581 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
2582 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
2585 fn expr_std_path(&mut self,
2587 components: &[&str],
2588 attrs: ThinVec<Attribute>)
2590 let path = self.std_path(span, components, true);
2591 self.expr(span, hir::ExprPath(hir::QPath::Resolved(None, P(path))), attrs)
2594 fn expr_match(&mut self,
2597 arms: hir::HirVec<hir::Arm>,
2598 source: hir::MatchSource)
2600 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
2603 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
2604 self.expr(b.span, hir::ExprBlock(b), attrs)
2607 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
2608 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
2611 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
2620 fn stmt_let(&mut self, sp: Span, mutbl: bool, ident: Name, ex: P<hir::Expr>)
2621 -> (hir::Stmt, NodeId) {
2622 let pat = if mutbl {
2623 self.pat_ident_binding_mode(sp, ident, hir::BindByValue(hir::MutMutable))
2625 self.pat_ident(sp, ident)
2627 let pat_id = pat.id;
2628 let local = P(hir::Local {
2634 attrs: ThinVec::new(),
2636 let decl = respan(sp, hir::DeclLocal(local));
2637 (respan(sp, hir::StmtDecl(P(decl), self.next_id())), pat_id)
2640 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
2641 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
2644 fn block_all(&mut self, span: Span, stmts: hir::HirVec<hir::Stmt>, expr: Option<P<hir::Expr>>)
2650 rules: hir::DefaultBlock,
2652 break_to_expr_id: None,
2656 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2657 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
2660 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2661 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
2664 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2665 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
2668 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
2669 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
2672 fn pat_std_enum(&mut self,
2674 components: &[&str],
2675 subpats: hir::HirVec<P<hir::Pat>>)
2677 let path = self.std_path(span, components, true);
2678 let qpath = hir::QPath::Resolved(None, P(path));
2679 let pt = if subpats.is_empty() {
2680 hir::PatKind::Path(qpath)
2682 hir::PatKind::TupleStruct(qpath, subpats, None)
2687 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
2688 self.pat_ident_binding_mode(span, name, hir::BindByValue(hir::MutImmutable))
2691 fn pat_ident_binding_mode(&mut self, span: Span, name: Name, bm: hir::BindingMode)
2693 let id = self.next_id();
2694 let parent_def = self.parent_def;
2696 let defs = self.resolver.definitions();
2697 let def_path_data = DefPathData::Binding(name.as_str());
2698 let def_index = defs.create_def_with_parent(parent_def,
2702 DefId::local(def_index)
2707 node: hir::PatKind::Binding(bm,
2718 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
2719 self.pat(span, hir::PatKind::Wild)
2722 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
2730 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
2731 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
2732 /// The path is also resolved according to `is_value`.
2733 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
2734 let mut path = hir::Path {
2737 segments: iter::once(keywords::CrateRoot.name()).chain({
2738 self.crate_root.into_iter().chain(components.iter().cloned()).map(Symbol::intern)
2739 }).map(hir::PathSegment::from_name).collect(),
2742 self.resolver.resolve_hir_path(&mut path, is_value);
2746 fn signal_block_expr(&mut self,
2747 stmts: hir::HirVec<hir::Stmt>,
2750 rule: hir::BlockCheckMode,
2751 attrs: ThinVec<Attribute>)
2753 let id = self.next_id();
2754 let block = P(hir::Block {
2760 break_to_expr_id: None,
2762 self.expr_block(block, attrs)
2765 fn ty_path(&mut self, id: NodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
2767 let node = match qpath {
2768 hir::QPath::Resolved(None, path) => {
2769 // Turn trait object paths into `TyTraitObject` instead.
2770 if let Def::Trait(_) = path.def {
2771 let principal = hir::PolyTraitRef {
2772 bound_lifetimes: hir_vec![],
2773 trait_ref: hir::TraitRef {
2774 path: path.and_then(|path| path),
2780 // The original ID is taken by the `PolyTraitRef`,
2781 // so the `Ty` itself needs a different one.
2782 id = self.next_id();
2784 hir::TyTraitObject(hir_vec![principal], self.elided_lifetime(span))
2786 hir::TyPath(hir::QPath::Resolved(None, path))
2789 _ => hir::TyPath(qpath)
2791 P(hir::Ty { id, node, span })
2794 fn elided_lifetime(&mut self, span: Span) -> hir::Lifetime {
2798 name: keywords::Invalid.name()
2803 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
2804 // Sorting by span ensures that we get things in order within a
2805 // file, and also puts the files in a sensible order.
2806 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
2807 body_ids.sort_by_key(|b| bodies[b].value.span);