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 lint::builtin::PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES;
49 use rustc_data_structures::indexed_vec::IndexVec;
51 use util::common::FN_OUTPUT_NAME;
52 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
54 use std::collections::BTreeMap;
61 use syntax::ext::hygiene::{Mark, SyntaxContext};
63 use syntax::codemap::{self, respan, Spanned, CompilerDesugaringKind};
64 use syntax::std_inject;
65 use syntax::symbol::{Symbol, keywords};
66 use syntax::util::small_vector::SmallVector;
67 use syntax::visit::{self, Visitor};
70 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
72 pub struct LoweringContext<'a> {
73 crate_root: Option<&'static str>,
75 // Use to assign ids to hir nodes that do not directly correspond to an ast node
78 // As we walk the AST we must keep track of the current 'parent' def id (in
79 // the form of a DefIndex) so that if we create a new node which introduces
80 // a definition, then we can properly create the def id.
81 parent_def: Option<DefIndex>,
82 resolver: &'a mut Resolver,
83 name_map: FxHashMap<Ident, Name>,
85 /// The items being lowered are collected here.
86 items: BTreeMap<NodeId, hir::Item>,
88 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
89 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
90 bodies: BTreeMap<hir::BodyId, hir::Body>,
91 exported_macros: Vec<hir::MacroDef>,
93 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
94 trait_default_impl: BTreeMap<DefId, NodeId>,
98 catch_scopes: Vec<NodeId>,
99 loop_scopes: Vec<NodeId>,
100 is_in_loop_condition: bool,
102 type_def_lifetime_params: DefIdMap<usize>,
104 current_hir_id_owner: Vec<(DefIndex, u32)>,
105 item_local_id_counters: NodeMap<u32>,
106 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
110 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
111 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
113 /// Obtain the resolution for a node id
114 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
116 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
117 /// This should only return `None` during testing.
118 fn definitions(&mut self) -> &mut Definitions;
121 pub fn lower_crate(sess: &Session,
123 resolver: &mut Resolver)
125 // We're constructing the HIR here; we don't care what we will
126 // read, since we haven't even constructed the *input* to
128 let _ignore = sess.dep_graph.in_ignore();
131 crate_root: std_inject::injected_crate_name(krate),
135 name_map: FxHashMap(),
136 items: BTreeMap::new(),
137 trait_items: BTreeMap::new(),
138 impl_items: BTreeMap::new(),
139 bodies: BTreeMap::new(),
140 trait_impls: BTreeMap::new(),
141 trait_default_impl: BTreeMap::new(),
142 exported_macros: Vec::new(),
143 catch_scopes: Vec::new(),
144 loop_scopes: Vec::new(),
145 is_in_loop_condition: false,
146 type_def_lifetime_params: DefIdMap(),
147 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
148 item_local_id_counters: NodeMap(),
149 node_id_to_hir_id: IndexVec::new(),
154 #[derive(Copy, Clone, PartialEq, Eq)]
156 /// Any path in a type context.
158 /// The `module::Type` in `module::Type::method` in an expression.
162 struct LoweredNodeId {
167 enum ParenthesizedGenericArgs {
173 impl<'a> LoweringContext<'a> {
174 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
175 /// Full-crate AST visitor that inserts into a fresh
176 /// `LoweringContext` any information that may be
177 /// needed from arbitrary locations in the crate.
178 /// E.g. The number of lifetime generic parameters
179 /// declared for every type and trait definition.
180 struct MiscCollector<'lcx, 'interner: 'lcx> {
181 lctx: &'lcx mut LoweringContext<'interner>,
184 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
185 fn visit_item(&mut self, item: &'lcx Item) {
186 self.lctx.allocate_hir_id_counter(item.id, item);
189 ItemKind::Struct(_, ref generics) |
190 ItemKind::Union(_, ref generics) |
191 ItemKind::Enum(_, ref generics) |
192 ItemKind::Ty(_, ref generics) |
193 ItemKind::Trait(_, ref generics, ..) => {
194 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
195 let count = generics.lifetimes.len();
196 self.lctx.type_def_lifetime_params.insert(def_id, count);
200 visit::walk_item(self, item);
203 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
204 self.lctx.allocate_hir_id_counter(item.id, item);
205 visit::walk_trait_item(self, item);
208 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
209 self.lctx.allocate_hir_id_counter(item.id, item);
210 visit::walk_impl_item(self, item);
214 struct ItemLowerer<'lcx, 'interner: 'lcx> {
215 lctx: &'lcx mut LoweringContext<'interner>,
218 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
219 fn visit_item(&mut self, item: &'lcx Item) {
220 let mut item_lowered = true;
221 self.lctx.with_hir_id_owner(item.id, |lctx| {
222 if let Some(hir_item) = lctx.lower_item(item) {
223 lctx.items.insert(item.id, hir_item);
225 item_lowered = false;
230 visit::walk_item(self, item);
234 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
235 self.lctx.with_hir_id_owner(item.id, |lctx| {
236 let id = hir::TraitItemId { node_id: item.id };
237 let hir_item = lctx.lower_trait_item(item);
238 lctx.trait_items.insert(id, hir_item);
241 visit::walk_trait_item(self, item);
244 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
245 self.lctx.with_hir_id_owner(item.id, |lctx| {
246 let id = hir::ImplItemId { node_id: item.id };
247 let hir_item = lctx.lower_impl_item(item);
248 lctx.impl_items.insert(id, hir_item);
250 visit::walk_impl_item(self, item);
254 self.lower_node_id(CRATE_NODE_ID);
255 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
257 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
258 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
260 let module = self.lower_mod(&c.module);
261 let attrs = self.lower_attrs(&c.attrs);
262 let body_ids = body_ids(&self.bodies);
266 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
272 exported_macros: hir::HirVec::from(self.exported_macros),
274 trait_items: self.trait_items,
275 impl_items: self.impl_items,
278 trait_impls: self.trait_impls,
279 trait_default_impl: self.trait_default_impl,
283 fn allocate_hir_id_counter<T: Debug>(&mut self,
286 if self.item_local_id_counters.insert(owner, 0).is_some() {
287 bug!("Tried to allocate item_local_id_counter for {:?} twice", debug);
289 // Always allocate the first HirId for the owner itself
290 self.lower_node_id_with_owner(owner, owner);
293 fn lower_node_id_generic<F>(&mut self,
297 where F: FnOnce(&mut Self) -> hir::HirId
299 if ast_node_id == DUMMY_NODE_ID {
300 return LoweredNodeId {
301 node_id: DUMMY_NODE_ID,
302 hir_id: hir::DUMMY_HIR_ID,
306 let min_size = ast_node_id.as_usize() + 1;
308 if min_size > self.node_id_to_hir_id.len() {
309 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
312 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
314 if existing_hir_id == hir::DUMMY_HIR_ID {
315 // Generate a new HirId
316 let hir_id = alloc_hir_id(self);
317 self.node_id_to_hir_id[ast_node_id] = hir_id;
319 node_id: ast_node_id,
324 node_id: ast_node_id,
325 hir_id: existing_hir_id,
330 fn with_hir_id_owner<F>(&mut self, owner: NodeId, f: F)
331 where F: FnOnce(&mut Self)
333 let counter = self.item_local_id_counters
334 .insert(owner, HIR_ID_COUNTER_LOCKED)
336 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
337 self.current_hir_id_owner.push((def_index, counter));
339 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
341 debug_assert!(def_index == new_def_index);
342 debug_assert!(new_counter >= counter);
344 let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
345 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
348 /// This method allocates a new HirId for the given NodeId and stores it in
349 /// the LoweringContext's NodeId => HirId map.
350 /// Take care not to call this method if the resulting HirId is then not
351 /// actually used in the HIR, as that would trigger an assertion in the
352 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
353 /// properly. Calling the method twice with the same NodeId is fine though.
354 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
355 self.lower_node_id_generic(ast_node_id, |this| {
356 let &mut (def_index, ref mut local_id_counter) = this.current_hir_id_owner
359 let local_id = *local_id_counter;
360 *local_id_counter += 1;
363 local_id: hir::ItemLocalId(local_id),
368 fn lower_node_id_with_owner(&mut self,
372 self.lower_node_id_generic(ast_node_id, |this| {
373 let local_id_counter = this.item_local_id_counters
376 let local_id = *local_id_counter;
378 // We want to be sure not to modify the counter in the map while it
379 // is also on the stack. Otherwise we'll get lost updates when writing
380 // back from the stack to the map.
381 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
383 *local_id_counter += 1;
384 let def_index = this.resolver.definitions().opt_def_index(owner).unwrap();
388 local_id: hir::ItemLocalId(local_id),
393 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>)
395 let body = hir::Body {
396 arguments: decl.map_or(hir_vec![], |decl| {
397 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
399 is_generator: self.is_generator,
403 self.bodies.insert(id, body);
407 fn next_id(&mut self) -> LoweredNodeId {
408 self.lower_node_id(self.sess.next_node_id())
411 fn expect_full_def(&mut self, id: NodeId) -> Def {
412 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
413 if pr.unresolved_segments() != 0 {
414 bug!("path not fully resolved: {:?}", pr);
420 fn diagnostic(&self) -> &errors::Handler {
421 self.sess.diagnostic()
424 fn str_to_ident(&self, s: &'static str) -> Name {
428 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span
430 let mark = Mark::fresh(Mark::root());
431 mark.set_expn_info(codemap::ExpnInfo {
433 callee: codemap::NameAndSpan {
434 format: codemap::CompilerDesugaring(reason),
436 allow_internal_unstable: true,
437 allow_internal_unsafe: false,
440 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
443 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
444 where F: FnOnce(&mut LoweringContext) -> T
446 let len = self.catch_scopes.len();
447 self.catch_scopes.push(catch_id);
449 let result = f(self);
450 assert_eq!(len + 1, self.catch_scopes.len(),
451 "catch scopes should be added and removed in stack order");
453 self.catch_scopes.pop().unwrap();
458 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
459 where F: FnOnce(&mut LoweringContext) -> hir::Expr
461 let prev = mem::replace(&mut self.is_generator, false);
462 let result = f(self);
463 let r = self.record_body(result, decl);
464 self.is_generator = prev;
468 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
469 where F: FnOnce(&mut LoweringContext) -> T
471 // We're no longer in the base loop's condition; we're in another loop.
472 let was_in_loop_condition = self.is_in_loop_condition;
473 self.is_in_loop_condition = false;
475 let len = self.loop_scopes.len();
476 self.loop_scopes.push(loop_id);
478 let result = f(self);
479 assert_eq!(len + 1, self.loop_scopes.len(),
480 "Loop scopes should be added and removed in stack order");
482 self.loop_scopes.pop().unwrap();
484 self.is_in_loop_condition = was_in_loop_condition;
489 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
490 where F: FnOnce(&mut LoweringContext) -> T
492 let was_in_loop_condition = self.is_in_loop_condition;
493 self.is_in_loop_condition = true;
495 let result = f(self);
497 self.is_in_loop_condition = was_in_loop_condition;
502 fn with_new_scopes<T, F>(&mut self, f: F) -> T
503 where F: FnOnce(&mut LoweringContext) -> T
505 let was_in_loop_condition = self.is_in_loop_condition;
506 self.is_in_loop_condition = false;
508 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
509 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
510 let result = f(self);
511 self.catch_scopes = catch_scopes;
512 self.loop_scopes = loop_scopes;
514 self.is_in_loop_condition = was_in_loop_condition;
519 fn with_parent_def<T, F>(&mut self, parent_id: NodeId, f: F) -> T
520 where F: FnOnce(&mut LoweringContext) -> T
522 let old_def = self.parent_def;
524 let defs = self.resolver.definitions();
525 Some(defs.opt_def_index(parent_id).unwrap())
528 let result = f(self);
530 self.parent_def = old_def;
534 fn def_key(&mut self, id: DefId) -> DefKey {
536 self.resolver.definitions().def_key(id.index)
538 self.sess.cstore.def_key(id)
542 fn lower_ident(&mut self, ident: Ident) -> Name {
543 let ident = ident.modern();
544 if ident.ctxt == SyntaxContext::empty() {
547 *self.name_map.entry(ident).or_insert_with(|| Symbol::from_ident(ident))
550 fn lower_opt_sp_ident(&mut self, o_id: Option<Spanned<Ident>>) -> Option<Spanned<Name>> {
551 o_id.map(|sp_ident| respan(sp_ident.span, sp_ident.node.name))
554 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Spanned<Ident>)>)
558 Some((id, label_ident)) => {
559 let target = if let Def::Label(loop_id) = self.expect_full_def(id) {
560 hir::LoopIdResult::Ok(self.lower_node_id(loop_id).node_id)
562 hir::LoopIdResult::Err(hir::LoopIdError::UnresolvedLabel)
565 ident: Some(label_ident),
566 target_id: hir::ScopeTarget::Loop(target),
570 let loop_id = self.loop_scopes
572 .map(|innermost_loop_id| *innermost_loop_id);
576 target_id: hir::ScopeTarget::Loop(
577 loop_id.map(|id| Ok(self.lower_node_id(id).node_id))
578 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
585 fn lower_attrs(&mut self, attrs: &Vec<Attribute>) -> hir::HirVec<Attribute> {
589 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
591 attrs: self.lower_attrs(&arm.attrs),
592 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
593 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
594 body: P(self.lower_expr(&arm.body)),
598 fn lower_ty_binding(&mut self, b: &TypeBinding) -> hir::TypeBinding {
600 id: self.lower_node_id(b.id).node_id,
601 name: self.lower_ident(b.ident),
602 ty: self.lower_ty(&b.ty),
607 fn lower_ty(&mut self, t: &Ty) -> P<hir::Ty> {
608 let kind = match t.node {
609 TyKind::Infer => hir::TyInfer,
610 TyKind::Err => hir::TyErr,
611 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty)),
612 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt)),
613 TyKind::Rptr(ref region, ref mt) => {
614 let span = t.span.with_hi(t.span.lo());
615 let lifetime = match *region {
616 Some(ref lt) => self.lower_lifetime(lt),
617 None => self.elided_lifetime(span)
619 hir::TyRptr(lifetime, self.lower_mt(mt))
621 TyKind::BareFn(ref f) => {
622 hir::TyBareFn(P(hir::BareFnTy {
623 lifetimes: self.lower_lifetime_defs(&f.lifetimes),
624 unsafety: self.lower_unsafety(f.unsafety),
626 decl: self.lower_fn_decl(&f.decl),
629 TyKind::Never => hir::TyNever,
630 TyKind::Tup(ref tys) => {
631 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty)).collect())
633 TyKind::Paren(ref ty) => {
634 return self.lower_ty(ty);
636 TyKind::Path(ref qself, ref path) => {
637 let id = self.lower_node_id(t.id).node_id;
638 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit);
639 return self.ty_path(id, t.span, qpath);
641 TyKind::ImplicitSelf => {
642 hir::TyPath(hir::QPath::Resolved(None, P(hir::Path {
643 def: self.expect_full_def(t.id),
644 segments: hir_vec![hir::PathSegment {
645 name: keywords::SelfType.name(),
646 parameters: hir::PathParameters::none()
651 TyKind::Array(ref ty, ref length) => {
652 let length = self.lower_body(None, |this| this.lower_expr(length));
653 hir::TyArray(self.lower_ty(ty), length)
655 TyKind::Typeof(ref expr) => {
656 let expr = self.lower_body(None, |this| this.lower_expr(expr));
659 TyKind::TraitObject(ref bounds) => {
660 let mut lifetime_bound = None;
661 let bounds = bounds.iter().filter_map(|bound| {
663 TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
664 Some(self.lower_poly_trait_ref(ty))
666 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
667 RegionTyParamBound(ref lifetime) => {
668 if lifetime_bound.is_none() {
669 lifetime_bound = Some(self.lower_lifetime(lifetime));
675 let lifetime_bound = lifetime_bound.unwrap_or_else(|| {
676 self.elided_lifetime(t.span)
678 hir::TyTraitObject(bounds, lifetime_bound)
680 TyKind::ImplTrait(ref bounds) => {
681 hir::TyImplTrait(self.lower_bounds(bounds))
683 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
687 id: self.lower_node_id(t.id).node_id,
693 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
696 items: fm.items.iter().map(|x| self.lower_foreign_item(x)).collect(),
700 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
707 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
709 node: hir::Variant_ {
710 name: v.node.name.name,
711 attrs: self.lower_attrs(&v.node.attrs),
712 data: self.lower_variant_data(&v.node.data),
713 disr_expr: v.node.disr_expr.as_ref().map(|e| {
714 self.lower_body(None, |this| this.lower_expr(e))
721 fn lower_qpath(&mut self,
723 qself: &Option<QSelf>,
725 param_mode: ParamMode)
727 let qself_position = qself.as_ref().map(|q| q.position);
728 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty));
730 let resolution = self.resolver.get_resolution(id)
731 .unwrap_or(PathResolution::new(Def::Err));
733 let proj_start = p.segments.len() - resolution.unresolved_segments();
734 let path = P(hir::Path {
735 def: resolution.base_def(),
736 segments: p.segments[..proj_start].iter().enumerate().map(|(i, segment)| {
737 let param_mode = match (qself_position, param_mode) {
738 (Some(j), ParamMode::Optional) if i < j => {
739 // This segment is part of the trait path in a
740 // qualified path - one of `a`, `b` or `Trait`
741 // in `<X as a::b::Trait>::T::U::method`.
747 // Figure out if this is a type/trait segment,
748 // which may need lifetime elision performed.
749 let parent_def_id = |this: &mut Self, def_id: DefId| {
752 index: this.def_key(def_id).parent.expect("missing parent")
755 let type_def_id = match resolution.base_def() {
756 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
757 Some(parent_def_id(self, def_id))
759 Def::Variant(def_id) if i + 1 == proj_start => {
760 Some(parent_def_id(self, def_id))
762 Def::Struct(def_id) |
765 Def::TyAlias(def_id) |
766 Def::Trait(def_id) if i + 1 == proj_start => Some(def_id),
769 let parenthesized_generic_args = match resolution.base_def() {
770 // `a::b::Trait(Args)`
771 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
772 // `a::b::Trait(Args)::TraitItem`
774 Def::AssociatedConst(..) |
775 Def::AssociatedTy(..) if i + 2 == proj_start => ParenthesizedGenericArgs::Ok,
776 // Avoid duplicated errors
777 Def::Err => ParenthesizedGenericArgs::Ok,
779 Def::Struct(..) | Def::Enum(..) | Def::Union(..) | Def::TyAlias(..) |
780 Def::Variant(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Err,
781 // A warning for now, for compatibility reasons
782 _ => ParenthesizedGenericArgs::Warn,
785 let num_lifetimes = type_def_id.map_or(0, |def_id| {
786 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
789 assert!(!def_id.is_local());
790 let n = self.sess.cstore.item_generics_cloned_untracked(def_id).regions.len();
791 self.type_def_lifetime_params.insert(def_id, n);
794 self.lower_path_segment(p.span, segment, param_mode, num_lifetimes,
795 parenthesized_generic_args)
800 // Simple case, either no projections, or only fully-qualified.
801 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
802 if resolution.unresolved_segments() == 0 {
803 return hir::QPath::Resolved(qself, path);
806 // Create the innermost type that we're projecting from.
807 let mut ty = if path.segments.is_empty() {
808 // If the base path is empty that means there exists a
809 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
810 qself.expect("missing QSelf for <T>::...")
812 // Otherwise, the base path is an implicit `Self` type path,
813 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
814 // `<I as Iterator>::Item::default`.
815 let new_id = self.next_id().node_id;
816 self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
819 // Anything after the base path are associated "extensions",
820 // out of which all but the last one are associated types,
821 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
822 // * base path is `std::vec::Vec<T>`
823 // * "extensions" are `IntoIter`, `Item` and `clone`
825 // 1. `std::vec::Vec<T>` (created above)
826 // 2. `<std::vec::Vec<T>>::IntoIter`
827 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
828 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
829 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
830 let segment = P(self.lower_path_segment(p.span, segment, param_mode, 0,
831 ParenthesizedGenericArgs::Warn));
832 let qpath = hir::QPath::TypeRelative(ty, segment);
834 // It's finished, return the extension of the right node type.
835 if i == p.segments.len() - 1 {
839 // Wrap the associated extension in another type node.
840 let new_id = self.next_id().node_id;
841 ty = self.ty_path(new_id, p.span, qpath);
844 // Should've returned in the for loop above.
845 span_bug!(p.span, "lower_qpath: no final extension segment in {}..{}",
846 proj_start, p.segments.len())
849 fn lower_path_extra(&mut self,
853 param_mode: ParamMode,
854 defaults_to_global: bool)
856 let mut segments = p.segments.iter();
857 if defaults_to_global && p.is_global() {
862 def: self.expect_full_def(id),
863 segments: segments.map(|segment| {
864 self.lower_path_segment(p.span, segment, param_mode, 0,
865 ParenthesizedGenericArgs::Err)
866 }).chain(name.map(|name| {
869 parameters: hir::PathParameters::none()
876 fn lower_path(&mut self,
879 param_mode: ParamMode,
880 defaults_to_global: bool)
882 self.lower_path_extra(id, p, None, param_mode, defaults_to_global)
885 fn lower_path_segment(&mut self,
887 segment: &PathSegment,
888 param_mode: ParamMode,
889 expected_lifetimes: usize,
890 parenthesized_generic_args: ParenthesizedGenericArgs)
891 -> hir::PathSegment {
892 let mut parameters = if let Some(ref parameters) = segment.parameters {
893 let msg = "parenthesized parameters may only be used with a trait";
895 PathParameters::AngleBracketed(ref data) => {
896 self.lower_angle_bracketed_parameter_data(data, param_mode)
898 PathParameters::Parenthesized(ref data) => match parenthesized_generic_args {
899 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
900 ParenthesizedGenericArgs::Warn => {
901 self.sess.buffer_lint(PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
902 CRATE_NODE_ID, data.span, msg.into());
903 hir::PathParameters::none()
905 ParenthesizedGenericArgs::Err => {
906 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
907 .span_label(data.span, "only traits may use parentheses").emit();
908 hir::PathParameters::none()
913 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode)
916 if !parameters.parenthesized && parameters.lifetimes.is_empty() {
917 parameters.lifetimes = (0..expected_lifetimes).map(|_| {
918 self.elided_lifetime(path_span)
923 name: self.lower_ident(segment.identifier),
928 fn lower_angle_bracketed_parameter_data(&mut self,
929 data: &AngleBracketedParameterData,
930 param_mode: ParamMode)
931 -> hir::PathParameters {
932 let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings, .. } = data;
933 hir::PathParameters {
934 lifetimes: self.lower_lifetimes(lifetimes),
935 types: types.iter().map(|ty| self.lower_ty(ty)).collect(),
936 infer_types: types.is_empty() && param_mode == ParamMode::Optional,
937 bindings: bindings.iter().map(|b| self.lower_ty_binding(b)).collect(),
938 parenthesized: false,
942 fn lower_parenthesized_parameter_data(&mut self,
943 data: &ParenthesizedParameterData)
944 -> hir::PathParameters {
945 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
946 let inputs = inputs.iter().map(|ty| self.lower_ty(ty)).collect();
947 let mk_tup = |this: &mut Self, tys, span| {
948 P(hir::Ty { node: hir::TyTup(tys), id: this.next_id().node_id, span })
951 hir::PathParameters {
952 lifetimes: hir::HirVec::new(),
953 types: hir_vec![mk_tup(self, inputs, span)],
955 bindings: hir_vec![hir::TypeBinding {
956 id: self.next_id().node_id,
957 name: Symbol::intern(FN_OUTPUT_NAME),
958 ty: output.as_ref().map(|ty| self.lower_ty(&ty))
959 .unwrap_or_else(|| mk_tup(self, hir::HirVec::new(), span)),
960 span: output.as_ref().map_or(span, |ty| ty.span),
966 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
967 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
971 ty: l.ty.as_ref().map(|t| self.lower_ty(t)),
972 pat: self.lower_pat(&l.pat),
973 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
975 attrs: l.attrs.clone(),
976 source: hir::LocalSource::Normal,
980 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
982 Mutability::Mutable => hir::MutMutable,
983 Mutability::Immutable => hir::MutImmutable,
987 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
988 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
992 pat: self.lower_pat(&arg.pat),
996 fn lower_fn_args_to_names(&mut self, decl: &FnDecl)
997 -> hir::HirVec<Spanned<Name>> {
998 decl.inputs.iter().map(|arg| {
1000 PatKind::Ident(_, ident, None) => {
1001 respan(ident.span, ident.node.name)
1003 _ => respan(arg.pat.span, keywords::Invalid.name()),
1008 fn lower_fn_decl(&mut self, decl: &FnDecl) -> P<hir::FnDecl> {
1010 inputs: decl.inputs.iter().map(|arg| self.lower_ty(&arg.ty)).collect(),
1011 output: match decl.output {
1012 FunctionRetTy::Ty(ref ty) => hir::Return(self.lower_ty(ty)),
1013 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1015 variadic: decl.variadic,
1016 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| {
1018 TyKind::ImplicitSelf => true,
1019 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1026 fn lower_ty_param_bound(&mut self, tpb: &TyParamBound) -> hir::TyParamBound {
1028 TraitTyParamBound(ref ty, modifier) => {
1029 hir::TraitTyParamBound(self.lower_poly_trait_ref(ty),
1030 self.lower_trait_bound_modifier(modifier))
1032 RegionTyParamBound(ref lifetime) => {
1033 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
1038 fn lower_ty_param(&mut self, tp: &TyParam, add_bounds: &[TyParamBound]) -> hir::TyParam {
1039 let mut name = self.lower_ident(tp.ident);
1041 // Don't expose `Self` (recovered "keyword used as ident" parse error).
1042 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1043 // Instead, use gensym("Self") to create a distinct name that looks the same.
1044 if name == keywords::SelfType.name() {
1045 name = Symbol::gensym("Self");
1048 let mut bounds = self.lower_bounds(&tp.bounds);
1049 if !add_bounds.is_empty() {
1050 bounds = bounds.into_iter().chain(self.lower_bounds(add_bounds).into_iter()).collect();
1054 id: self.lower_node_id(tp.id).node_id,
1057 default: tp.default.as_ref().map(|x| self.lower_ty(x)),
1059 pure_wrt_drop: tp.attrs.iter().any(|attr| attr.check_name("may_dangle")),
1063 fn lower_ty_params(&mut self, tps: &Vec<TyParam>, add_bounds: &NodeMap<Vec<TyParamBound>>)
1064 -> hir::HirVec<hir::TyParam> {
1065 tps.iter().map(|tp| {
1066 self.lower_ty_param(tp, add_bounds.get(&tp.id).map_or(&[][..], |x| &x))
1070 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1072 id: self.lower_node_id(l.id).node_id,
1073 name: self.lower_ident(l.ident),
1078 fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef {
1080 lifetime: self.lower_lifetime(&l.lifetime),
1081 bounds: self.lower_lifetimes(&l.bounds),
1082 pure_wrt_drop: l.attrs.iter().any(|attr| attr.check_name("may_dangle")),
1086 fn lower_lifetimes(&mut self, lts: &Vec<Lifetime>) -> hir::HirVec<hir::Lifetime> {
1087 lts.iter().map(|l| self.lower_lifetime(l)).collect()
1090 fn lower_lifetime_defs(&mut self, lts: &Vec<LifetimeDef>) -> hir::HirVec<hir::LifetimeDef> {
1091 lts.iter().map(|l| self.lower_lifetime_def(l)).collect()
1094 fn lower_generics(&mut self, g: &Generics) -> hir::Generics {
1095 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1096 let mut add_bounds = NodeMap();
1097 for pred in &g.where_clause.predicates {
1098 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1099 'next_bound: for bound in &bound_pred.bounds {
1100 if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
1101 let report_error = |this: &mut Self| {
1102 this.diagnostic().span_err(bound_pred.bounded_ty.span,
1103 "`?Trait` bounds are only permitted at the \
1104 point where a type parameter is declared");
1106 // Check if the where clause type is a plain type parameter.
1107 match bound_pred.bounded_ty.node {
1108 TyKind::Path(None, ref path)
1109 if path.segments.len() == 1 &&
1110 bound_pred.bound_lifetimes.is_empty() => {
1111 if let Some(Def::TyParam(def_id)) =
1112 self.resolver.get_resolution(bound_pred.bounded_ty.id)
1113 .map(|d| d.base_def()) {
1114 if let Some(node_id) =
1115 self.resolver.definitions().as_local_node_id(def_id) {
1116 for ty_param in &g.ty_params {
1117 if node_id == ty_param.id {
1118 add_bounds.entry(ty_param.id).or_insert(Vec::new())
1119 .push(bound.clone());
1120 continue 'next_bound;
1127 _ => report_error(self)
1135 ty_params: self.lower_ty_params(&g.ty_params, &add_bounds),
1136 lifetimes: self.lower_lifetime_defs(&g.lifetimes),
1137 where_clause: self.lower_where_clause(&g.where_clause),
1142 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
1144 id: self.lower_node_id(wc.id).node_id,
1145 predicates: wc.predicates
1147 .map(|predicate| self.lower_where_predicate(predicate))
1152 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
1154 WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
1158 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1159 bound_lifetimes: self.lower_lifetime_defs(bound_lifetimes),
1160 bounded_ty: self.lower_ty(bounded_ty),
1161 bounds: bounds.iter().filter_map(|bound| match *bound {
1162 // Ignore `?Trait` bounds, they were copied into type parameters already.
1163 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1164 _ => Some(self.lower_ty_param_bound(bound))
1169 WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
1172 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1174 lifetime: self.lower_lifetime(lifetime),
1175 bounds: bounds.iter().map(|bound| self.lower_lifetime(bound)).collect(),
1178 WherePredicate::EqPredicate(WhereEqPredicate{ id,
1182 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1183 id: self.lower_node_id(id).node_id,
1184 lhs_ty: self.lower_ty(lhs_ty),
1185 rhs_ty: self.lower_ty(rhs_ty),
1192 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
1194 VariantData::Struct(ref fields, id) => {
1195 hir::VariantData::Struct(fields.iter()
1197 .map(|f| self.lower_struct_field(f))
1199 self.lower_node_id(id).node_id)
1201 VariantData::Tuple(ref fields, id) => {
1202 hir::VariantData::Tuple(fields.iter()
1204 .map(|f| self.lower_struct_field(f))
1206 self.lower_node_id(id).node_id)
1208 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
1212 fn lower_trait_ref(&mut self, p: &TraitRef) -> hir::TraitRef {
1213 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit) {
1214 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
1215 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath)
1219 ref_id: self.lower_node_id(p.ref_id).node_id,
1223 fn lower_poly_trait_ref(&mut self, p: &PolyTraitRef) -> hir::PolyTraitRef {
1225 bound_lifetimes: self.lower_lifetime_defs(&p.bound_lifetimes),
1226 trait_ref: self.lower_trait_ref(&p.trait_ref),
1231 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
1234 id: self.lower_node_id(f.id).node_id,
1235 name: self.lower_ident(match f.ident {
1236 Some(ident) => ident,
1237 // FIXME(jseyfried) positional field hygiene
1238 None => Ident { name: Symbol::intern(&index.to_string()), ctxt: f.span.ctxt() },
1240 vis: self.lower_visibility(&f.vis, None),
1241 ty: self.lower_ty(&f.ty),
1242 attrs: self.lower_attrs(&f.attrs),
1246 fn lower_field(&mut self, f: &Field) -> hir::Field {
1248 name: respan(f.ident.span, self.lower_ident(f.ident.node)),
1249 expr: P(self.lower_expr(&f.expr)),
1251 is_shorthand: f.is_shorthand,
1255 fn lower_mt(&mut self, mt: &MutTy) -> hir::MutTy {
1257 ty: self.lower_ty(&mt.ty),
1258 mutbl: self.lower_mutability(mt.mutbl),
1262 fn lower_bounds(&mut self, bounds: &[TyParamBound]) -> hir::TyParamBounds {
1263 bounds.iter().map(|bound| self.lower_ty_param_bound(bound)).collect()
1266 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
1267 let mut expr = None;
1269 let mut stmts = vec![];
1271 for (index, stmt) in b.stmts.iter().enumerate() {
1272 if index == b.stmts.len() - 1 {
1273 if let StmtKind::Expr(ref e) = stmt.node {
1274 expr = Some(P(self.lower_expr(e)));
1276 stmts.extend(self.lower_stmt(stmt));
1279 stmts.extend(self.lower_stmt(stmt));
1283 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
1288 stmts: stmts.into(),
1290 rules: self.lower_block_check_mode(&b.rules),
1296 fn lower_item_kind(&mut self,
1299 attrs: &hir::HirVec<Attribute>,
1300 vis: &mut hir::Visibility,
1304 ItemKind::ExternCrate(string) => hir::ItemExternCrate(string),
1305 ItemKind::Use(ref view_path) => {
1306 let path = match view_path.node {
1307 ViewPathSimple(_, ref path) => path,
1308 ViewPathGlob(ref path) => path,
1309 ViewPathList(ref path, ref path_list_idents) => {
1310 for &Spanned { node: ref import, span } in path_list_idents {
1311 // `use a::{self as x, b as y};` lowers to
1312 // `use a as x; use a::b as y;`
1313 let mut ident = import.name;
1314 let suffix = if ident.name == keywords::SelfValue.name() {
1315 if let Some(last) = path.segments.last() {
1316 ident = last.identifier;
1323 let mut path = self.lower_path_extra(import.id, path, suffix,
1324 ParamMode::Explicit, true);
1327 self.allocate_hir_id_counter(import.id, import);
1329 node_id: import_node_id,
1330 hir_id: import_hir_id,
1331 } = self.lower_node_id(import.id);
1333 self.with_hir_id_owner(import_node_id, |this| {
1334 let vis = match *vis {
1335 hir::Visibility::Public => hir::Visibility::Public,
1336 hir::Visibility::Crate => hir::Visibility::Crate,
1337 hir::Visibility::Inherited => hir::Visibility::Inherited,
1338 hir::Visibility::Restricted { ref path, id: _ } => {
1339 hir::Visibility::Restricted {
1341 // We are allocating a new NodeId here
1342 id: this.next_id().node_id,
1347 this.items.insert(import_node_id, hir::Item {
1349 hir_id: import_hir_id,
1350 name: import.rename.unwrap_or(ident).name,
1351 attrs: attrs.clone(),
1352 node: hir::ItemUse(P(path), hir::UseKind::Single),
1361 let path = P(self.lower_path(id, path, ParamMode::Explicit, true));
1362 let kind = match view_path.node {
1363 ViewPathSimple(ident, _) => {
1365 hir::UseKind::Single
1367 ViewPathGlob(_) => {
1370 ViewPathList(..) => {
1371 // Privatize the degenerate import base, used only to check
1372 // the stability of `use a::{};`, to avoid it showing up as
1373 // a reexport by accident when `pub`, e.g. in documentation.
1374 *vis = hir::Inherited;
1375 hir::UseKind::ListStem
1378 hir::ItemUse(path, kind)
1380 ItemKind::Static(ref t, m, ref e) => {
1381 let value = self.lower_body(None, |this| this.lower_expr(e));
1382 hir::ItemStatic(self.lower_ty(t),
1383 self.lower_mutability(m),
1386 ItemKind::Const(ref t, ref e) => {
1387 let value = self.lower_body(None, |this| this.lower_expr(e));
1388 hir::ItemConst(self.lower_ty(t), value)
1390 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
1391 self.with_new_scopes(|this| {
1392 let body_id = this.lower_body(Some(decl), |this| {
1393 let body = this.lower_block(body, false);
1394 this.expr_block(body, ThinVec::new())
1396 hir::ItemFn(this.lower_fn_decl(decl),
1397 this.lower_unsafety(unsafety),
1398 this.lower_constness(constness),
1400 this.lower_generics(generics),
1404 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
1405 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
1406 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
1407 ItemKind::Ty(ref t, ref generics) => {
1408 hir::ItemTy(self.lower_ty(t), self.lower_generics(generics))
1410 ItemKind::Enum(ref enum_definition, ref generics) => {
1411 hir::ItemEnum(hir::EnumDef {
1412 variants: enum_definition.variants
1414 .map(|x| self.lower_variant(x))
1417 self.lower_generics(generics))
1419 ItemKind::Struct(ref struct_def, ref generics) => {
1420 let struct_def = self.lower_variant_data(struct_def);
1421 hir::ItemStruct(struct_def, self.lower_generics(generics))
1423 ItemKind::Union(ref vdata, ref generics) => {
1424 let vdata = self.lower_variant_data(vdata);
1425 hir::ItemUnion(vdata, self.lower_generics(generics))
1427 ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1428 let trait_ref = self.lower_trait_ref(trait_ref);
1430 if let Def::Trait(def_id) = trait_ref.path.def {
1431 self.trait_default_impl.insert(def_id, id);
1434 hir::ItemDefaultImpl(self.lower_unsafety(unsafety),
1437 ItemKind::Impl(unsafety,
1443 ref impl_items) => {
1444 let new_impl_items = impl_items.iter()
1445 .map(|item| self.lower_impl_item_ref(item))
1447 let ifce = ifce.as_ref().map(|trait_ref| self.lower_trait_ref(trait_ref));
1449 if let Some(ref trait_ref) = ifce {
1450 if let Def::Trait(def_id) = trait_ref.path.def {
1451 self.trait_impls.entry(def_id).or_insert(vec![]).push(id);
1455 hir::ItemImpl(self.lower_unsafety(unsafety),
1456 self.lower_impl_polarity(polarity),
1457 self.lower_defaultness(defaultness, true /* [1] */),
1458 self.lower_generics(generics),
1463 ItemKind::Trait(unsafety, ref generics, ref bounds, ref items) => {
1464 let bounds = self.lower_bounds(bounds);
1465 let items = items.iter().map(|item| self.lower_trait_item_ref(item)).collect();
1466 hir::ItemTrait(self.lower_unsafety(unsafety),
1467 self.lower_generics(generics),
1471 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
1474 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
1475 // not cause an assertion failure inside the `lower_defaultness` function
1478 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
1479 self.with_parent_def(i.id, |this| {
1480 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(i.id);
1485 name: this.lower_ident(i.ident),
1486 attrs: this.lower_attrs(&i.attrs),
1487 node: match i.node {
1488 TraitItemKind::Const(ref ty, ref default) => {
1489 hir::TraitItemKind::Const(this.lower_ty(ty),
1490 default.as_ref().map(|x| {
1491 this.lower_body(None, |this| this.lower_expr(x))
1494 TraitItemKind::Method(ref sig, None) => {
1495 let names = this.lower_fn_args_to_names(&sig.decl);
1496 hir::TraitItemKind::Method(this.lower_method_sig(sig),
1497 hir::TraitMethod::Required(names))
1499 TraitItemKind::Method(ref sig, Some(ref body)) => {
1500 let body_id = this.lower_body(Some(&sig.decl), |this| {
1501 let body = this.lower_block(body, false);
1502 this.expr_block(body, ThinVec::new())
1504 hir::TraitItemKind::Method(this.lower_method_sig(sig),
1505 hir::TraitMethod::Provided(body_id))
1507 TraitItemKind::Type(ref bounds, ref default) => {
1508 hir::TraitItemKind::Type(this.lower_bounds(bounds),
1509 default.as_ref().map(|x| this.lower_ty(x)))
1511 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
1518 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
1519 let (kind, has_default) = match i.node {
1520 TraitItemKind::Const(_, ref default) => {
1521 (hir::AssociatedItemKind::Const, default.is_some())
1523 TraitItemKind::Type(_, ref default) => {
1524 (hir::AssociatedItemKind::Type, default.is_some())
1526 TraitItemKind::Method(ref sig, ref default) => {
1527 (hir::AssociatedItemKind::Method {
1528 has_self: sig.decl.has_self(),
1529 }, default.is_some())
1531 TraitItemKind::Macro(..) => unimplemented!(),
1534 id: hir::TraitItemId { node_id: i.id },
1535 name: self.lower_ident(i.ident),
1537 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
1542 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
1543 self.with_parent_def(i.id, |this| {
1544 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(i.id);
1549 name: this.lower_ident(i.ident),
1550 attrs: this.lower_attrs(&i.attrs),
1551 vis: this.lower_visibility(&i.vis, None),
1552 defaultness: this.lower_defaultness(i.defaultness, true /* [1] */),
1553 node: match i.node {
1554 ImplItemKind::Const(ref ty, ref expr) => {
1555 let body_id = this.lower_body(None, |this| this.lower_expr(expr));
1556 hir::ImplItemKind::Const(this.lower_ty(ty), body_id)
1558 ImplItemKind::Method(ref sig, ref body) => {
1559 let body_id = this.lower_body(Some(&sig.decl), |this| {
1560 let body = this.lower_block(body, false);
1561 this.expr_block(body, ThinVec::new())
1563 hir::ImplItemKind::Method(this.lower_method_sig(sig), body_id)
1565 ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(this.lower_ty(ty)),
1566 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
1572 // [1] since `default impl` is not yet implemented, this is always true in impls
1575 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
1577 id: hir::ImplItemId { node_id: i.id },
1578 name: self.lower_ident(i.ident),
1580 vis: self.lower_visibility(&i.vis, Some(i.id)),
1581 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
1582 kind: match i.node {
1583 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
1584 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
1585 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
1586 has_self: sig.decl.has_self(),
1588 ImplItemKind::Macro(..) => unimplemented!(),
1592 // [1] since `default impl` is not yet implemented, this is always true in impls
1595 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
1598 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
1602 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
1604 ItemKind::Use(ref view_path) => {
1605 if let ViewPathList(_, ref imports) = view_path.node {
1606 return iter::once(i.id).chain(imports.iter().map(|import| import.node.id))
1607 .map(|id| hir::ItemId { id: id }).collect();
1610 ItemKind::MacroDef(..) => return SmallVector::new(),
1613 SmallVector::one(hir::ItemId { id: i.id })
1616 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
1617 let mut name = i.ident.name;
1618 let mut vis = self.lower_visibility(&i.vis, None);
1619 let attrs = self.lower_attrs(&i.attrs);
1620 if let ItemKind::MacroDef(ref def) = i.node {
1621 if !def.legacy || i.attrs.iter().any(|attr| attr.path == "macro_export") {
1622 self.exported_macros.push(hir::MacroDef {
1635 let node = self.with_parent_def(i.id, |this| {
1636 this.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node)
1639 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
1652 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
1653 self.with_parent_def(i.id, |this| {
1655 id: this.lower_node_id(i.id).node_id,
1657 attrs: this.lower_attrs(&i.attrs),
1658 node: match i.node {
1659 ForeignItemKind::Fn(ref fdec, ref generics) => {
1660 hir::ForeignItemFn(this.lower_fn_decl(fdec),
1661 this.lower_fn_args_to_names(fdec),
1662 this.lower_generics(generics))
1664 ForeignItemKind::Static(ref t, m) => {
1665 hir::ForeignItemStatic(this.lower_ty(t), m)
1668 vis: this.lower_visibility(&i.vis, None),
1674 fn lower_method_sig(&mut self, sig: &MethodSig) -> hir::MethodSig {
1676 generics: self.lower_generics(&sig.generics),
1678 unsafety: self.lower_unsafety(sig.unsafety),
1679 constness: self.lower_constness(sig.constness),
1680 decl: self.lower_fn_decl(&sig.decl),
1684 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
1686 Unsafety::Unsafe => hir::Unsafety::Unsafe,
1687 Unsafety::Normal => hir::Unsafety::Normal,
1691 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
1693 Constness::Const => hir::Constness::Const,
1694 Constness::NotConst => hir::Constness::NotConst,
1698 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
1700 UnOp::Deref => hir::UnDeref,
1701 UnOp::Not => hir::UnNot,
1702 UnOp::Neg => hir::UnNeg,
1706 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
1708 node: match b.node {
1709 BinOpKind::Add => hir::BiAdd,
1710 BinOpKind::Sub => hir::BiSub,
1711 BinOpKind::Mul => hir::BiMul,
1712 BinOpKind::Div => hir::BiDiv,
1713 BinOpKind::Rem => hir::BiRem,
1714 BinOpKind::And => hir::BiAnd,
1715 BinOpKind::Or => hir::BiOr,
1716 BinOpKind::BitXor => hir::BiBitXor,
1717 BinOpKind::BitAnd => hir::BiBitAnd,
1718 BinOpKind::BitOr => hir::BiBitOr,
1719 BinOpKind::Shl => hir::BiShl,
1720 BinOpKind::Shr => hir::BiShr,
1721 BinOpKind::Eq => hir::BiEq,
1722 BinOpKind::Lt => hir::BiLt,
1723 BinOpKind::Le => hir::BiLe,
1724 BinOpKind::Ne => hir::BiNe,
1725 BinOpKind::Ge => hir::BiGe,
1726 BinOpKind::Gt => hir::BiGt,
1732 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
1733 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
1738 node: match p.node {
1739 PatKind::Wild => hir::PatKind::Wild,
1740 PatKind::Ident(ref binding_mode, pth1, ref sub) => {
1741 self.with_parent_def(p.id, |this| {
1742 match this.resolver.get_resolution(p.id).map(|d| d.base_def()) {
1743 // `None` can occur in body-less function signatures
1744 def @ None | def @ Some(Def::Local(_)) => {
1745 let def_id = def.map(|d| d.def_id()).unwrap_or_else(|| {
1746 this.resolver.definitions().local_def_id(p.id)
1748 hir::PatKind::Binding(this.lower_binding_mode(binding_mode),
1750 respan(pth1.span, pth1.node.name),
1751 sub.as_ref().map(|x| this.lower_pat(x)))
1754 hir::PatKind::Path(hir::QPath::Resolved(None, P(hir::Path {
1758 hir::PathSegment::from_name(pth1.node.name)
1765 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
1766 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
1767 let qpath = self.lower_qpath(p.id, &None, path, ParamMode::Optional);
1768 hir::PatKind::TupleStruct(qpath,
1769 pats.iter().map(|x| self.lower_pat(x)).collect(),
1772 PatKind::Path(ref qself, ref path) => {
1773 hir::PatKind::Path(self.lower_qpath(p.id, qself, path, ParamMode::Optional))
1775 PatKind::Struct(ref path, ref fields, etc) => {
1776 let qpath = self.lower_qpath(p.id, &None, path, ParamMode::Optional);
1778 let fs = fields.iter()
1782 node: hir::FieldPat {
1783 name: self.lower_ident(f.node.ident),
1784 pat: self.lower_pat(&f.node.pat),
1785 is_shorthand: f.node.is_shorthand,
1790 hir::PatKind::Struct(qpath, fs, etc)
1792 PatKind::Tuple(ref elts, ddpos) => {
1793 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
1795 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
1796 PatKind::Ref(ref inner, mutbl) => {
1797 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
1799 PatKind::Range(ref e1, ref e2, ref end) => {
1800 hir::PatKind::Range(P(self.lower_expr(e1)),
1801 P(self.lower_expr(e2)),
1802 self.lower_range_end(end))
1804 PatKind::Slice(ref before, ref slice, ref after) => {
1805 hir::PatKind::Slice(before.iter().map(|x| self.lower_pat(x)).collect(),
1806 slice.as_ref().map(|x| self.lower_pat(x)),
1807 after.iter().map(|x| self.lower_pat(x)).collect())
1809 PatKind::Mac(_) => panic!("Shouldn't exist here"),
1815 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
1817 RangeEnd::Included => hir::RangeEnd::Included,
1818 RangeEnd::Excluded => hir::RangeEnd::Excluded,
1822 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
1823 let kind = match e.node {
1825 // Eventually a desugaring for `box EXPR`
1826 // (similar to the desugaring above for `in PLACE BLOCK`)
1827 // should go here, desugaring
1831 // let mut place = BoxPlace::make_place();
1832 // let raw_place = Place::pointer(&mut place);
1833 // let value = $value;
1835 // ::std::ptr::write(raw_place, value);
1836 // Boxed::finalize(place)
1839 // But for now there are type-inference issues doing that.
1840 ExprKind::Box(ref inner) => {
1841 hir::ExprBox(P(self.lower_expr(inner)))
1844 // Desugar ExprBox: `in (PLACE) EXPR`
1845 ExprKind::InPlace(ref placer, ref value_expr) => {
1849 // let mut place = Placer::make_place(p);
1850 // let raw_place = Place::pointer(&mut place);
1852 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1853 // InPlace::finalize(place)
1855 let placer_expr = P(self.lower_expr(placer));
1856 let value_expr = P(self.lower_expr(value_expr));
1858 let placer_ident = self.str_to_ident("placer");
1859 let place_ident = self.str_to_ident("place");
1860 let p_ptr_ident = self.str_to_ident("p_ptr");
1862 let make_place = ["ops", "Placer", "make_place"];
1863 let place_pointer = ["ops", "Place", "pointer"];
1864 let move_val_init = ["intrinsics", "move_val_init"];
1865 let inplace_finalize = ["ops", "InPlace", "finalize"];
1868 self.allow_internal_unstable(CompilerDesugaringKind::BackArrow, e.span);
1869 let make_call = |this: &mut LoweringContext, p, args| {
1870 let path = P(this.expr_std_path(unstable_span, p, ThinVec::new()));
1871 P(this.expr_call(e.span, path, args))
1874 let mk_stmt_let = |this: &mut LoweringContext, bind, expr| {
1875 this.stmt_let(e.span, false, bind, expr)
1878 let mk_stmt_let_mut = |this: &mut LoweringContext, bind, expr| {
1879 this.stmt_let(e.span, true, bind, expr)
1882 // let placer = <placer_expr> ;
1883 let (s1, placer_binding) = {
1884 mk_stmt_let(self, placer_ident, placer_expr)
1887 // let mut place = Placer::make_place(placer);
1888 let (s2, place_binding) = {
1889 let placer = self.expr_ident(e.span, placer_ident, placer_binding);
1890 let call = make_call(self, &make_place, hir_vec![placer]);
1891 mk_stmt_let_mut(self, place_ident, call)
1894 // let p_ptr = Place::pointer(&mut place);
1895 let (s3, p_ptr_binding) = {
1896 let agent = P(self.expr_ident(e.span, place_ident, place_binding));
1897 let args = hir_vec![self.expr_mut_addr_of(e.span, agent)];
1898 let call = make_call(self, &place_pointer, args);
1899 mk_stmt_let(self, p_ptr_ident, call)
1902 // pop_unsafe!(EXPR));
1903 let pop_unsafe_expr = {
1904 self.signal_block_expr(hir_vec![],
1907 hir::PopUnsafeBlock(hir::CompilerGenerated),
1912 // std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1913 // InPlace::finalize(place)
1916 let ptr = self.expr_ident(e.span, p_ptr_ident, p_ptr_binding);
1917 let call_move_val_init =
1919 make_call(self, &move_val_init, hir_vec![ptr, pop_unsafe_expr]),
1920 self.next_id().node_id);
1921 let call_move_val_init = respan(e.span, call_move_val_init);
1923 let place = self.expr_ident(e.span, place_ident, place_binding);
1924 let call = make_call(self, &inplace_finalize, hir_vec![place]);
1925 P(self.signal_block_expr(hir_vec![call_move_val_init],
1928 hir::PushUnsafeBlock(hir::CompilerGenerated),
1932 let block = self.block_all(e.span, hir_vec![s1, s2, s3], Some(expr));
1933 hir::ExprBlock(P(block))
1936 ExprKind::Array(ref exprs) => {
1937 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
1939 ExprKind::Repeat(ref expr, ref count) => {
1940 let expr = P(self.lower_expr(expr));
1941 let count = self.lower_body(None, |this| this.lower_expr(count));
1942 hir::ExprRepeat(expr, count)
1944 ExprKind::Tup(ref elts) => {
1945 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
1947 ExprKind::Call(ref f, ref args) => {
1948 let f = P(self.lower_expr(f));
1949 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
1951 ExprKind::MethodCall(ref seg, ref args) => {
1952 let hir_seg = self.lower_path_segment(e.span, seg, ParamMode::Optional, 0,
1953 ParenthesizedGenericArgs::Err);
1954 let args = args.iter().map(|x| self.lower_expr(x)).collect();
1955 hir::ExprMethodCall(hir_seg, seg.span, args)
1957 ExprKind::Binary(binop, ref lhs, ref rhs) => {
1958 let binop = self.lower_binop(binop);
1959 let lhs = P(self.lower_expr(lhs));
1960 let rhs = P(self.lower_expr(rhs));
1961 hir::ExprBinary(binop, lhs, rhs)
1963 ExprKind::Unary(op, ref ohs) => {
1964 let op = self.lower_unop(op);
1965 let ohs = P(self.lower_expr(ohs));
1966 hir::ExprUnary(op, ohs)
1968 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
1969 ExprKind::Cast(ref expr, ref ty) => {
1970 let expr = P(self.lower_expr(expr));
1971 hir::ExprCast(expr, self.lower_ty(ty))
1973 ExprKind::Type(ref expr, ref ty) => {
1974 let expr = P(self.lower_expr(expr));
1975 hir::ExprType(expr, self.lower_ty(ty))
1977 ExprKind::AddrOf(m, ref ohs) => {
1978 let m = self.lower_mutability(m);
1979 let ohs = P(self.lower_expr(ohs));
1980 hir::ExprAddrOf(m, ohs)
1982 // More complicated than you might expect because the else branch
1983 // might be `if let`.
1984 ExprKind::If(ref cond, ref blk, ref else_opt) => {
1985 let else_opt = else_opt.as_ref().map(|els| {
1987 ExprKind::IfLet(..) => {
1988 // wrap the if-let expr in a block
1989 let span = els.span;
1990 let els = P(self.lower_expr(els));
1995 let blk = P(hir::Block {
2000 rules: hir::DefaultBlock,
2002 targeted_by_break: false,
2004 P(self.expr_block(blk, ThinVec::new()))
2006 _ => P(self.lower_expr(els)),
2010 let then_blk = self.lower_block(blk, false);
2011 let then_expr = self.expr_block(then_blk, ThinVec::new());
2013 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
2015 ExprKind::While(ref cond, ref body, opt_ident) => {
2016 self.with_loop_scope(e.id, |this|
2018 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
2019 this.lower_block(body, false),
2020 this.lower_opt_sp_ident(opt_ident)))
2022 ExprKind::Loop(ref body, opt_ident) => {
2023 self.with_loop_scope(e.id, |this|
2024 hir::ExprLoop(this.lower_block(body, false),
2025 this.lower_opt_sp_ident(opt_ident),
2026 hir::LoopSource::Loop))
2028 ExprKind::Catch(ref body) => {
2029 self.with_catch_scope(body.id, |this|
2030 hir::ExprBlock(this.lower_block(body, true)))
2032 ExprKind::Match(ref expr, ref arms) => {
2033 hir::ExprMatch(P(self.lower_expr(expr)),
2034 arms.iter().map(|x| self.lower_arm(x)).collect(),
2035 hir::MatchSource::Normal)
2037 ExprKind::Closure(capture_clause, ref decl, ref body, fn_decl_span) => {
2038 self.with_new_scopes(|this| {
2039 this.with_parent_def(e.id, |this| {
2040 let mut is_generator = false;
2041 let body_id = this.lower_body(Some(decl), |this| {
2042 let e = this.lower_expr(body);
2043 is_generator = this.is_generator;
2046 if is_generator && !decl.inputs.is_empty() {
2047 span_err!(this.sess, fn_decl_span, E0628,
2048 "generators cannot have explicit arguments");
2049 this.sess.abort_if_errors();
2051 hir::ExprClosure(this.lower_capture_clause(capture_clause),
2052 this.lower_fn_decl(decl),
2059 ExprKind::Block(ref blk) => hir::ExprBlock(self.lower_block(blk, false)),
2060 ExprKind::Assign(ref el, ref er) => {
2061 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
2063 ExprKind::AssignOp(op, ref el, ref er) => {
2064 hir::ExprAssignOp(self.lower_binop(op),
2065 P(self.lower_expr(el)),
2066 P(self.lower_expr(er)))
2068 ExprKind::Field(ref el, ident) => {
2069 hir::ExprField(P(self.lower_expr(el)),
2070 respan(ident.span, self.lower_ident(ident.node)))
2072 ExprKind::TupField(ref el, ident) => {
2073 hir::ExprTupField(P(self.lower_expr(el)), ident)
2075 ExprKind::Index(ref el, ref er) => {
2076 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
2078 ExprKind::Range(ref e1, ref e2, lims) => {
2079 use syntax::ast::RangeLimits::*;
2081 let path = match (e1, e2, lims) {
2082 (&None, &None, HalfOpen) => "RangeFull",
2083 (&Some(..), &None, HalfOpen) => "RangeFrom",
2084 (&None, &Some(..), HalfOpen) => "RangeTo",
2085 (&Some(..), &Some(..), HalfOpen) => "Range",
2086 (&None, &Some(..), Closed) => "RangeToInclusive",
2087 (&Some(..), &Some(..), Closed) => "RangeInclusive",
2088 (_, &None, Closed) =>
2089 panic!(self.diagnostic().span_fatal(
2090 e.span, "inclusive range with no end")),
2094 e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e)))
2096 let expr = P(self.lower_expr(&e));
2098 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
2099 self.field(Symbol::intern(s), expr, unstable_span)
2100 }).collect::<P<[hir::Field]>>();
2102 let is_unit = fields.is_empty();
2104 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
2106 iter::once("ops").chain(iter::once(path))
2107 .collect::<Vec<_>>();
2108 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
2109 let struct_path = hir::QPath::Resolved(None, P(struct_path));
2111 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
2117 hir::ExprPath(struct_path)
2119 hir::ExprStruct(struct_path, fields, None)
2121 span: unstable_span,
2122 attrs: e.attrs.clone(),
2125 ExprKind::Path(ref qself, ref path) => {
2126 hir::ExprPath(self.lower_qpath(e.id, qself, path, ParamMode::Optional))
2128 ExprKind::Break(opt_ident, ref opt_expr) => {
2129 let label_result = if self.is_in_loop_condition && opt_ident.is_none() {
2132 target_id: hir::ScopeTarget::Loop(
2133 Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into()),
2136 self.lower_loop_destination(opt_ident.map(|ident| (e.id, ident)))
2140 opt_expr.as_ref().map(|x| P(self.lower_expr(x))))
2142 ExprKind::Continue(opt_ident) =>
2144 if self.is_in_loop_condition && opt_ident.is_none() {
2147 target_id: hir::ScopeTarget::Loop(Err(
2148 hir::LoopIdError::UnlabeledCfInWhileCondition).into()),
2151 self.lower_loop_destination(opt_ident.map( |ident| (e.id, ident)))
2153 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
2154 ExprKind::InlineAsm(ref asm) => {
2155 let hir_asm = hir::InlineAsm {
2156 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
2157 outputs: asm.outputs.iter().map(|out| {
2158 hir::InlineAsmOutput {
2159 constraint: out.constraint.clone(),
2161 is_indirect: out.is_indirect,
2164 asm: asm.asm.clone(),
2165 asm_str_style: asm.asm_str_style,
2166 clobbers: asm.clobbers.clone().into(),
2167 volatile: asm.volatile,
2168 alignstack: asm.alignstack,
2169 dialect: asm.dialect,
2173 asm.outputs.iter().map(|out| self.lower_expr(&out.expr)).collect();
2175 asm.inputs.iter().map(|&(_, ref input)| self.lower_expr(input)).collect();
2176 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
2178 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
2179 hir::ExprStruct(self.lower_qpath(e.id, &None, path, ParamMode::Optional),
2180 fields.iter().map(|x| self.lower_field(x)).collect(),
2181 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))))
2183 ExprKind::Paren(ref ex) => {
2184 let mut ex = self.lower_expr(ex);
2185 // include parens in span, but only if it is a super-span.
2186 if e.span.contains(ex.span) {
2189 // merge attributes into the inner expression.
2190 let mut attrs = e.attrs.clone();
2191 attrs.extend::<Vec<_>>(ex.attrs.into());
2196 ExprKind::Yield(ref opt_expr) => {
2197 self.is_generator = true;
2198 let expr = opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| {
2199 self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new())
2201 hir::ExprYield(P(expr))
2204 // Desugar ExprIfLet
2205 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
2206 ExprKind::IfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
2209 // match <sub_expr> {
2211 // _ => [<else_opt> | ()]
2214 let mut arms = vec![];
2216 // `<pat> => <body>`
2218 let body = self.lower_block(body, false);
2219 let body_expr = P(self.expr_block(body, ThinVec::new()));
2220 let pat = self.lower_pat(pat);
2221 arms.push(self.arm(hir_vec![pat], body_expr));
2224 // _ => [<else_opt>|()]
2226 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
2227 let wildcard_pattern = self.pat_wild(e.span);
2228 let body = if let Some(else_expr) = wildcard_arm {
2229 P(self.lower_expr(else_expr))
2231 self.expr_tuple(e.span, hir_vec![])
2233 arms.push(self.arm(hir_vec![wildcard_pattern], body));
2236 let contains_else_clause = else_opt.is_some();
2238 let sub_expr = P(self.lower_expr(sub_expr));
2243 hir::MatchSource::IfLetDesugar {
2244 contains_else_clause,
2248 // Desugar ExprWhileLet
2249 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
2250 ExprKind::WhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
2253 // [opt_ident]: loop {
2254 // match <sub_expr> {
2260 // Note that the block AND the condition are evaluated in the loop scope.
2261 // This is done to allow `break` from inside the condition of the loop.
2262 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| (
2263 this.lower_block(body, false),
2264 this.expr_break(e.span, ThinVec::new()),
2265 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
2268 // `<pat> => <body>`
2270 let body_expr = P(self.expr_block(body, ThinVec::new()));
2271 let pat = self.lower_pat(pat);
2272 self.arm(hir_vec![pat], body_expr)
2277 let pat_under = self.pat_wild(e.span);
2278 self.arm(hir_vec![pat_under], break_expr)
2281 // `match <sub_expr> { ... }`
2282 let arms = hir_vec![pat_arm, break_arm];
2283 let match_expr = self.expr(e.span,
2284 hir::ExprMatch(sub_expr,
2286 hir::MatchSource::WhileLetDesugar),
2289 // `[opt_ident]: loop { ... }`
2290 let loop_block = P(self.block_expr(P(match_expr)));
2291 let loop_expr = hir::ExprLoop(loop_block, self.lower_opt_sp_ident(opt_ident),
2292 hir::LoopSource::WhileLet);
2293 // add attributes to the outer returned expr node
2297 // Desugar ExprForLoop
2298 // From: `[opt_ident]: for <pat> in <head> <body>`
2299 ExprKind::ForLoop(ref pat, ref head, ref body, opt_ident) => {
2303 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
2305 // [opt_ident]: loop {
2307 // match ::std::iter::Iterator::next(&mut iter) {
2308 // ::std::option::Option::Some(val) => __next = val,
2309 // ::std::option::Option::None => break
2311 // let <pat> = __next;
2312 // StmtExpr(<body>);
2320 let head = self.lower_expr(head);
2322 let iter = self.str_to_ident("iter");
2324 let next_ident = self.str_to_ident("__next");
2325 let next_pat = self.pat_ident_binding_mode(e.span,
2327 hir::BindingAnnotation::Mutable);
2329 // `::std::option::Option::Some(val) => next = val`
2331 let val_ident = self.str_to_ident("val");
2332 let val_pat = self.pat_ident(e.span, val_ident);
2333 let val_expr = P(self.expr_ident(e.span, val_ident, val_pat.id));
2334 let next_expr = P(self.expr_ident(e.span, next_ident, next_pat.id));
2335 let assign = P(self.expr(e.span,
2336 hir::ExprAssign(next_expr, val_expr),
2338 let some_pat = self.pat_some(e.span, val_pat);
2339 self.arm(hir_vec![some_pat], assign)
2342 // `::std::option::Option::None => break`
2344 let break_expr = self.with_loop_scope(e.id, |this|
2345 this.expr_break(e.span, ThinVec::new()));
2346 let pat = self.pat_none(e.span);
2347 self.arm(hir_vec![pat], break_expr)
2351 let iter_pat = self.pat_ident_binding_mode(e.span,
2353 hir::BindingAnnotation::Mutable);
2355 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
2357 let iter = P(self.expr_ident(e.span, iter, iter_pat.id));
2358 let ref_mut_iter = self.expr_mut_addr_of(e.span, iter);
2359 let next_path = &["iter", "Iterator", "next"];
2360 let next_path = P(self.expr_std_path(e.span, next_path, ThinVec::new()));
2361 let next_expr = P(self.expr_call(e.span, next_path,
2362 hir_vec![ref_mut_iter]));
2363 let arms = hir_vec![pat_arm, break_arm];
2366 hir::ExprMatch(next_expr, arms,
2367 hir::MatchSource::ForLoopDesugar),
2370 let match_stmt = respan(e.span, hir::StmtExpr(match_expr, self.next_id().node_id));
2372 let next_expr = P(self.expr_ident(e.span, next_ident, next_pat.id));
2375 let next_let = self.stmt_let_pat(e.span,
2378 hir::LocalSource::ForLoopDesugar);
2380 // `let <pat> = __next`
2381 let pat = self.lower_pat(pat);
2382 let pat_let = self.stmt_let_pat(e.span,
2385 hir::LocalSource::ForLoopDesugar);
2387 let body_block = self.with_loop_scope(e.id,
2388 |this| this.lower_block(body, false));
2389 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
2390 let body_stmt = respan(e.span, hir::StmtExpr(body_expr, self.next_id().node_id));
2392 let loop_block = P(self.block_all(e.span,
2399 // `[opt_ident]: loop { ... }`
2400 let loop_expr = hir::ExprLoop(loop_block, self.lower_opt_sp_ident(opt_ident),
2401 hir::LoopSource::ForLoop);
2402 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
2403 let loop_expr = P(hir::Expr {
2408 attrs: ThinVec::new(),
2411 // `mut iter => { ... }`
2412 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
2414 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
2415 let into_iter_expr = {
2416 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
2417 let into_iter = P(self.expr_std_path(e.span, into_iter_path,
2419 P(self.expr_call(e.span, into_iter, hir_vec![head]))
2422 let match_expr = P(self.expr_match(e.span,
2425 hir::MatchSource::ForLoopDesugar));
2427 // `{ let _result = ...; _result }`
2428 // underscore prevents an unused_variables lint if the head diverges
2429 let result_ident = self.str_to_ident("_result");
2430 let (let_stmt, let_stmt_binding) =
2431 self.stmt_let(e.span, false, result_ident, match_expr);
2433 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
2434 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
2435 // add the attributes to the outer returned expr node
2436 return self.expr_block(block, e.attrs.clone());
2439 // Desugar ExprKind::Try
2441 ExprKind::Try(ref sub_expr) => {
2444 // match Try::into_result(<expr>) {
2445 // Ok(val) => #[allow(unreachable_code)] val,
2446 // Err(err) => #[allow(unreachable_code)]
2447 // // If there is an enclosing `catch {...}`
2448 // break 'catch_target Try::from_error(From::from(err)),
2450 // return Try::from_error(From::from(err)),
2454 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
2456 // Try::into_result(<expr>)
2459 let sub_expr = self.lower_expr(sub_expr);
2461 let path = &["ops", "Try", "into_result"];
2462 let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
2463 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
2466 // #[allow(unreachable_code)]
2468 // allow(unreachable_code)
2470 let allow_ident = self.str_to_ident("allow");
2471 let uc_ident = self.str_to_ident("unreachable_code");
2472 let uc_meta_item = attr::mk_spanned_word_item(e.span, uc_ident);
2473 let uc_nested = NestedMetaItemKind::MetaItem(uc_meta_item);
2474 let uc_spanned = respan(e.span, uc_nested);
2475 attr::mk_spanned_list_item(e.span, allow_ident, vec![uc_spanned])
2477 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
2479 let attrs = vec![attr];
2481 // Ok(val) => #[allow(unreachable_code)] val,
2483 let val_ident = self.str_to_ident("val");
2484 let val_pat = self.pat_ident(e.span, val_ident);
2485 let val_expr = P(self.expr_ident_with_attrs(e.span,
2488 ThinVec::from(attrs.clone())));
2489 let ok_pat = self.pat_ok(e.span, val_pat);
2491 self.arm(hir_vec![ok_pat], val_expr)
2494 // Err(err) => #[allow(unreachable_code)]
2495 // return Carrier::from_error(From::from(err)),
2497 let err_ident = self.str_to_ident("err");
2498 let err_local = self.pat_ident(e.span, err_ident);
2500 let path = &["convert", "From", "from"];
2501 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
2502 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
2504 self.expr_call(e.span, from, hir_vec![err_expr])
2506 let from_err_expr = {
2507 let path = &["ops", "Try", "from_error"];
2508 let from_err = P(self.expr_std_path(unstable_span, path,
2510 P(self.expr_call(e.span, from_err, hir_vec![from_expr]))
2513 let thin_attrs = ThinVec::from(attrs);
2514 let catch_scope = self.catch_scopes.last().map(|x| *x);
2515 let ret_expr = if let Some(catch_node) = catch_scope {
2521 target_id: hir::ScopeTarget::Block(catch_node),
2528 hir::Expr_::ExprRet(Some(from_err_expr)),
2533 let err_pat = self.pat_err(e.span, err_local);
2534 self.arm(hir_vec![err_pat], ret_expr)
2537 hir::ExprMatch(discr,
2538 hir_vec![err_arm, ok_arm],
2539 hir::MatchSource::TryDesugar)
2542 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
2545 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
2552 attrs: e.attrs.clone(),
2556 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
2557 SmallVector::one(match s.node {
2558 StmtKind::Local(ref l) => Spanned {
2559 node: hir::StmtDecl(P(Spanned {
2560 node: hir::DeclLocal(self.lower_local(l)),
2562 }), self.lower_node_id(s.id).node_id),
2565 StmtKind::Item(ref it) => {
2566 // Can only use the ID once.
2567 let mut id = Some(s.id);
2568 return self.lower_item_id(it).into_iter().map(|item_id| Spanned {
2569 node: hir::StmtDecl(P(Spanned {
2570 node: hir::DeclItem(item_id),
2573 .map(|id| self.lower_node_id(id).node_id)
2574 .unwrap_or_else(|| self.next_id().node_id)),
2578 StmtKind::Expr(ref e) => {
2580 node: hir::StmtExpr(P(self.lower_expr(e)),
2581 self.lower_node_id(s.id).node_id),
2585 StmtKind::Semi(ref e) => {
2587 node: hir::StmtSemi(P(self.lower_expr(e)),
2588 self.lower_node_id(s.id).node_id),
2592 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
2596 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
2598 CaptureBy::Value => hir::CaptureByValue,
2599 CaptureBy::Ref => hir::CaptureByRef,
2603 /// If an `explicit_owner` is given, this method allocates the `HirId` in
2604 /// the address space of that item instead of the item currently being
2605 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
2606 /// lower a `Visibility` value although we haven't lowered the owning
2607 /// `ImplItem` in question yet.
2608 fn lower_visibility(&mut self,
2610 explicit_owner: Option<NodeId>)
2611 -> hir::Visibility {
2613 Visibility::Public => hir::Public,
2614 Visibility::Crate(_) => hir::Visibility::Crate,
2615 Visibility::Restricted { ref path, id } => {
2616 hir::Visibility::Restricted {
2617 path: P(self.lower_path(id, path, ParamMode::Explicit, true)),
2618 id: if let Some(owner) = explicit_owner {
2619 self.lower_node_id_with_owner(id, owner).node_id
2621 self.lower_node_id(id).node_id
2625 Visibility::Inherited => hir::Inherited,
2629 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
2631 Defaultness::Default => hir::Defaultness::Default { has_value: has_value },
2632 Defaultness::Final => {
2634 hir::Defaultness::Final
2639 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
2641 BlockCheckMode::Default => hir::DefaultBlock,
2642 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
2646 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
2648 BindingMode::ByValue(Mutability::Immutable) =>
2649 hir::BindingAnnotation::Unannotated,
2650 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
2651 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
2652 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
2656 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2658 CompilerGenerated => hir::CompilerGenerated,
2659 UserProvided => hir::UserProvided,
2663 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
2665 ImplPolarity::Positive => hir::ImplPolarity::Positive,
2666 ImplPolarity::Negative => hir::ImplPolarity::Negative,
2670 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2672 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2673 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
2677 // Helper methods for building HIR.
2679 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
2688 fn field(&mut self, name: Name, expr: P<hir::Expr>, span: Span) -> hir::Field {
2696 is_shorthand: false,
2700 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
2701 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
2702 P(self.expr(span, expr_break, attrs))
2705 fn expr_call(&mut self, span: Span, e: P<hir::Expr>, args: hir::HirVec<hir::Expr>)
2707 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
2710 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
2711 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
2714 fn expr_ident_with_attrs(&mut self, span: Span,
2717 attrs: ThinVec<Attribute>) -> hir::Expr {
2719 let defs = self.resolver.definitions();
2720 Def::Local(defs.local_def_id(binding))
2723 let expr_path = hir::ExprPath(hir::QPath::Resolved(None, P(hir::Path {
2726 segments: hir_vec![hir::PathSegment::from_name(id)],
2729 self.expr(span, expr_path, attrs)
2732 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
2733 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
2736 fn expr_std_path(&mut self,
2738 components: &[&str],
2739 attrs: ThinVec<Attribute>)
2741 let path = self.std_path(span, components, true);
2742 self.expr(span, hir::ExprPath(hir::QPath::Resolved(None, P(path))), attrs)
2745 fn expr_match(&mut self,
2748 arms: hir::HirVec<hir::Arm>,
2749 source: hir::MatchSource)
2751 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
2754 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
2755 self.expr(b.span, hir::ExprBlock(b), attrs)
2758 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
2759 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
2762 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
2763 let LoweredNodeId { node_id, hir_id } = self.next_id();
2773 fn stmt_let_pat(&mut self,
2775 ex: Option<P<hir::Expr>>,
2777 source: hir::LocalSource)
2779 let LoweredNodeId { node_id, hir_id } = self.next_id();
2781 let local = P(hir::Local {
2788 attrs: ThinVec::new(),
2791 let decl = respan(sp, hir::DeclLocal(local));
2792 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
2795 fn stmt_let(&mut self, sp: Span, mutbl: bool, ident: Name, ex: P<hir::Expr>)
2796 -> (hir::Stmt, NodeId) {
2797 let pat = if mutbl {
2798 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
2800 self.pat_ident(sp, ident)
2802 let pat_id = pat.id;
2803 (self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal), pat_id)
2806 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
2807 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
2810 fn block_all(&mut self, span: Span, stmts: hir::HirVec<hir::Stmt>, expr: Option<P<hir::Expr>>)
2812 let LoweredNodeId { node_id, hir_id } = self.next_id();
2819 rules: hir::DefaultBlock,
2821 targeted_by_break: false,
2825 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2826 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
2829 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2830 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
2833 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2834 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
2837 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
2838 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
2841 fn pat_std_enum(&mut self,
2843 components: &[&str],
2844 subpats: hir::HirVec<P<hir::Pat>>)
2846 let path = self.std_path(span, components, true);
2847 let qpath = hir::QPath::Resolved(None, P(path));
2848 let pt = if subpats.is_empty() {
2849 hir::PatKind::Path(qpath)
2851 hir::PatKind::TupleStruct(qpath, subpats, None)
2856 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
2857 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
2860 fn pat_ident_binding_mode(&mut self, span: Span, name: Name, bm: hir::BindingAnnotation)
2862 let LoweredNodeId { node_id, hir_id } = self.next_id();
2863 let parent_def = self.parent_def.unwrap();
2865 let defs = self.resolver.definitions();
2866 let def_path_data = DefPathData::Binding(name.as_str());
2867 let def_index = defs.create_def_with_parent(parent_def,
2872 DefId::local(def_index)
2878 node: hir::PatKind::Binding(bm,
2889 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
2890 self.pat(span, hir::PatKind::Wild)
2893 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
2894 let LoweredNodeId { node_id, hir_id } = self.next_id();
2903 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
2904 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
2905 /// The path is also resolved according to `is_value`.
2906 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
2907 let mut path = hir::Path {
2910 segments: iter::once(keywords::CrateRoot.name()).chain({
2911 self.crate_root.into_iter().chain(components.iter().cloned()).map(Symbol::intern)
2912 }).map(hir::PathSegment::from_name).collect(),
2915 self.resolver.resolve_hir_path(&mut path, is_value);
2919 fn signal_block_expr(&mut self,
2920 stmts: hir::HirVec<hir::Stmt>,
2923 rule: hir::BlockCheckMode,
2924 attrs: ThinVec<Attribute>)
2926 let LoweredNodeId { node_id, hir_id } = self.next_id();
2928 let block = P(hir::Block {
2935 targeted_by_break: false,
2937 self.expr_block(block, attrs)
2940 fn ty_path(&mut self, id: NodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
2942 let node = match qpath {
2943 hir::QPath::Resolved(None, path) => {
2944 // Turn trait object paths into `TyTraitObject` instead.
2945 if let Def::Trait(_) = path.def {
2946 let principal = hir::PolyTraitRef {
2947 bound_lifetimes: hir_vec![],
2948 trait_ref: hir::TraitRef {
2949 path: path.and_then(|path| path),
2955 // The original ID is taken by the `PolyTraitRef`,
2956 // so the `Ty` itself needs a different one.
2957 id = self.next_id().node_id;
2959 hir::TyTraitObject(hir_vec![principal], self.elided_lifetime(span))
2961 hir::TyPath(hir::QPath::Resolved(None, path))
2964 _ => hir::TyPath(qpath)
2966 P(hir::Ty { id, node, span })
2969 fn elided_lifetime(&mut self, span: Span) -> hir::Lifetime {
2971 id: self.next_id().node_id,
2973 name: keywords::Invalid.name()
2978 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
2979 // Sorting by span ensures that we get things in order within a
2980 // file, and also puts the files in a sensible order.
2981 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
2982 body_ids.sort_by_key(|b| bodies[b].value.span);