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;
60 use syntax::ext::hygiene::{Mark, SyntaxContext};
62 use syntax::codemap::{self, respan, Spanned};
63 use syntax::std_inject;
64 use syntax::symbol::{Symbol, keywords};
65 use syntax::util::small_vector::SmallVector;
66 use syntax::visit::{self, Visitor};
69 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
71 pub struct LoweringContext<'a> {
72 crate_root: Option<&'static str>,
73 // Use to assign ids to hir nodes that do not directly correspond to an ast node
75 // As we walk the AST we must keep track of the current 'parent' def id (in
76 // the form of a DefIndex) so that if we create a new node which introduces
77 // a definition, then we can properly create the def id.
78 parent_def: Option<DefIndex>,
79 resolver: &'a mut Resolver,
81 /// The items being lowered are collected here.
82 items: BTreeMap<NodeId, hir::Item>,
84 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
85 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
86 bodies: BTreeMap<hir::BodyId, hir::Body>,
87 exported_macros: Vec<hir::MacroDef>,
89 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
90 trait_default_impl: BTreeMap<DefId, NodeId>,
92 catch_scopes: Vec<NodeId>,
93 loop_scopes: Vec<NodeId>,
94 is_in_loop_condition: bool,
96 type_def_lifetime_params: DefIdMap<usize>,
98 current_hir_id_owner: Vec<(DefIndex, u32)>,
99 item_local_id_counters: NodeMap<u32>,
100 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
104 // Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
105 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
107 // Obtain the resolution for a node id
108 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
110 // We must keep the set of definitions up to date as we add nodes that weren't in the AST.
111 // This should only return `None` during testing.
112 fn definitions(&mut self) -> &mut Definitions;
115 pub fn lower_crate(sess: &Session,
117 resolver: &mut Resolver)
119 // We're constructing the HIR here; we don't care what we will
120 // read, since we haven't even constructed the *input* to
122 let _ignore = sess.dep_graph.in_ignore();
125 crate_root: std_inject::injected_crate_name(krate),
129 items: BTreeMap::new(),
130 trait_items: BTreeMap::new(),
131 impl_items: BTreeMap::new(),
132 bodies: BTreeMap::new(),
133 trait_impls: BTreeMap::new(),
134 trait_default_impl: BTreeMap::new(),
135 exported_macros: Vec::new(),
136 catch_scopes: Vec::new(),
137 loop_scopes: Vec::new(),
138 is_in_loop_condition: false,
139 type_def_lifetime_params: DefIdMap(),
140 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
141 item_local_id_counters: NodeMap(),
142 node_id_to_hir_id: IndexVec::new(),
146 #[derive(Copy, Clone, PartialEq, Eq)]
148 /// Any path in a type context.
150 /// The `module::Type` in `module::Type::method` in an expression.
154 impl<'a> LoweringContext<'a> {
155 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
156 /// Full-crate AST visitor that inserts into a fresh
157 /// `LoweringContext` any information that may be
158 /// needed from arbitrary locations in the crate.
159 /// E.g. The number of lifetime generic parameters
160 /// declared for every type and trait definition.
161 struct MiscCollector<'lcx, 'interner: 'lcx> {
162 lctx: &'lcx mut LoweringContext<'interner>,
165 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
166 fn visit_item(&mut self, item: &'lcx Item) {
167 self.lctx.allocate_hir_id_counter(item.id, item);
170 ItemKind::Struct(_, ref generics) |
171 ItemKind::Union(_, ref generics) |
172 ItemKind::Enum(_, ref generics) |
173 ItemKind::Ty(_, ref generics) |
174 ItemKind::Trait(_, ref generics, ..) => {
175 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
176 let count = generics.lifetimes.len();
177 self.lctx.type_def_lifetime_params.insert(def_id, count);
181 visit::walk_item(self, item);
184 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
185 self.lctx.allocate_hir_id_counter(item.id, item);
186 visit::walk_trait_item(self, item);
189 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
190 self.lctx.allocate_hir_id_counter(item.id, item);
191 visit::walk_impl_item(self, item);
195 struct ItemLowerer<'lcx, 'interner: 'lcx> {
196 lctx: &'lcx mut LoweringContext<'interner>,
199 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
200 fn visit_item(&mut self, item: &'lcx Item) {
201 let mut item_lowered = true;
202 self.lctx.with_hir_id_owner(item.id, |lctx| {
203 if let Some(hir_item) = lctx.lower_item(item) {
204 lctx.items.insert(item.id, hir_item);
206 item_lowered = false;
211 visit::walk_item(self, item);
215 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
216 self.lctx.with_hir_id_owner(item.id, |lctx| {
217 let id = hir::TraitItemId { node_id: item.id };
218 let hir_item = lctx.lower_trait_item(item);
219 lctx.trait_items.insert(id, hir_item);
222 visit::walk_trait_item(self, item);
225 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
226 self.lctx.with_hir_id_owner(item.id, |lctx| {
227 let id = hir::ImplItemId { node_id: item.id };
228 let hir_item = lctx.lower_impl_item(item);
229 lctx.impl_items.insert(id, hir_item);
231 visit::walk_impl_item(self, item);
235 self.lower_node_id(CRATE_NODE_ID);
236 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
238 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
239 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
241 let module = self.lower_mod(&c.module);
242 let attrs = self.lower_attrs(&c.attrs);
243 let body_ids = body_ids(&self.bodies);
247 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
253 exported_macros: hir::HirVec::from(self.exported_macros),
255 trait_items: self.trait_items,
256 impl_items: self.impl_items,
259 trait_impls: self.trait_impls,
260 trait_default_impl: self.trait_default_impl,
264 fn allocate_hir_id_counter<T: Debug>(&mut self,
267 if self.item_local_id_counters.insert(owner, 0).is_some() {
268 bug!("Tried to allocate item_local_id_counter for {:?} twice", debug);
270 // Always allocate the first HirId for the owner itself
271 self.lower_node_id_with_owner(owner, owner);
274 fn lower_node_id_generic<F>(&mut self,
278 where F: FnOnce(&mut Self) -> hir::HirId
280 if ast_node_id == DUMMY_NODE_ID {
284 let min_size = ast_node_id.as_usize() + 1;
286 if min_size > self.node_id_to_hir_id.len() {
287 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
290 if self.node_id_to_hir_id[ast_node_id] == hir::DUMMY_HIR_ID {
291 // Generate a new HirId
292 self.node_id_to_hir_id[ast_node_id] = alloc_hir_id(self);
298 fn with_hir_id_owner<F>(&mut self, owner: NodeId, f: F)
299 where F: FnOnce(&mut Self)
301 let counter = self.item_local_id_counters
302 .insert(owner, HIR_ID_COUNTER_LOCKED)
304 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
305 self.current_hir_id_owner.push((def_index, counter));
307 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
309 debug_assert!(def_index == new_def_index);
310 debug_assert!(new_counter >= counter);
312 let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
313 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
316 /// This method allocates a new HirId for the given NodeId and stores it in
317 /// the LoweringContext's NodeId => HirId map.
318 /// Take care not to call this method if the resulting HirId is then not
319 /// actually used in the HIR, as that would trigger an assertion in the
320 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
321 /// properly. Calling the method twice with the same NodeId is fine though.
322 fn lower_node_id(&mut self, ast_node_id: NodeId) -> NodeId {
323 self.lower_node_id_generic(ast_node_id, |this| {
324 let &mut (def_index, ref mut local_id_counter) = this.current_hir_id_owner
327 let local_id = *local_id_counter;
328 *local_id_counter += 1;
331 local_id: hir::ItemLocalId(local_id),
336 fn lower_node_id_with_owner(&mut self,
340 self.lower_node_id_generic(ast_node_id, |this| {
341 let local_id_counter = this.item_local_id_counters
344 let local_id = *local_id_counter;
346 // We want to be sure not to modify the counter in the map while it
347 // is also on the stack. Otherwise we'll get lost updates when writing
348 // back from the stack to the map.
349 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
351 *local_id_counter += 1;
352 let def_index = this.resolver.definitions().opt_def_index(owner).unwrap();
356 local_id: hir::ItemLocalId(local_id),
361 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>)
363 let body = hir::Body {
364 arguments: decl.map_or(hir_vec![], |decl| {
365 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
370 self.bodies.insert(id, body);
374 fn next_id(&mut self) -> NodeId {
375 self.lower_node_id(self.sess.next_node_id())
378 fn expect_full_def(&mut self, id: NodeId) -> Def {
379 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
380 if pr.unresolved_segments() != 0 {
381 bug!("path not fully resolved: {:?}", pr);
387 fn diagnostic(&self) -> &errors::Handler {
388 self.sess.diagnostic()
391 fn str_to_ident(&self, s: &'static str) -> Name {
395 fn allow_internal_unstable(&self, reason: &'static str, mut span: Span) -> Span {
396 let mark = Mark::fresh();
397 mark.set_expn_info(codemap::ExpnInfo {
399 callee: codemap::NameAndSpan {
400 format: codemap::CompilerDesugaring(Symbol::intern(reason)),
402 allow_internal_unstable: true,
405 span.ctxt = SyntaxContext::empty().apply_mark(mark);
409 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
410 where F: FnOnce(&mut LoweringContext) -> T
412 let len = self.catch_scopes.len();
413 self.catch_scopes.push(catch_id);
415 let result = f(self);
416 assert_eq!(len + 1, self.catch_scopes.len(),
417 "catch scopes should be added and removed in stack order");
419 self.catch_scopes.pop().unwrap();
424 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
425 where F: FnOnce(&mut LoweringContext) -> T
427 // We're no longer in the base loop's condition; we're in another loop.
428 let was_in_loop_condition = self.is_in_loop_condition;
429 self.is_in_loop_condition = false;
431 let len = self.loop_scopes.len();
432 self.loop_scopes.push(loop_id);
434 let result = f(self);
435 assert_eq!(len + 1, self.loop_scopes.len(),
436 "Loop scopes should be added and removed in stack order");
438 self.loop_scopes.pop().unwrap();
440 self.is_in_loop_condition = was_in_loop_condition;
445 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
446 where F: FnOnce(&mut LoweringContext) -> T
448 let was_in_loop_condition = self.is_in_loop_condition;
449 self.is_in_loop_condition = true;
451 let result = f(self);
453 self.is_in_loop_condition = was_in_loop_condition;
458 fn with_new_scopes<T, F>(&mut self, f: F) -> T
459 where F: FnOnce(&mut LoweringContext) -> T
461 let was_in_loop_condition = self.is_in_loop_condition;
462 self.is_in_loop_condition = false;
464 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
465 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
466 let result = f(self);
467 self.catch_scopes = catch_scopes;
468 self.loop_scopes = loop_scopes;
470 self.is_in_loop_condition = was_in_loop_condition;
475 fn with_parent_def<T, F>(&mut self, parent_id: NodeId, f: F) -> T
476 where F: FnOnce(&mut LoweringContext) -> T
478 let old_def = self.parent_def;
480 let defs = self.resolver.definitions();
481 Some(defs.opt_def_index(parent_id).unwrap())
484 let result = f(self);
486 self.parent_def = old_def;
490 fn def_key(&mut self, id: DefId) -> DefKey {
492 self.resolver.definitions().def_key(id.index)
494 self.sess.cstore.def_key(id)
498 fn lower_opt_sp_ident(&mut self, o_id: Option<Spanned<Ident>>) -> Option<Spanned<Name>> {
499 o_id.map(|sp_ident| respan(sp_ident.span, sp_ident.node.name))
502 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Spanned<Ident>)>)
506 Some((id, label_ident)) => {
507 let target = if let Def::Label(loop_id) = self.expect_full_def(id) {
508 hir::LoopIdResult::Ok(self.lower_node_id(loop_id))
510 hir::LoopIdResult::Err(hir::LoopIdError::UnresolvedLabel)
513 ident: Some(label_ident),
514 target_id: hir::ScopeTarget::Loop(target),
518 let loop_id = self.loop_scopes
520 .map(|innermost_loop_id| *innermost_loop_id);
524 target_id: hir::ScopeTarget::Loop(
525 loop_id.map(|id| Ok(self.lower_node_id(id)))
526 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
533 fn lower_attrs(&mut self, attrs: &Vec<Attribute>) -> hir::HirVec<Attribute> {
537 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
539 attrs: self.lower_attrs(&arm.attrs),
540 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
541 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
542 body: P(self.lower_expr(&arm.body)),
546 fn lower_ty_binding(&mut self, b: &TypeBinding) -> hir::TypeBinding {
548 id: self.lower_node_id(b.id),
550 ty: self.lower_ty(&b.ty),
555 fn lower_ty(&mut self, t: &Ty) -> P<hir::Ty> {
556 let kind = match t.node {
557 TyKind::Infer => hir::TyInfer,
558 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty)),
559 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt)),
560 TyKind::Rptr(ref region, ref mt) => {
561 let span = Span { hi: t.span.lo, ..t.span };
562 let lifetime = match *region {
563 Some(ref lt) => self.lower_lifetime(lt),
564 None => self.elided_lifetime(span)
566 hir::TyRptr(lifetime, self.lower_mt(mt))
568 TyKind::BareFn(ref f) => {
569 hir::TyBareFn(P(hir::BareFnTy {
570 lifetimes: self.lower_lifetime_defs(&f.lifetimes),
571 unsafety: self.lower_unsafety(f.unsafety),
573 decl: self.lower_fn_decl(&f.decl),
576 TyKind::Never => hir::TyNever,
577 TyKind::Tup(ref tys) => {
578 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty)).collect())
580 TyKind::Paren(ref ty) => {
581 return self.lower_ty(ty);
583 TyKind::Path(ref qself, ref path) => {
584 let id = self.lower_node_id(t.id);
585 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit);
586 return self.ty_path(id, t.span, qpath);
588 TyKind::ImplicitSelf => {
589 hir::TyPath(hir::QPath::Resolved(None, P(hir::Path {
590 def: self.expect_full_def(t.id),
591 segments: hir_vec![hir::PathSegment {
592 name: keywords::SelfType.name(),
593 parameters: hir::PathParameters::none()
598 TyKind::Array(ref ty, ref length) => {
599 let length = self.lower_expr(length);
600 hir::TyArray(self.lower_ty(ty),
601 self.record_body(length, None))
603 TyKind::Typeof(ref expr) => {
604 let expr = self.lower_expr(expr);
605 hir::TyTypeof(self.record_body(expr, None))
607 TyKind::TraitObject(ref bounds) => {
608 let mut lifetime_bound = None;
609 let bounds = bounds.iter().filter_map(|bound| {
611 TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
612 Some(self.lower_poly_trait_ref(ty))
614 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
615 RegionTyParamBound(ref lifetime) => {
616 if lifetime_bound.is_none() {
617 lifetime_bound = Some(self.lower_lifetime(lifetime));
623 let lifetime_bound = lifetime_bound.unwrap_or_else(|| {
624 self.elided_lifetime(t.span)
626 hir::TyTraitObject(bounds, lifetime_bound)
628 TyKind::ImplTrait(ref bounds) => {
629 hir::TyImplTrait(self.lower_bounds(bounds))
631 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
635 id: self.lower_node_id(t.id),
641 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
644 items: fm.items.iter().map(|x| self.lower_foreign_item(x)).collect(),
648 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
650 node: hir::Variant_ {
651 name: v.node.name.name,
652 attrs: self.lower_attrs(&v.node.attrs),
653 data: self.lower_variant_data(&v.node.data),
654 disr_expr: v.node.disr_expr.as_ref().map(|e| {
655 let e = self.lower_expr(e);
656 self.record_body(e, None)
663 fn lower_qpath(&mut self,
665 qself: &Option<QSelf>,
667 param_mode: ParamMode)
669 let qself_position = qself.as_ref().map(|q| q.position);
670 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty));
672 let resolution = self.resolver.get_resolution(id)
673 .unwrap_or(PathResolution::new(Def::Err));
675 let proj_start = p.segments.len() - resolution.unresolved_segments();
676 let path = P(hir::Path {
677 def: resolution.base_def(),
678 segments: p.segments[..proj_start].iter().enumerate().map(|(i, segment)| {
679 let param_mode = match (qself_position, param_mode) {
680 (Some(j), ParamMode::Optional) if i < j => {
681 // This segment is part of the trait path in a
682 // qualified path - one of `a`, `b` or `Trait`
683 // in `<X as a::b::Trait>::T::U::method`.
689 // Figure out if this is a type/trait segment,
690 // which may need lifetime elision performed.
691 let parent_def_id = |this: &mut Self, def_id: DefId| {
694 index: this.def_key(def_id).parent.expect("missing parent")
697 let type_def_id = match resolution.base_def() {
698 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
699 Some(parent_def_id(self, def_id))
701 Def::Variant(def_id) if i + 1 == proj_start => {
702 Some(parent_def_id(self, def_id))
704 Def::Struct(def_id) |
707 Def::TyAlias(def_id) |
708 Def::Trait(def_id) if i + 1 == proj_start => Some(def_id),
712 let num_lifetimes = type_def_id.map_or(0, |def_id| {
713 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
716 assert!(!def_id.is_local());
717 let n = self.sess.cstore.item_generics_cloned(def_id).regions.len();
718 self.type_def_lifetime_params.insert(def_id, n);
721 self.lower_path_segment(p.span, segment, param_mode, num_lifetimes)
726 // Simple case, either no projections, or only fully-qualified.
727 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
728 if resolution.unresolved_segments() == 0 {
729 return hir::QPath::Resolved(qself, path);
732 // Create the innermost type that we're projecting from.
733 let mut ty = if path.segments.is_empty() {
734 // If the base path is empty that means there exists a
735 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
736 qself.expect("missing QSelf for <T>::...")
738 // Otherwise, the base path is an implicit `Self` type path,
739 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
740 // `<I as Iterator>::Item::default`.
741 let new_id = self.next_id();
742 self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
745 // Anything after the base path are associated "extensions",
746 // out of which all but the last one are associated types,
747 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
748 // * base path is `std::vec::Vec<T>`
749 // * "extensions" are `IntoIter`, `Item` and `clone`
751 // 1. `std::vec::Vec<T>` (created above)
752 // 2. `<std::vec::Vec<T>>::IntoIter`
753 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
754 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
755 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
756 let segment = P(self.lower_path_segment(p.span, segment, param_mode, 0));
757 let qpath = hir::QPath::TypeRelative(ty, segment);
759 // It's finished, return the extension of the right node type.
760 if i == p.segments.len() - 1 {
764 // Wrap the associated extension in another type node.
765 let new_id = self.next_id();
766 ty = self.ty_path(new_id, p.span, qpath);
769 // Should've returned in the for loop above.
770 span_bug!(p.span, "lower_qpath: no final extension segment in {}..{}",
771 proj_start, p.segments.len())
774 fn lower_path_extra(&mut self,
778 param_mode: ParamMode,
779 defaults_to_global: bool)
781 let mut segments = p.segments.iter();
782 if defaults_to_global && p.is_global() {
787 def: self.expect_full_def(id),
788 segments: segments.map(|segment| {
789 self.lower_path_segment(p.span, segment, param_mode, 0)
790 }).chain(name.map(|name| {
793 parameters: hir::PathParameters::none()
800 fn lower_path(&mut self,
803 param_mode: ParamMode,
804 defaults_to_global: bool)
806 self.lower_path_extra(id, p, None, param_mode, defaults_to_global)
809 fn lower_path_segment(&mut self,
811 segment: &PathSegment,
812 param_mode: ParamMode,
813 expected_lifetimes: usize)
814 -> hir::PathSegment {
815 let mut parameters = if let Some(ref parameters) = segment.parameters {
817 PathParameters::AngleBracketed(ref data) => {
818 let data = self.lower_angle_bracketed_parameter_data(data, param_mode);
819 hir::AngleBracketedParameters(data)
821 PathParameters::Parenthesized(ref data) => {
822 hir::ParenthesizedParameters(self.lower_parenthesized_parameter_data(data))
826 let data = self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode);
827 hir::AngleBracketedParameters(data)
830 if let hir::AngleBracketedParameters(ref mut data) = parameters {
831 if data.lifetimes.is_empty() {
832 data.lifetimes = (0..expected_lifetimes).map(|_| {
833 self.elided_lifetime(path_span)
839 name: segment.identifier.name,
840 parameters: parameters,
844 fn lower_angle_bracketed_parameter_data(&mut self,
845 data: &AngleBracketedParameterData,
846 param_mode: ParamMode)
847 -> hir::AngleBracketedParameterData {
848 let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
849 hir::AngleBracketedParameterData {
850 lifetimes: self.lower_lifetimes(lifetimes),
851 types: types.iter().map(|ty| self.lower_ty(ty)).collect(),
852 infer_types: types.is_empty() && param_mode == ParamMode::Optional,
853 bindings: bindings.iter().map(|b| self.lower_ty_binding(b)).collect(),
857 fn lower_parenthesized_parameter_data(&mut self,
858 data: &ParenthesizedParameterData)
859 -> hir::ParenthesizedParameterData {
860 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
861 hir::ParenthesizedParameterData {
862 inputs: inputs.iter().map(|ty| self.lower_ty(ty)).collect(),
863 output: output.as_ref().map(|ty| self.lower_ty(ty)),
868 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
870 id: self.lower_node_id(l.id),
871 ty: l.ty.as_ref().map(|t| self.lower_ty(t)),
872 pat: self.lower_pat(&l.pat),
873 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
875 attrs: l.attrs.clone(),
879 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
881 Mutability::Mutable => hir::MutMutable,
882 Mutability::Immutable => hir::MutImmutable,
886 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
888 id: self.lower_node_id(arg.id),
889 pat: self.lower_pat(&arg.pat),
893 fn lower_fn_args_to_names(&mut self, decl: &FnDecl)
894 -> hir::HirVec<Spanned<Name>> {
895 decl.inputs.iter().map(|arg| {
897 PatKind::Ident(_, ident, None) => {
898 respan(ident.span, ident.node.name)
900 _ => respan(arg.pat.span, keywords::Invalid.name()),
905 fn lower_fn_decl(&mut self, decl: &FnDecl) -> P<hir::FnDecl> {
907 inputs: decl.inputs.iter().map(|arg| self.lower_ty(&arg.ty)).collect(),
908 output: match decl.output {
909 FunctionRetTy::Ty(ref ty) => hir::Return(self.lower_ty(ty)),
910 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
912 variadic: decl.variadic,
913 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| {
915 TyKind::ImplicitSelf => true,
916 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
923 fn lower_ty_param_bound(&mut self, tpb: &TyParamBound) -> hir::TyParamBound {
925 TraitTyParamBound(ref ty, modifier) => {
926 hir::TraitTyParamBound(self.lower_poly_trait_ref(ty),
927 self.lower_trait_bound_modifier(modifier))
929 RegionTyParamBound(ref lifetime) => {
930 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
935 fn lower_ty_param(&mut self, tp: &TyParam, add_bounds: &[TyParamBound]) -> hir::TyParam {
936 let mut name = tp.ident.name;
938 // Don't expose `Self` (recovered "keyword used as ident" parse error).
939 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
940 // Instead, use gensym("Self") to create a distinct name that looks the same.
941 if name == keywords::SelfType.name() {
942 name = Symbol::gensym("Self");
945 let mut bounds = self.lower_bounds(&tp.bounds);
946 if !add_bounds.is_empty() {
947 bounds = bounds.into_iter().chain(self.lower_bounds(add_bounds).into_iter()).collect();
951 id: self.lower_node_id(tp.id),
954 default: tp.default.as_ref().map(|x| self.lower_ty(x)),
956 pure_wrt_drop: tp.attrs.iter().any(|attr| attr.check_name("may_dangle")),
960 fn lower_ty_params(&mut self, tps: &Vec<TyParam>, add_bounds: &NodeMap<Vec<TyParamBound>>)
961 -> hir::HirVec<hir::TyParam> {
962 tps.iter().map(|tp| {
963 self.lower_ty_param(tp, add_bounds.get(&tp.id).map_or(&[][..], |x| &x))
967 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
969 id: self.lower_node_id(l.id),
975 fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef {
977 lifetime: self.lower_lifetime(&l.lifetime),
978 bounds: self.lower_lifetimes(&l.bounds),
979 pure_wrt_drop: l.attrs.iter().any(|attr| attr.check_name("may_dangle")),
983 fn lower_lifetimes(&mut self, lts: &Vec<Lifetime>) -> hir::HirVec<hir::Lifetime> {
984 lts.iter().map(|l| self.lower_lifetime(l)).collect()
987 fn lower_lifetime_defs(&mut self, lts: &Vec<LifetimeDef>) -> hir::HirVec<hir::LifetimeDef> {
988 lts.iter().map(|l| self.lower_lifetime_def(l)).collect()
991 fn lower_generics(&mut self, g: &Generics) -> hir::Generics {
992 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
993 let mut add_bounds = NodeMap();
994 for pred in &g.where_clause.predicates {
995 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
996 'next_bound: for bound in &bound_pred.bounds {
997 if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
998 let report_error = |this: &mut Self| {
999 this.diagnostic().span_err(bound_pred.bounded_ty.span,
1000 "`?Trait` bounds are only permitted at the \
1001 point where a type parameter is declared");
1003 // Check if the where clause type is a plain type parameter.
1004 match bound_pred.bounded_ty.node {
1005 TyKind::Path(None, ref path)
1006 if path.segments.len() == 1 &&
1007 bound_pred.bound_lifetimes.is_empty() => {
1008 if let Some(Def::TyParam(def_id)) =
1009 self.resolver.get_resolution(bound_pred.bounded_ty.id)
1010 .map(|d| d.base_def()) {
1011 if let Some(node_id) =
1012 self.resolver.definitions().as_local_node_id(def_id) {
1013 for ty_param in &g.ty_params {
1014 if node_id == ty_param.id {
1015 add_bounds.entry(ty_param.id).or_insert(Vec::new())
1016 .push(bound.clone());
1017 continue 'next_bound;
1024 _ => report_error(self)
1032 ty_params: self.lower_ty_params(&g.ty_params, &add_bounds),
1033 lifetimes: self.lower_lifetime_defs(&g.lifetimes),
1034 where_clause: self.lower_where_clause(&g.where_clause),
1039 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
1041 id: self.lower_node_id(wc.id),
1042 predicates: wc.predicates
1044 .map(|predicate| self.lower_where_predicate(predicate))
1049 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
1051 WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
1055 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1056 bound_lifetimes: self.lower_lifetime_defs(bound_lifetimes),
1057 bounded_ty: self.lower_ty(bounded_ty),
1058 bounds: bounds.iter().filter_map(|bound| match *bound {
1059 // Ignore `?Trait` bounds, they were copied into type parameters already.
1060 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1061 _ => Some(self.lower_ty_param_bound(bound))
1066 WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
1069 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1071 lifetime: self.lower_lifetime(lifetime),
1072 bounds: bounds.iter().map(|bound| self.lower_lifetime(bound)).collect(),
1075 WherePredicate::EqPredicate(WhereEqPredicate{ id,
1079 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1080 id: self.lower_node_id(id),
1081 lhs_ty: self.lower_ty(lhs_ty),
1082 rhs_ty: self.lower_ty(rhs_ty),
1089 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
1091 VariantData::Struct(ref fields, id) => {
1092 hir::VariantData::Struct(fields.iter()
1094 .map(|f| self.lower_struct_field(f))
1096 self.lower_node_id(id))
1098 VariantData::Tuple(ref fields, id) => {
1099 hir::VariantData::Tuple(fields.iter()
1101 .map(|f| self.lower_struct_field(f))
1103 self.lower_node_id(id))
1105 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id)),
1109 fn lower_trait_ref(&mut self, p: &TraitRef) -> hir::TraitRef {
1110 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit) {
1111 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
1112 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath)
1116 ref_id: self.lower_node_id(p.ref_id),
1120 fn lower_poly_trait_ref(&mut self, p: &PolyTraitRef) -> hir::PolyTraitRef {
1122 bound_lifetimes: self.lower_lifetime_defs(&p.bound_lifetimes),
1123 trait_ref: self.lower_trait_ref(&p.trait_ref),
1128 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
1131 id: self.lower_node_id(f.id),
1132 name: f.ident.map(|ident| ident.name).unwrap_or(Symbol::intern(&index.to_string())),
1133 vis: self.lower_visibility(&f.vis, None),
1134 ty: self.lower_ty(&f.ty),
1135 attrs: self.lower_attrs(&f.attrs),
1139 fn lower_field(&mut self, f: &Field) -> hir::Field {
1141 name: respan(f.ident.span, f.ident.node.name),
1142 expr: P(self.lower_expr(&f.expr)),
1144 is_shorthand: f.is_shorthand,
1148 fn lower_mt(&mut self, mt: &MutTy) -> hir::MutTy {
1150 ty: self.lower_ty(&mt.ty),
1151 mutbl: self.lower_mutability(mt.mutbl),
1155 fn lower_bounds(&mut self, bounds: &[TyParamBound]) -> hir::TyParamBounds {
1156 bounds.iter().map(|bound| self.lower_ty_param_bound(bound)).collect()
1159 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
1160 let mut expr = None;
1162 let mut stmts = vec![];
1164 for (index, stmt) in b.stmts.iter().enumerate() {
1165 if index == b.stmts.len() - 1 {
1166 if let StmtKind::Expr(ref e) = stmt.node {
1167 expr = Some(P(self.lower_expr(e)));
1169 stmts.extend(self.lower_stmt(stmt));
1172 stmts.extend(self.lower_stmt(stmt));
1177 id: self.lower_node_id(b.id),
1178 stmts: stmts.into(),
1180 rules: self.lower_block_check_mode(&b.rules),
1182 targeted_by_break: targeted_by_break,
1186 fn lower_item_kind(&mut self,
1189 attrs: &hir::HirVec<Attribute>,
1190 vis: &mut hir::Visibility,
1194 ItemKind::ExternCrate(string) => hir::ItemExternCrate(string),
1195 ItemKind::Use(ref view_path) => {
1196 let path = match view_path.node {
1197 ViewPathSimple(_, ref path) => path,
1198 ViewPathGlob(ref path) => path,
1199 ViewPathList(ref path, ref path_list_idents) => {
1200 for &Spanned { node: ref import, span } in path_list_idents {
1201 // `use a::{self as x, b as y};` lowers to
1202 // `use a as x; use a::b as y;`
1203 let mut ident = import.name;
1204 let suffix = if ident.name == keywords::SelfValue.name() {
1205 if let Some(last) = path.segments.last() {
1206 ident = last.identifier;
1213 let mut path = self.lower_path_extra(import.id, path, suffix,
1214 ParamMode::Explicit, true);
1217 self.allocate_hir_id_counter(import.id, import);
1218 self.with_hir_id_owner(import.id, |this| {
1219 let vis = match *vis {
1220 hir::Visibility::Public => hir::Visibility::Public,
1221 hir::Visibility::Crate => hir::Visibility::Crate,
1222 hir::Visibility::Inherited => hir::Visibility::Inherited,
1223 hir::Visibility::Restricted { ref path, id: _ } => {
1224 hir::Visibility::Restricted {
1226 // We are allocating a new NodeId here
1232 this.items.insert(import.id, hir::Item {
1234 name: import.rename.unwrap_or(ident).name,
1235 attrs: attrs.clone(),
1236 node: hir::ItemUse(P(path), hir::UseKind::Single),
1245 let path = P(self.lower_path(id, path, ParamMode::Explicit, true));
1246 let kind = match view_path.node {
1247 ViewPathSimple(ident, _) => {
1249 hir::UseKind::Single
1251 ViewPathGlob(_) => {
1254 ViewPathList(..) => {
1255 // Privatize the degenerate import base, used only to check
1256 // the stability of `use a::{};`, to avoid it showing up as
1257 // a reexport by accident when `pub`, e.g. in documentation.
1258 *vis = hir::Inherited;
1259 hir::UseKind::ListStem
1262 hir::ItemUse(path, kind)
1264 ItemKind::Static(ref t, m, ref e) => {
1265 let value = self.lower_expr(e);
1266 hir::ItemStatic(self.lower_ty(t),
1267 self.lower_mutability(m),
1268 self.record_body(value, None))
1270 ItemKind::Const(ref t, ref e) => {
1271 let value = self.lower_expr(e);
1272 hir::ItemConst(self.lower_ty(t),
1273 self.record_body(value, None))
1275 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
1276 self.with_new_scopes(|this| {
1277 let body = this.lower_block(body, false);
1278 let body = this.expr_block(body, ThinVec::new());
1279 let body_id = this.record_body(body, Some(decl));
1280 hir::ItemFn(this.lower_fn_decl(decl),
1281 this.lower_unsafety(unsafety),
1282 this.lower_constness(constness),
1284 this.lower_generics(generics),
1288 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
1289 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
1290 ItemKind::Ty(ref t, ref generics) => {
1291 hir::ItemTy(self.lower_ty(t), self.lower_generics(generics))
1293 ItemKind::Enum(ref enum_definition, ref generics) => {
1294 hir::ItemEnum(hir::EnumDef {
1295 variants: enum_definition.variants
1297 .map(|x| self.lower_variant(x))
1300 self.lower_generics(generics))
1302 ItemKind::Struct(ref struct_def, ref generics) => {
1303 let struct_def = self.lower_variant_data(struct_def);
1304 hir::ItemStruct(struct_def, self.lower_generics(generics))
1306 ItemKind::Union(ref vdata, ref generics) => {
1307 let vdata = self.lower_variant_data(vdata);
1308 hir::ItemUnion(vdata, self.lower_generics(generics))
1310 ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1311 let trait_ref = self.lower_trait_ref(trait_ref);
1313 if let Def::Trait(def_id) = trait_ref.path.def {
1314 self.trait_default_impl.insert(def_id, id);
1317 hir::ItemDefaultImpl(self.lower_unsafety(unsafety),
1320 ItemKind::Impl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
1321 let new_impl_items = impl_items.iter()
1322 .map(|item| self.lower_impl_item_ref(item))
1324 let ifce = ifce.as_ref().map(|trait_ref| self.lower_trait_ref(trait_ref));
1326 if let Some(ref trait_ref) = ifce {
1327 if let Def::Trait(def_id) = trait_ref.path.def {
1328 self.trait_impls.entry(def_id).or_insert(vec![]).push(id);
1332 hir::ItemImpl(self.lower_unsafety(unsafety),
1333 self.lower_impl_polarity(polarity),
1334 self.lower_generics(generics),
1339 ItemKind::Trait(unsafety, ref generics, ref bounds, ref items) => {
1340 let bounds = self.lower_bounds(bounds);
1341 let items = items.iter().map(|item| self.lower_trait_item_ref(item)).collect();
1342 hir::ItemTrait(self.lower_unsafety(unsafety),
1343 self.lower_generics(generics),
1347 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
1351 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
1352 self.with_parent_def(i.id, |this| {
1354 id: this.lower_node_id(i.id),
1356 attrs: this.lower_attrs(&i.attrs),
1357 node: match i.node {
1358 TraitItemKind::Const(ref ty, ref default) => {
1359 hir::TraitItemKind::Const(this.lower_ty(ty),
1360 default.as_ref().map(|x| {
1361 let value = this.lower_expr(x);
1362 this.record_body(value, None)
1365 TraitItemKind::Method(ref sig, None) => {
1366 let names = this.lower_fn_args_to_names(&sig.decl);
1367 hir::TraitItemKind::Method(this.lower_method_sig(sig),
1368 hir::TraitMethod::Required(names))
1370 TraitItemKind::Method(ref sig, Some(ref body)) => {
1371 let body = this.lower_block(body, false);
1372 let expr = this.expr_block(body, ThinVec::new());
1373 let body_id = this.record_body(expr, Some(&sig.decl));
1374 hir::TraitItemKind::Method(this.lower_method_sig(sig),
1375 hir::TraitMethod::Provided(body_id))
1377 TraitItemKind::Type(ref bounds, ref default) => {
1378 hir::TraitItemKind::Type(this.lower_bounds(bounds),
1379 default.as_ref().map(|x| this.lower_ty(x)))
1381 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
1388 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
1389 let (kind, has_default) = match i.node {
1390 TraitItemKind::Const(_, ref default) => {
1391 (hir::AssociatedItemKind::Const, default.is_some())
1393 TraitItemKind::Type(_, ref default) => {
1394 (hir::AssociatedItemKind::Type, default.is_some())
1396 TraitItemKind::Method(ref sig, ref default) => {
1397 (hir::AssociatedItemKind::Method {
1398 has_self: sig.decl.has_self(),
1399 }, default.is_some())
1401 TraitItemKind::Macro(..) => unimplemented!(),
1404 id: hir::TraitItemId { node_id: i.id },
1407 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
1412 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
1413 self.with_parent_def(i.id, |this| {
1415 id: this.lower_node_id(i.id),
1417 attrs: this.lower_attrs(&i.attrs),
1418 vis: this.lower_visibility(&i.vis, None),
1419 defaultness: this.lower_defaultness(i.defaultness, true /* [1] */),
1420 node: match i.node {
1421 ImplItemKind::Const(ref ty, ref expr) => {
1422 let value = this.lower_expr(expr);
1423 let body_id = this.record_body(value, None);
1424 hir::ImplItemKind::Const(this.lower_ty(ty), body_id)
1426 ImplItemKind::Method(ref sig, ref body) => {
1427 let body = this.lower_block(body, false);
1428 let expr = this.expr_block(body, ThinVec::new());
1429 let body_id = this.record_body(expr, Some(&sig.decl));
1430 hir::ImplItemKind::Method(this.lower_method_sig(sig), body_id)
1432 ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(this.lower_ty(ty)),
1433 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
1439 // [1] since `default impl` is not yet implemented, this is always true in impls
1442 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
1444 id: hir::ImplItemId { node_id: i.id },
1447 vis: self.lower_visibility(&i.vis, Some(i.id)),
1448 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
1449 kind: match i.node {
1450 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
1451 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
1452 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
1453 has_self: sig.decl.has_self(),
1455 ImplItemKind::Macro(..) => unimplemented!(),
1459 // [1] since `default impl` is not yet implemented, this is always true in impls
1462 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
1465 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
1469 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
1471 ItemKind::Use(ref view_path) => {
1472 if let ViewPathList(_, ref imports) = view_path.node {
1473 return iter::once(i.id).chain(imports.iter().map(|import| import.node.id))
1474 .map(|id| hir::ItemId { id: id }).collect();
1477 ItemKind::MacroDef(..) => return SmallVector::new(),
1480 SmallVector::one(hir::ItemId { id: i.id })
1483 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
1484 let mut name = i.ident.name;
1485 let attrs = self.lower_attrs(&i.attrs);
1486 if let ItemKind::MacroDef(ref tts) = i.node {
1487 if i.attrs.iter().any(|attr| attr.path == "macro_export") {
1488 self.exported_macros.push(hir::MacroDef {
1489 name: name, attrs: attrs, id: i.id, span: i.span, body: tts.clone().into(),
1495 let mut vis = self.lower_visibility(&i.vis, None);
1496 let node = self.with_parent_def(i.id, |this| {
1497 this.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node)
1501 id: self.lower_node_id(i.id),
1510 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
1511 self.with_parent_def(i.id, |this| {
1513 id: this.lower_node_id(i.id),
1515 attrs: this.lower_attrs(&i.attrs),
1516 node: match i.node {
1517 ForeignItemKind::Fn(ref fdec, ref generics) => {
1518 hir::ForeignItemFn(this.lower_fn_decl(fdec),
1519 this.lower_fn_args_to_names(fdec),
1520 this.lower_generics(generics))
1522 ForeignItemKind::Static(ref t, m) => {
1523 hir::ForeignItemStatic(this.lower_ty(t), m)
1526 vis: this.lower_visibility(&i.vis, None),
1532 fn lower_method_sig(&mut self, sig: &MethodSig) -> hir::MethodSig {
1534 generics: self.lower_generics(&sig.generics),
1536 unsafety: self.lower_unsafety(sig.unsafety),
1537 constness: self.lower_constness(sig.constness),
1538 decl: self.lower_fn_decl(&sig.decl),
1542 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
1544 Unsafety::Unsafe => hir::Unsafety::Unsafe,
1545 Unsafety::Normal => hir::Unsafety::Normal,
1549 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
1551 Constness::Const => hir::Constness::Const,
1552 Constness::NotConst => hir::Constness::NotConst,
1556 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
1558 UnOp::Deref => hir::UnDeref,
1559 UnOp::Not => hir::UnNot,
1560 UnOp::Neg => hir::UnNeg,
1564 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
1566 node: match b.node {
1567 BinOpKind::Add => hir::BiAdd,
1568 BinOpKind::Sub => hir::BiSub,
1569 BinOpKind::Mul => hir::BiMul,
1570 BinOpKind::Div => hir::BiDiv,
1571 BinOpKind::Rem => hir::BiRem,
1572 BinOpKind::And => hir::BiAnd,
1573 BinOpKind::Or => hir::BiOr,
1574 BinOpKind::BitXor => hir::BiBitXor,
1575 BinOpKind::BitAnd => hir::BiBitAnd,
1576 BinOpKind::BitOr => hir::BiBitOr,
1577 BinOpKind::Shl => hir::BiShl,
1578 BinOpKind::Shr => hir::BiShr,
1579 BinOpKind::Eq => hir::BiEq,
1580 BinOpKind::Lt => hir::BiLt,
1581 BinOpKind::Le => hir::BiLe,
1582 BinOpKind::Ne => hir::BiNe,
1583 BinOpKind::Ge => hir::BiGe,
1584 BinOpKind::Gt => hir::BiGt,
1590 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
1592 id: self.lower_node_id(p.id),
1593 node: match p.node {
1594 PatKind::Wild => hir::PatKind::Wild,
1595 PatKind::Ident(ref binding_mode, pth1, ref sub) => {
1596 self.with_parent_def(p.id, |this| {
1597 match this.resolver.get_resolution(p.id).map(|d| d.base_def()) {
1598 // `None` can occur in body-less function signatures
1599 def @ None | def @ Some(Def::Local(_)) => {
1600 let def_id = def.map(|d| d.def_id()).unwrap_or_else(|| {
1601 this.resolver.definitions().local_def_id(p.id)
1603 hir::PatKind::Binding(this.lower_binding_mode(binding_mode),
1605 respan(pth1.span, pth1.node.name),
1606 sub.as_ref().map(|x| this.lower_pat(x)))
1609 hir::PatKind::Path(hir::QPath::Resolved(None, P(hir::Path {
1613 hir::PathSegment::from_name(pth1.node.name)
1620 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
1621 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
1622 let qpath = self.lower_qpath(p.id, &None, path, ParamMode::Optional);
1623 hir::PatKind::TupleStruct(qpath,
1624 pats.iter().map(|x| self.lower_pat(x)).collect(),
1627 PatKind::Path(ref qself, ref path) => {
1628 hir::PatKind::Path(self.lower_qpath(p.id, qself, path, ParamMode::Optional))
1630 PatKind::Struct(ref path, ref fields, etc) => {
1631 let qpath = self.lower_qpath(p.id, &None, path, ParamMode::Optional);
1633 let fs = fields.iter()
1637 node: hir::FieldPat {
1638 name: f.node.ident.name,
1639 pat: self.lower_pat(&f.node.pat),
1640 is_shorthand: f.node.is_shorthand,
1645 hir::PatKind::Struct(qpath, fs, etc)
1647 PatKind::Tuple(ref elts, ddpos) => {
1648 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
1650 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
1651 PatKind::Ref(ref inner, mutbl) => {
1652 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
1654 PatKind::Range(ref e1, ref e2, ref end) => {
1655 hir::PatKind::Range(P(self.lower_expr(e1)),
1656 P(self.lower_expr(e2)),
1657 self.lower_range_end(end))
1659 PatKind::Slice(ref before, ref slice, ref after) => {
1660 hir::PatKind::Slice(before.iter().map(|x| self.lower_pat(x)).collect(),
1661 slice.as_ref().map(|x| self.lower_pat(x)),
1662 after.iter().map(|x| self.lower_pat(x)).collect())
1664 PatKind::Mac(_) => panic!("Shouldn't exist here"),
1670 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
1672 RangeEnd::Included => hir::RangeEnd::Included,
1673 RangeEnd::Excluded => hir::RangeEnd::Excluded,
1677 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
1678 let kind = match e.node {
1680 // Eventually a desugaring for `box EXPR`
1681 // (similar to the desugaring above for `in PLACE BLOCK`)
1682 // should go here, desugaring
1686 // let mut place = BoxPlace::make_place();
1687 // let raw_place = Place::pointer(&mut place);
1688 // let value = $value;
1690 // ::std::ptr::write(raw_place, value);
1691 // Boxed::finalize(place)
1694 // But for now there are type-inference issues doing that.
1695 ExprKind::Box(ref inner) => {
1696 hir::ExprBox(P(self.lower_expr(inner)))
1699 // Desugar ExprBox: `in (PLACE) EXPR`
1700 ExprKind::InPlace(ref placer, ref value_expr) => {
1704 // let mut place = Placer::make_place(p);
1705 // let raw_place = Place::pointer(&mut place);
1707 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1708 // InPlace::finalize(place)
1710 let placer_expr = P(self.lower_expr(placer));
1711 let value_expr = P(self.lower_expr(value_expr));
1713 let placer_ident = self.str_to_ident("placer");
1714 let place_ident = self.str_to_ident("place");
1715 let p_ptr_ident = self.str_to_ident("p_ptr");
1717 let make_place = ["ops", "Placer", "make_place"];
1718 let place_pointer = ["ops", "Place", "pointer"];
1719 let move_val_init = ["intrinsics", "move_val_init"];
1720 let inplace_finalize = ["ops", "InPlace", "finalize"];
1722 let unstable_span = self.allow_internal_unstable("<-", e.span);
1723 let make_call = |this: &mut LoweringContext, p, args| {
1724 let path = P(this.expr_std_path(unstable_span, p, ThinVec::new()));
1725 P(this.expr_call(e.span, path, args))
1728 let mk_stmt_let = |this: &mut LoweringContext, bind, expr| {
1729 this.stmt_let(e.span, false, bind, expr)
1732 let mk_stmt_let_mut = |this: &mut LoweringContext, bind, expr| {
1733 this.stmt_let(e.span, true, bind, expr)
1736 // let placer = <placer_expr> ;
1737 let (s1, placer_binding) = {
1738 mk_stmt_let(self, placer_ident, placer_expr)
1741 // let mut place = Placer::make_place(placer);
1742 let (s2, place_binding) = {
1743 let placer = self.expr_ident(e.span, placer_ident, placer_binding);
1744 let call = make_call(self, &make_place, hir_vec![placer]);
1745 mk_stmt_let_mut(self, place_ident, call)
1748 // let p_ptr = Place::pointer(&mut place);
1749 let (s3, p_ptr_binding) = {
1750 let agent = P(self.expr_ident(e.span, place_ident, place_binding));
1751 let args = hir_vec![self.expr_mut_addr_of(e.span, agent)];
1752 let call = make_call(self, &place_pointer, args);
1753 mk_stmt_let(self, p_ptr_ident, call)
1756 // pop_unsafe!(EXPR));
1757 let pop_unsafe_expr = {
1758 self.signal_block_expr(hir_vec![],
1761 hir::PopUnsafeBlock(hir::CompilerGenerated),
1766 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1767 // InPlace::finalize(place)
1770 let ptr = self.expr_ident(e.span, p_ptr_ident, p_ptr_binding);
1771 let call_move_val_init =
1773 make_call(self, &move_val_init, hir_vec![ptr, pop_unsafe_expr]),
1775 let call_move_val_init = respan(e.span, call_move_val_init);
1777 let place = self.expr_ident(e.span, place_ident, place_binding);
1778 let call = make_call(self, &inplace_finalize, hir_vec![place]);
1779 P(self.signal_block_expr(hir_vec![call_move_val_init],
1782 hir::PushUnsafeBlock(hir::CompilerGenerated),
1786 let block = self.block_all(e.span, hir_vec![s1, s2, s3], Some(expr));
1787 hir::ExprBlock(P(block))
1790 ExprKind::Array(ref exprs) => {
1791 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
1793 ExprKind::Repeat(ref expr, ref count) => {
1794 let expr = P(self.lower_expr(expr));
1795 let count = self.lower_expr(count);
1796 hir::ExprRepeat(expr, self.record_body(count, None))
1798 ExprKind::Tup(ref elts) => {
1799 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
1801 ExprKind::Call(ref f, ref args) => {
1802 let f = P(self.lower_expr(f));
1803 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
1805 ExprKind::MethodCall(i, ref tps, ref args) => {
1806 let tps = tps.iter().map(|x| self.lower_ty(x)).collect();
1807 let args = args.iter().map(|x| self.lower_expr(x)).collect();
1808 hir::ExprMethodCall(respan(i.span, i.node.name), tps, args)
1810 ExprKind::Binary(binop, ref lhs, ref rhs) => {
1811 let binop = self.lower_binop(binop);
1812 let lhs = P(self.lower_expr(lhs));
1813 let rhs = P(self.lower_expr(rhs));
1814 hir::ExprBinary(binop, lhs, rhs)
1816 ExprKind::Unary(op, ref ohs) => {
1817 let op = self.lower_unop(op);
1818 let ohs = P(self.lower_expr(ohs));
1819 hir::ExprUnary(op, ohs)
1821 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
1822 ExprKind::Cast(ref expr, ref ty) => {
1823 let expr = P(self.lower_expr(expr));
1824 hir::ExprCast(expr, self.lower_ty(ty))
1826 ExprKind::Type(ref expr, ref ty) => {
1827 let expr = P(self.lower_expr(expr));
1828 hir::ExprType(expr, self.lower_ty(ty))
1830 ExprKind::AddrOf(m, ref ohs) => {
1831 let m = self.lower_mutability(m);
1832 let ohs = P(self.lower_expr(ohs));
1833 hir::ExprAddrOf(m, ohs)
1835 // More complicated than you might expect because the else branch
1836 // might be `if let`.
1837 ExprKind::If(ref cond, ref blk, ref else_opt) => {
1838 let else_opt = else_opt.as_ref().map(|els| {
1840 ExprKind::IfLet(..) => {
1841 // wrap the if-let expr in a block
1842 let span = els.span;
1843 let els = P(self.lower_expr(els));
1844 let id = self.next_id();
1845 let blk = P(hir::Block {
1849 rules: hir::DefaultBlock,
1851 targeted_by_break: false,
1853 P(self.expr_block(blk, ThinVec::new()))
1855 _ => P(self.lower_expr(els)),
1859 let then_blk = self.lower_block(blk, false);
1860 let then_expr = self.expr_block(then_blk, ThinVec::new());
1862 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
1864 ExprKind::While(ref cond, ref body, opt_ident) => {
1865 self.with_loop_scope(e.id, |this|
1867 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
1868 this.lower_block(body, false),
1869 this.lower_opt_sp_ident(opt_ident)))
1871 ExprKind::Loop(ref body, opt_ident) => {
1872 self.with_loop_scope(e.id, |this|
1873 hir::ExprLoop(this.lower_block(body, false),
1874 this.lower_opt_sp_ident(opt_ident),
1875 hir::LoopSource::Loop))
1877 ExprKind::Catch(ref body) => {
1878 self.with_catch_scope(body.id, |this|
1879 hir::ExprBlock(this.lower_block(body, true)))
1881 ExprKind::Match(ref expr, ref arms) => {
1882 hir::ExprMatch(P(self.lower_expr(expr)),
1883 arms.iter().map(|x| self.lower_arm(x)).collect(),
1884 hir::MatchSource::Normal)
1886 ExprKind::Closure(capture_clause, ref decl, ref body, fn_decl_span) => {
1887 self.with_new_scopes(|this| {
1888 this.with_parent_def(e.id, |this| {
1889 let expr = this.lower_expr(body);
1890 hir::ExprClosure(this.lower_capture_clause(capture_clause),
1891 this.lower_fn_decl(decl),
1892 this.record_body(expr, Some(decl)),
1897 ExprKind::Block(ref blk) => hir::ExprBlock(self.lower_block(blk, false)),
1898 ExprKind::Assign(ref el, ref er) => {
1899 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
1901 ExprKind::AssignOp(op, ref el, ref er) => {
1902 hir::ExprAssignOp(self.lower_binop(op),
1903 P(self.lower_expr(el)),
1904 P(self.lower_expr(er)))
1906 ExprKind::Field(ref el, ident) => {
1907 hir::ExprField(P(self.lower_expr(el)), respan(ident.span, ident.node.name))
1909 ExprKind::TupField(ref el, ident) => {
1910 hir::ExprTupField(P(self.lower_expr(el)), ident)
1912 ExprKind::Index(ref el, ref er) => {
1913 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
1915 ExprKind::Range(ref e1, ref e2, lims) => {
1916 use syntax::ast::RangeLimits::*;
1918 let (path, variant) = match (e1, e2, lims) {
1919 (&None, &None, HalfOpen) => ("RangeFull", None),
1920 (&Some(..), &None, HalfOpen) => ("RangeFrom", None),
1921 (&None, &Some(..), HalfOpen) => ("RangeTo", None),
1922 (&Some(..), &Some(..), HalfOpen) => ("Range", None),
1923 (&None, &Some(..), Closed) => ("RangeToInclusive", None),
1924 (&Some(..), &Some(..), Closed) => ("RangeInclusive", Some("NonEmpty")),
1925 (_, &None, Closed) =>
1926 panic!(self.diagnostic().span_fatal(
1927 e.span, "inclusive range with no end")),
1931 e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e)))
1933 let expr = P(self.lower_expr(&e));
1934 let unstable_span = self.allow_internal_unstable("...", e.span);
1935 self.field(Symbol::intern(s), expr, unstable_span)
1936 }).collect::<P<[hir::Field]>>();
1938 let is_unit = fields.is_empty();
1939 let unstable_span = self.allow_internal_unstable("...", e.span);
1941 iter::once("ops").chain(iter::once(path)).chain(variant)
1942 .collect::<Vec<_>>();
1943 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
1944 let struct_path = hir::QPath::Resolved(None, P(struct_path));
1947 id: self.lower_node_id(e.id),
1949 hir::ExprPath(struct_path)
1951 hir::ExprStruct(struct_path, fields, None)
1953 span: unstable_span,
1954 attrs: e.attrs.clone(),
1957 ExprKind::Path(ref qself, ref path) => {
1958 hir::ExprPath(self.lower_qpath(e.id, qself, path, ParamMode::Optional))
1960 ExprKind::Break(opt_ident, ref opt_expr) => {
1961 let label_result = if self.is_in_loop_condition && opt_ident.is_none() {
1964 target_id: hir::ScopeTarget::Loop(
1965 Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into()),
1968 self.lower_loop_destination(opt_ident.map(|ident| (e.id, ident)))
1972 opt_expr.as_ref().map(|x| P(self.lower_expr(x))))
1974 ExprKind::Continue(opt_ident) =>
1976 if self.is_in_loop_condition && opt_ident.is_none() {
1979 target_id: hir::ScopeTarget::Loop(Err(
1980 hir::LoopIdError::UnlabeledCfInWhileCondition).into()),
1983 self.lower_loop_destination(opt_ident.map( |ident| (e.id, ident)))
1985 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
1986 ExprKind::InlineAsm(ref asm) => {
1987 let hir_asm = hir::InlineAsm {
1988 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
1989 outputs: asm.outputs.iter().map(|out| {
1990 hir::InlineAsmOutput {
1991 constraint: out.constraint.clone(),
1993 is_indirect: out.is_indirect,
1996 asm: asm.asm.clone(),
1997 asm_str_style: asm.asm_str_style,
1998 clobbers: asm.clobbers.clone().into(),
1999 volatile: asm.volatile,
2000 alignstack: asm.alignstack,
2001 dialect: asm.dialect,
2005 asm.outputs.iter().map(|out| self.lower_expr(&out.expr)).collect();
2007 asm.inputs.iter().map(|&(_, ref input)| self.lower_expr(input)).collect();
2008 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
2010 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
2011 hir::ExprStruct(self.lower_qpath(e.id, &None, path, ParamMode::Optional),
2012 fields.iter().map(|x| self.lower_field(x)).collect(),
2013 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))))
2015 ExprKind::Paren(ref ex) => {
2016 let mut ex = self.lower_expr(ex);
2017 // include parens in span, but only if it is a super-span.
2018 if e.span.contains(ex.span) {
2021 // merge attributes into the inner expression.
2022 let mut attrs = e.attrs.clone();
2023 attrs.extend::<Vec<_>>(ex.attrs.into());
2028 // Desugar ExprIfLet
2029 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
2030 ExprKind::IfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
2033 // match <sub_expr> {
2035 // [_ if <else_opt_if_cond> => <else_opt_if_body>,]
2036 // _ => [<else_opt> | ()]
2039 let mut arms = vec![];
2041 // `<pat> => <body>`
2043 let body = self.lower_block(body, false);
2044 let body_expr = P(self.expr_block(body, ThinVec::new()));
2045 let pat = self.lower_pat(pat);
2046 arms.push(self.arm(hir_vec![pat], body_expr));
2049 // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
2050 // `_ => [<else_opt> | ()]`
2052 let mut current: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
2053 let mut else_exprs: Vec<Option<&Expr>> = vec![current];
2055 // First, we traverse the AST and recursively collect all
2056 // `else` branches into else_exprs, e.g.:
2058 // if let Some(_) = x {
2060 // } else if ... { // Expr1
2062 // } else if ... { // Expr2
2064 // } else { // Expr3
2068 // ... results in else_exprs = [Some(&Expr1),
2072 // Because there also the case there is no `else`, these
2073 // entries can also be `None`, as in:
2075 // if let Some(_) = x {
2077 // } else if ... { // Expr1
2079 // } else if ... { // Expr2
2083 // ... results in else_exprs = [Some(&Expr1),
2087 // The last entry in this list is always translated into
2088 // the final "unguard" wildcard arm of the `match`. In the
2089 // case of a `None`, it becomes `_ => ()`.
2091 if let Some(e) = current {
2092 // There is an else branch at this level
2093 if let ExprKind::If(_, _, ref else_opt) = e.node {
2094 // The else branch is again an if-expr
2095 current = else_opt.as_ref().map(|p| &**p);
2096 else_exprs.push(current);
2098 // The last item in the list is not an if-expr,
2103 // We have no more else branch
2108 // Now translate the list of nested else-branches into the
2109 // arms of the match statement.
2110 for else_expr in else_exprs {
2111 if let Some(else_expr) = else_expr {
2112 let (guard, body) = if let ExprKind::If(ref cond,
2114 _) = else_expr.node {
2115 let then = self.lower_block(then, false);
2117 self.expr_block(then, ThinVec::new()))
2120 self.lower_expr(else_expr))
2123 arms.push(hir::Arm {
2125 pats: hir_vec![self.pat_wild(e.span)],
2126 guard: guard.map(|e| P(self.lower_expr(e))),
2130 // There was no else-branch, push a noop
2131 let pat_under = self.pat_wild(e.span);
2132 let unit = self.expr_tuple(e.span, hir_vec![]);
2133 arms.push(self.arm(hir_vec![pat_under], unit));
2138 let contains_else_clause = else_opt.is_some();
2140 let sub_expr = P(self.lower_expr(sub_expr));
2145 hir::MatchSource::IfLetDesugar {
2146 contains_else_clause: contains_else_clause,
2150 // Desugar ExprWhileLet
2151 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
2152 ExprKind::WhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
2155 // [opt_ident]: loop {
2156 // match <sub_expr> {
2162 // Note that the block AND the condition are evaluated in the loop scope.
2163 // This is done to allow `break` from inside the condition of the loop.
2164 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| (
2165 this.lower_block(body, false),
2166 this.expr_break(e.span, ThinVec::new()),
2167 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
2170 // `<pat> => <body>`
2172 let body_expr = P(self.expr_block(body, ThinVec::new()));
2173 let pat = self.lower_pat(pat);
2174 self.arm(hir_vec![pat], body_expr)
2179 let pat_under = self.pat_wild(e.span);
2180 self.arm(hir_vec![pat_under], break_expr)
2183 // `match <sub_expr> { ... }`
2184 let arms = hir_vec![pat_arm, break_arm];
2185 let match_expr = self.expr(e.span,
2186 hir::ExprMatch(sub_expr,
2188 hir::MatchSource::WhileLetDesugar),
2191 // `[opt_ident]: loop { ... }`
2192 let loop_block = P(self.block_expr(P(match_expr)));
2193 let loop_expr = hir::ExprLoop(loop_block, self.lower_opt_sp_ident(opt_ident),
2194 hir::LoopSource::WhileLet);
2195 // add attributes to the outer returned expr node
2199 // Desugar ExprForLoop
2200 // From: `[opt_ident]: for <pat> in <head> <body>`
2201 ExprKind::ForLoop(ref pat, ref head, ref body, opt_ident) => {
2205 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
2207 // [opt_ident]: loop {
2208 // match ::std::iter::Iterator::next(&mut iter) {
2209 // ::std::option::Option::Some(<pat>) => <body>,
2210 // ::std::option::Option::None => break
2219 let head = self.lower_expr(head);
2221 let iter = self.str_to_ident("iter");
2223 // `::std::option::Option::Some(<pat>) => <body>`
2225 let body_block = self.with_loop_scope(e.id,
2226 |this| this.lower_block(body, false));
2227 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
2228 let pat = self.lower_pat(pat);
2229 let some_pat = self.pat_some(e.span, pat);
2231 self.arm(hir_vec![some_pat], body_expr)
2234 // `::std::option::Option::None => break`
2236 let break_expr = self.with_loop_scope(e.id, |this|
2237 this.expr_break(e.span, ThinVec::new()));
2238 let pat = self.pat_none(e.span);
2239 self.arm(hir_vec![pat], break_expr)
2243 let iter_pat = self.pat_ident_binding_mode(e.span, iter,
2244 hir::BindByValue(hir::MutMutable));
2246 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
2248 let iter = P(self.expr_ident(e.span, iter, iter_pat.id));
2249 let ref_mut_iter = self.expr_mut_addr_of(e.span, iter);
2250 let next_path = &["iter", "Iterator", "next"];
2251 let next_path = P(self.expr_std_path(e.span, next_path, ThinVec::new()));
2252 let next_expr = P(self.expr_call(e.span, next_path,
2253 hir_vec![ref_mut_iter]));
2254 let arms = hir_vec![pat_arm, break_arm];
2257 hir::ExprMatch(next_expr, arms,
2258 hir::MatchSource::ForLoopDesugar),
2262 // `[opt_ident]: loop { ... }`
2263 let loop_block = P(self.block_expr(match_expr));
2264 let loop_expr = hir::ExprLoop(loop_block, self.lower_opt_sp_ident(opt_ident),
2265 hir::LoopSource::ForLoop);
2266 let loop_expr = P(hir::Expr {
2267 id: self.lower_node_id(e.id),
2270 attrs: ThinVec::new(),
2273 // `mut iter => { ... }`
2274 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
2276 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
2277 let into_iter_expr = {
2278 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
2279 let into_iter = P(self.expr_std_path(e.span, into_iter_path,
2281 P(self.expr_call(e.span, into_iter, hir_vec![head]))
2284 let match_expr = P(self.expr_match(e.span,
2287 hir::MatchSource::ForLoopDesugar));
2289 // `{ let _result = ...; _result }`
2290 // underscore prevents an unused_variables lint if the head diverges
2291 let result_ident = self.str_to_ident("_result");
2292 let (let_stmt, let_stmt_binding) =
2293 self.stmt_let(e.span, false, result_ident, match_expr);
2295 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
2296 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
2297 // add the attributes to the outer returned expr node
2298 return self.expr_block(block, e.attrs.clone());
2301 // Desugar ExprKind::Try
2303 ExprKind::Try(ref sub_expr) => {
2306 // match Carrier::translate(<expr>) {
2307 // Ok(val) => #[allow(unreachable_code)] val,
2308 // Err(err) => #[allow(unreachable_code)]
2309 // // If there is an enclosing `catch {...}`
2310 // break 'catch_target Carrier::from_error(From::from(err)),
2312 // return Carrier::from_error(From::from(err)),
2315 let unstable_span = self.allow_internal_unstable("?", e.span);
2317 // Carrier::translate(<expr>)
2320 let sub_expr = self.lower_expr(sub_expr);
2322 let path = &["ops", "Carrier", "translate"];
2323 let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
2324 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
2327 // #[allow(unreachable_code)]
2329 // allow(unreachable_code)
2331 let allow_ident = self.str_to_ident("allow");
2332 let uc_ident = self.str_to_ident("unreachable_code");
2333 let uc_meta_item = attr::mk_spanned_word_item(e.span, uc_ident);
2334 let uc_nested = NestedMetaItemKind::MetaItem(uc_meta_item);
2335 let uc_spanned = respan(e.span, uc_nested);
2336 attr::mk_spanned_list_item(e.span, allow_ident, vec![uc_spanned])
2338 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
2340 let attrs = vec![attr];
2342 // Ok(val) => #[allow(unreachable_code)] val,
2344 let val_ident = self.str_to_ident("val");
2345 let val_pat = self.pat_ident(e.span, val_ident);
2346 let val_expr = P(self.expr_ident_with_attrs(e.span,
2349 ThinVec::from(attrs.clone())));
2350 let ok_pat = self.pat_ok(e.span, val_pat);
2352 self.arm(hir_vec![ok_pat], val_expr)
2355 // Err(err) => #[allow(unreachable_code)]
2356 // return Carrier::from_error(From::from(err)),
2358 let err_ident = self.str_to_ident("err");
2359 let err_local = self.pat_ident(e.span, err_ident);
2361 let path = &["convert", "From", "from"];
2362 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
2363 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
2365 self.expr_call(e.span, from, hir_vec![err_expr])
2367 let from_err_expr = {
2368 let path = &["ops", "Carrier", "from_error"];
2369 let from_err = P(self.expr_std_path(unstable_span, path,
2371 P(self.expr_call(e.span, from_err, hir_vec![from_expr]))
2374 let thin_attrs = ThinVec::from(attrs);
2375 let catch_scope = self.catch_scopes.last().map(|x| *x);
2376 let ret_expr = if let Some(catch_node) = catch_scope {
2382 target_id: hir::ScopeTarget::Block(catch_node),
2389 hir::Expr_::ExprRet(Some(from_err_expr)),
2394 let err_pat = self.pat_err(e.span, err_local);
2395 self.arm(hir_vec![err_pat], ret_expr)
2398 hir::ExprMatch(discr,
2399 hir_vec![err_arm, ok_arm],
2400 hir::MatchSource::TryDesugar)
2403 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
2407 id: self.lower_node_id(e.id),
2410 attrs: e.attrs.clone(),
2414 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
2415 SmallVector::one(match s.node {
2416 StmtKind::Local(ref l) => Spanned {
2417 node: hir::StmtDecl(P(Spanned {
2418 node: hir::DeclLocal(self.lower_local(l)),
2420 }), self.lower_node_id(s.id)),
2423 StmtKind::Item(ref it) => {
2424 // Can only use the ID once.
2425 let mut id = Some(s.id);
2426 return self.lower_item_id(it).into_iter().map(|item_id| Spanned {
2427 node: hir::StmtDecl(P(Spanned {
2428 node: hir::DeclItem(item_id),
2431 .map(|id| self.lower_node_id(id))
2432 .unwrap_or_else(|| self.next_id())),
2436 StmtKind::Expr(ref e) => {
2438 node: hir::StmtExpr(P(self.lower_expr(e)),
2439 self.lower_node_id(s.id)),
2443 StmtKind::Semi(ref e) => {
2445 node: hir::StmtSemi(P(self.lower_expr(e)),
2446 self.lower_node_id(s.id)),
2450 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
2454 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
2456 CaptureBy::Value => hir::CaptureByValue,
2457 CaptureBy::Ref => hir::CaptureByRef,
2461 /// If an `explicit_owner` is given, this method allocates the `HirId` in
2462 /// the address space of that item instead of the item currently being
2463 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
2464 /// lower a `Visibility` value although we haven't lowered the owning
2465 /// `ImplItem` in question yet.
2466 fn lower_visibility(&mut self,
2468 explicit_owner: Option<NodeId>)
2469 -> hir::Visibility {
2471 Visibility::Public => hir::Public,
2472 Visibility::Crate(_) => hir::Visibility::Crate,
2473 Visibility::Restricted { ref path, id } => {
2474 hir::Visibility::Restricted {
2475 path: P(self.lower_path(id, path, ParamMode::Explicit, true)),
2476 id: if let Some(owner) = explicit_owner {
2477 self.lower_node_id_with_owner(id, owner)
2479 self.lower_node_id(id)
2483 Visibility::Inherited => hir::Inherited,
2487 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
2489 Defaultness::Default => hir::Defaultness::Default { has_value: has_value },
2490 Defaultness::Final => {
2492 hir::Defaultness::Final
2497 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
2499 BlockCheckMode::Default => hir::DefaultBlock,
2500 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
2504 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingMode {
2506 BindingMode::ByRef(m) => hir::BindByRef(self.lower_mutability(m)),
2507 BindingMode::ByValue(m) => hir::BindByValue(self.lower_mutability(m)),
2511 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2513 CompilerGenerated => hir::CompilerGenerated,
2514 UserProvided => hir::UserProvided,
2518 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
2520 ImplPolarity::Positive => hir::ImplPolarity::Positive,
2521 ImplPolarity::Negative => hir::ImplPolarity::Negative,
2525 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2527 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2528 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
2532 // Helper methods for building HIR.
2534 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
2543 fn field(&mut self, name: Name, expr: P<hir::Expr>, span: Span) -> hir::Field {
2551 is_shorthand: false,
2555 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
2556 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
2557 P(self.expr(span, expr_break, attrs))
2560 fn expr_call(&mut self, span: Span, e: P<hir::Expr>, args: hir::HirVec<hir::Expr>)
2562 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
2565 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
2566 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
2569 fn expr_ident_with_attrs(&mut self, span: Span,
2572 attrs: ThinVec<Attribute>) -> hir::Expr {
2574 let defs = self.resolver.definitions();
2575 Def::Local(defs.local_def_id(binding))
2578 let expr_path = hir::ExprPath(hir::QPath::Resolved(None, P(hir::Path {
2581 segments: hir_vec![hir::PathSegment::from_name(id)],
2584 self.expr(span, expr_path, attrs)
2587 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
2588 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
2591 fn expr_std_path(&mut self,
2593 components: &[&str],
2594 attrs: ThinVec<Attribute>)
2596 let path = self.std_path(span, components, true);
2597 self.expr(span, hir::ExprPath(hir::QPath::Resolved(None, P(path))), attrs)
2600 fn expr_match(&mut self,
2603 arms: hir::HirVec<hir::Arm>,
2604 source: hir::MatchSource)
2606 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
2609 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
2610 self.expr(b.span, hir::ExprBlock(b), attrs)
2613 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
2614 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
2617 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
2626 fn stmt_let(&mut self, sp: Span, mutbl: bool, ident: Name, ex: P<hir::Expr>)
2627 -> (hir::Stmt, NodeId) {
2628 let pat = if mutbl {
2629 self.pat_ident_binding_mode(sp, ident, hir::BindByValue(hir::MutMutable))
2631 self.pat_ident(sp, ident)
2633 let pat_id = pat.id;
2634 let local = P(hir::Local {
2640 attrs: ThinVec::new(),
2642 let decl = respan(sp, hir::DeclLocal(local));
2643 (respan(sp, hir::StmtDecl(P(decl), self.next_id())), pat_id)
2646 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
2647 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
2650 fn block_all(&mut self, span: Span, stmts: hir::HirVec<hir::Stmt>, expr: Option<P<hir::Expr>>)
2656 rules: hir::DefaultBlock,
2658 targeted_by_break: false,
2662 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2663 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
2666 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2667 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
2670 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2671 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
2674 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
2675 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
2678 fn pat_std_enum(&mut self,
2680 components: &[&str],
2681 subpats: hir::HirVec<P<hir::Pat>>)
2683 let path = self.std_path(span, components, true);
2684 let qpath = hir::QPath::Resolved(None, P(path));
2685 let pt = if subpats.is_empty() {
2686 hir::PatKind::Path(qpath)
2688 hir::PatKind::TupleStruct(qpath, subpats, None)
2693 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
2694 self.pat_ident_binding_mode(span, name, hir::BindByValue(hir::MutImmutable))
2697 fn pat_ident_binding_mode(&mut self, span: Span, name: Name, bm: hir::BindingMode)
2699 let id = self.next_id();
2700 let parent_def = self.parent_def;
2702 let defs = self.resolver.definitions();
2703 let def_path_data = DefPathData::Binding(name.as_str());
2704 let def_index = defs.create_def_with_parent(parent_def,
2708 DefId::local(def_index)
2713 node: hir::PatKind::Binding(bm,
2724 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
2725 self.pat(span, hir::PatKind::Wild)
2728 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
2736 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
2737 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
2738 /// The path is also resolved according to `is_value`.
2739 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
2740 let mut path = hir::Path {
2743 segments: iter::once(keywords::CrateRoot.name()).chain({
2744 self.crate_root.into_iter().chain(components.iter().cloned()).map(Symbol::intern)
2745 }).map(hir::PathSegment::from_name).collect(),
2748 self.resolver.resolve_hir_path(&mut path, is_value);
2752 fn signal_block_expr(&mut self,
2753 stmts: hir::HirVec<hir::Stmt>,
2756 rule: hir::BlockCheckMode,
2757 attrs: ThinVec<Attribute>)
2759 let id = self.next_id();
2760 let block = P(hir::Block {
2766 targeted_by_break: false,
2768 self.expr_block(block, attrs)
2771 fn ty_path(&mut self, id: NodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
2773 let node = match qpath {
2774 hir::QPath::Resolved(None, path) => {
2775 // Turn trait object paths into `TyTraitObject` instead.
2776 if let Def::Trait(_) = path.def {
2777 let principal = hir::PolyTraitRef {
2778 bound_lifetimes: hir_vec![],
2779 trait_ref: hir::TraitRef {
2780 path: path.and_then(|path| path),
2786 // The original ID is taken by the `PolyTraitRef`,
2787 // so the `Ty` itself needs a different one.
2788 id = self.next_id();
2790 hir::TyTraitObject(hir_vec![principal], self.elided_lifetime(span))
2792 hir::TyPath(hir::QPath::Resolved(None, path))
2795 _ => hir::TyPath(qpath)
2797 P(hir::Ty { id, node, span })
2800 fn elided_lifetime(&mut self, span: Span) -> hir::Lifetime {
2804 name: keywords::Invalid.name()
2809 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
2810 // Sorting by span ensures that we get things in order within a
2811 // file, and also puts the files in a sensible order.
2812 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
2813 body_ids.sort_by_key(|b| bodies[b].value.span);