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.
43 use dep_graph::DepGraph;
44 use hir::{self, ParamName};
46 use hir::map::{DefKey, DefPathData, Definitions};
47 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
48 use hir::def::{Def, PathResolution, PerNS};
50 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES};
51 use middle::cstore::CrateStore;
52 use rustc_data_structures::indexed_vec::IndexVec;
54 use util::common::FN_OUTPUT_NAME;
55 use util::nodemap::{DefIdMap, NodeMap};
57 use std::collections::{BTreeMap, HashSet};
65 use syntax::ext::hygiene::{Mark, SyntaxContext};
66 use syntax::print::pprust;
68 use syntax::codemap::{self, respan, CompilerDesugaringKind, Spanned};
69 use syntax::std_inject;
70 use syntax::symbol::{keywords, Symbol};
71 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
72 use syntax::parse::token::Token;
73 use syntax::util::small_vector::SmallVector;
74 use syntax::visit::{self, Visitor};
77 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
79 pub struct LoweringContext<'a> {
80 crate_root: Option<&'static str>,
82 // Use to assign ids to hir nodes that do not directly correspond to an ast node
85 cstore: &'a CrateStore,
87 resolver: &'a mut Resolver,
89 /// The items being lowered are collected here.
90 items: BTreeMap<NodeId, hir::Item>,
92 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
93 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
94 bodies: BTreeMap<hir::BodyId, hir::Body>,
95 exported_macros: Vec<hir::MacroDef>,
97 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
98 trait_auto_impl: BTreeMap<DefId, NodeId>,
102 catch_scopes: Vec<NodeId>,
103 loop_scopes: Vec<NodeId>,
104 is_in_loop_condition: bool,
105 is_in_trait_impl: bool,
107 /// What to do when we encounter either an "anonymous lifetime
108 /// reference". The term "anonymous" is meant to encompass both
109 /// `'_` lifetimes as well as fully elided cases where nothing is
110 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
111 anonymous_lifetime_mode: AnonymousLifetimeMode,
113 // Used to create lifetime definitions from in-band lifetime usages.
114 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
115 // When a named lifetime is encountered in a function or impl header and
116 // has not been defined
117 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
118 // to this list. The results of this list are then added to the list of
119 // lifetime definitions in the corresponding impl or function generics.
120 lifetimes_to_define: Vec<(Span, ParamName)>,
122 // Whether or not in-band lifetimes are being collected. This is used to
123 // indicate whether or not we're in a place where new lifetimes will result
124 // in in-band lifetime definitions, such a function or an impl header.
125 // This will always be false unless the `in_band_lifetimes` feature is
127 is_collecting_in_band_lifetimes: bool,
129 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
130 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
131 // against this list to see if it is already in-scope, or if a definition
132 // needs to be created for it.
133 in_scope_lifetimes: Vec<Ident>,
135 type_def_lifetime_params: DefIdMap<usize>,
137 current_hir_id_owner: Vec<(DefIndex, u32)>,
138 item_local_id_counters: NodeMap<u32>,
139 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
143 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
144 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
146 /// Obtain the resolution for a node id
147 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
149 /// Obtain the possible resolutions for the given `use` statement.
150 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
152 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
153 /// This should only return `None` during testing.
154 fn definitions(&mut self) -> &mut Definitions;
156 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
157 /// it based on `is_value`.
161 crate_root: Option<&str>,
163 params: Option<P<hir::GenericArgs>>,
169 enum ImplTraitContext<'a> {
170 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
171 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
172 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
174 /// Newly generated parameters should be inserted into the given `Vec`
175 Universal(&'a mut Vec<hir::GenericParam>),
177 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
178 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
179 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
181 /// We store a DefId here so we can look up necessary information later
184 /// `impl Trait` is not accepted in this position.
188 impl<'a> ImplTraitContext<'a> {
189 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
190 use self::ImplTraitContext::*;
192 Universal(params) => Universal(params),
193 Existential(did) => Existential(*did),
194 Disallowed => Disallowed,
202 dep_graph: &DepGraph,
204 resolver: &mut Resolver,
206 // We're constructing the HIR here; we don't care what we will
207 // read, since we haven't even constructed the *input* to
209 dep_graph.assert_ignored();
212 crate_root: std_inject::injected_crate_name(),
216 items: BTreeMap::new(),
217 trait_items: BTreeMap::new(),
218 impl_items: BTreeMap::new(),
219 bodies: BTreeMap::new(),
220 trait_impls: BTreeMap::new(),
221 trait_auto_impl: BTreeMap::new(),
222 exported_macros: Vec::new(),
223 catch_scopes: Vec::new(),
224 loop_scopes: Vec::new(),
225 is_in_loop_condition: false,
226 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
227 type_def_lifetime_params: DefIdMap(),
228 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
229 item_local_id_counters: NodeMap(),
230 node_id_to_hir_id: IndexVec::new(),
232 is_in_trait_impl: false,
233 lifetimes_to_define: Vec::new(),
234 is_collecting_in_band_lifetimes: false,
235 in_scope_lifetimes: Vec::new(),
239 #[derive(Copy, Clone, PartialEq, Eq)]
241 /// Any path in a type context.
243 /// The `module::Type` in `module::Type::method` in an expression.
248 struct LoweredNodeId {
253 enum ParenthesizedGenericArgs {
259 /// What to do when we encounter an **anonymous** lifetime
260 /// reference. Anonymous lifetime references come in two flavors. You
261 /// have implicit, or fully elided, references to lifetimes, like the
262 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
263 /// or `Ref<'_, T>`. These often behave the same, but not always:
265 /// - certain usages of implicit references are deprecated, like
266 /// `Ref<T>`, and we sometimes just give hard errors in those cases
268 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
269 /// the same as `Box<dyn Foo + '_>`.
271 /// We describe the effects of the various modes in terms of three cases:
273 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
274 /// of a `&` (e.g., the missing lifetime in something like `&T`)
275 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
276 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
277 /// elided bounds follow special rules. Note that this only covers
278 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
279 /// '_>` is a case of "modern" elision.
280 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
281 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
282 /// non-deprecated equivalent.
284 /// Currently, the handling of lifetime elision is somewhat spread out
285 /// between HIR lowering and -- as described below -- the
286 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
287 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
288 /// everything into HIR lowering.
289 #[derive(Copy, Clone)]
290 enum AnonymousLifetimeMode {
291 /// For **Modern** cases, create a new anonymous region parameter
292 /// and reference that.
294 /// For **Dyn Bound** cases, pass responsibility to
295 /// `resolve_lifetime` code.
297 /// For **Deprecated** cases, report an error.
300 /// Pass responsibility to `resolve_lifetime` code for all cases.
304 impl<'a> LoweringContext<'a> {
305 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
306 /// Full-crate AST visitor that inserts into a fresh
307 /// `LoweringContext` any information that may be
308 /// needed from arbitrary locations in the crate.
309 /// E.g. The number of lifetime generic parameters
310 /// declared for every type and trait definition.
311 struct MiscCollector<'lcx, 'interner: 'lcx> {
312 lctx: &'lcx mut LoweringContext<'interner>,
315 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
316 fn visit_item(&mut self, item: &'lcx Item) {
317 self.lctx.allocate_hir_id_counter(item.id, item);
320 ItemKind::Struct(_, ref generics)
321 | ItemKind::Union(_, ref generics)
322 | ItemKind::Enum(_, ref generics)
323 | ItemKind::Ty(_, ref generics)
324 | ItemKind::Trait(_, _, ref generics, ..) => {
325 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
329 .filter(|param| match param.kind {
330 ast::GenericParamKind::Lifetime { .. } => true,
334 self.lctx.type_def_lifetime_params.insert(def_id, count);
338 visit::walk_item(self, item);
341 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
342 self.lctx.allocate_hir_id_counter(item.id, item);
343 visit::walk_trait_item(self, item);
346 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
347 self.lctx.allocate_hir_id_counter(item.id, item);
348 visit::walk_impl_item(self, item);
352 struct ItemLowerer<'lcx, 'interner: 'lcx> {
353 lctx: &'lcx mut LoweringContext<'interner>,
356 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
357 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
359 F: FnOnce(&mut Self),
361 let old = self.lctx.is_in_trait_impl;
362 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
368 self.lctx.is_in_trait_impl = old;
372 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
373 fn visit_item(&mut self, item: &'lcx Item) {
374 let mut item_lowered = true;
375 self.lctx.with_hir_id_owner(item.id, |lctx| {
376 if let Some(hir_item) = lctx.lower_item(item) {
377 lctx.items.insert(item.id, hir_item);
379 item_lowered = false;
384 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
385 hir::Item_::ItemImpl(_, _, _, ref generics, ..)
386 | hir::Item_::ItemTrait(_, _, ref generics, ..) => {
387 generics.params.clone()
392 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
393 let this = &mut ItemLowerer { lctx: this };
394 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
395 this.with_trait_impl_ref(opt_trait_ref, |this| {
396 visit::walk_item(this, item)
399 visit::walk_item(this, item);
405 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
406 self.lctx.with_hir_id_owner(item.id, |lctx| {
407 let id = hir::TraitItemId { node_id: item.id };
408 let hir_item = lctx.lower_trait_item(item);
409 lctx.trait_items.insert(id, hir_item);
412 visit::walk_trait_item(self, item);
415 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
416 self.lctx.with_hir_id_owner(item.id, |lctx| {
417 let id = hir::ImplItemId { node_id: item.id };
418 let hir_item = lctx.lower_impl_item(item);
419 lctx.impl_items.insert(id, hir_item);
421 visit::walk_impl_item(self, item);
425 self.lower_node_id(CRATE_NODE_ID);
426 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
428 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
429 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
431 let module = self.lower_mod(&c.module);
432 let attrs = self.lower_attrs(&c.attrs);
433 let body_ids = body_ids(&self.bodies);
437 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
443 exported_macros: hir::HirVec::from(self.exported_macros),
445 trait_items: self.trait_items,
446 impl_items: self.impl_items,
449 trait_impls: self.trait_impls,
450 trait_auto_impl: self.trait_auto_impl,
454 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
455 if self.item_local_id_counters.insert(owner, 0).is_some() {
457 "Tried to allocate item_local_id_counter for {:?} twice",
461 // Always allocate the first HirId for the owner itself
462 self.lower_node_id_with_owner(owner, owner)
465 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
467 F: FnOnce(&mut Self) -> hir::HirId,
469 if ast_node_id == DUMMY_NODE_ID {
470 return LoweredNodeId {
471 node_id: DUMMY_NODE_ID,
472 hir_id: hir::DUMMY_HIR_ID,
476 let min_size = ast_node_id.as_usize() + 1;
478 if min_size > self.node_id_to_hir_id.len() {
479 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
482 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
484 if existing_hir_id == hir::DUMMY_HIR_ID {
485 // Generate a new HirId
486 let hir_id = alloc_hir_id(self);
487 self.node_id_to_hir_id[ast_node_id] = hir_id;
489 node_id: ast_node_id,
494 node_id: ast_node_id,
495 hir_id: existing_hir_id,
500 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
502 F: FnOnce(&mut Self) -> T,
504 let counter = self.item_local_id_counters
505 .insert(owner, HIR_ID_COUNTER_LOCKED)
506 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
507 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
508 self.current_hir_id_owner.push((def_index, counter));
510 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
512 debug_assert!(def_index == new_def_index);
513 debug_assert!(new_counter >= counter);
515 let prev = self.item_local_id_counters
516 .insert(owner, new_counter)
518 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
522 /// This method allocates a new HirId for the given NodeId and stores it in
523 /// the LoweringContext's NodeId => HirId map.
524 /// Take care not to call this method if the resulting HirId is then not
525 /// actually used in the HIR, as that would trigger an assertion in the
526 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
527 /// properly. Calling the method twice with the same NodeId is fine though.
528 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
529 self.lower_node_id_generic(ast_node_id, |this| {
530 let &mut (def_index, ref mut local_id_counter) =
531 this.current_hir_id_owner.last_mut().unwrap();
532 let local_id = *local_id_counter;
533 *local_id_counter += 1;
536 local_id: hir::ItemLocalId(local_id),
541 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
542 self.lower_node_id_generic(ast_node_id, |this| {
543 let local_id_counter = this
544 .item_local_id_counters
546 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
547 let local_id = *local_id_counter;
549 // We want to be sure not to modify the counter in the map while it
550 // is also on the stack. Otherwise we'll get lost updates when writing
551 // back from the stack to the map.
552 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
554 *local_id_counter += 1;
558 .opt_def_index(owner)
559 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
560 that do not belong to the current owner");
564 local_id: hir::ItemLocalId(local_id),
569 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
570 let body = hir::Body {
571 arguments: decl.map_or(hir_vec![], |decl| {
572 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
574 is_generator: self.is_generator,
578 self.bodies.insert(id, body);
582 fn next_id(&mut self) -> LoweredNodeId {
583 self.lower_node_id(self.sess.next_node_id())
586 fn expect_full_def(&mut self, id: NodeId) -> Def {
587 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
588 if pr.unresolved_segments() != 0 {
589 bug!("path not fully resolved: {:?}", pr);
595 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
596 self.resolver.get_import(id).present_items().map(|pr| {
597 if pr.unresolved_segments() != 0 {
598 bug!("path not fully resolved: {:?}", pr);
604 fn diagnostic(&self) -> &errors::Handler {
605 self.sess.diagnostic()
608 fn str_to_ident(&self, s: &'static str) -> Ident {
609 Ident::with_empty_ctxt(Symbol::gensym(s))
612 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
613 let mark = Mark::fresh(Mark::root());
614 mark.set_expn_info(codemap::ExpnInfo {
616 def_site: Some(span),
617 format: codemap::CompilerDesugaring(reason),
618 allow_internal_unstable: true,
619 allow_internal_unsafe: false,
620 local_inner_macros: false,
621 edition: codemap::hygiene::default_edition(),
623 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
626 fn with_anonymous_lifetime_mode<R>(
628 anonymous_lifetime_mode: AnonymousLifetimeMode,
629 op: impl FnOnce(&mut Self) -> R,
631 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
632 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
633 let result = op(self);
634 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
638 /// Creates a new hir::GenericParam for every new lifetime and
639 /// type parameter encountered while evaluating `f`. Definitions
640 /// are created with the parent provided. If no `parent_id` is
641 /// provided, no definitions will be returned.
643 /// Presuming that in-band lifetimes are enabled, then
644 /// `self.anonymous_lifetime_mode` will be updated to match the
645 /// argument while `f` is running (and restored afterwards).
646 fn collect_in_band_defs<T, F>(
649 anonymous_lifetime_mode: AnonymousLifetimeMode,
651 ) -> (Vec<hir::GenericParam>, T)
653 F: FnOnce(&mut LoweringContext) -> (Vec<hir::GenericParam>, T),
655 assert!(!self.is_collecting_in_band_lifetimes);
656 assert!(self.lifetimes_to_define.is_empty());
657 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
659 self.is_collecting_in_band_lifetimes = self.sess.features_untracked().in_band_lifetimes;
660 if self.is_collecting_in_band_lifetimes {
661 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
664 let (in_band_ty_params, res) = f(self);
666 self.is_collecting_in_band_lifetimes = false;
667 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
669 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
671 let params = lifetimes_to_define
673 .map(|(span, hir_name)| {
674 let def_node_id = self.next_id().node_id;
676 // Get the name we'll use to make the def-path. Note
677 // that collisions are ok here and this shouldn't
678 // really show up for end-user.
679 let str_name = match hir_name {
680 ParamName::Plain(ident) => ident.as_interned_str(),
681 ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_interned_str(),
684 // Add a definition for the in-band lifetime def
685 self.resolver.definitions().create_def_with_parent(
688 DefPathData::LifetimeParam(str_name),
689 DefIndexAddressSpace::High,
700 pure_wrt_drop: false,
701 kind: hir::GenericParamKind::Lifetime { in_band: true }
704 .chain(in_band_ty_params.into_iter())
710 /// When there is a reference to some lifetime `'a`, and in-band
711 /// lifetimes are enabled, then we want to push that lifetime into
712 /// the vector of names to define later. In that case, it will get
713 /// added to the appropriate generics.
714 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
715 if !self.is_collecting_in_band_lifetimes {
719 if self.in_scope_lifetimes.contains(&ident.modern()) {
723 let hir_name = ParamName::Plain(ident);
725 if self.lifetimes_to_define.iter()
726 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
730 self.lifetimes_to_define.push((ident.span, hir_name));
733 /// When we have either an elided or `'_` lifetime in an impl
734 /// header, we convert it to
735 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
736 assert!(self.is_collecting_in_band_lifetimes);
737 let index = self.lifetimes_to_define.len();
738 let hir_name = ParamName::Fresh(index);
739 self.lifetimes_to_define.push((span, hir_name));
743 // Evaluates `f` with the lifetimes in `params` in-scope.
744 // This is used to track which lifetimes have already been defined, and
745 // which are new in-band lifetimes that need to have a definition created
747 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &Vec<GenericParam>, f: F) -> T
749 F: FnOnce(&mut LoweringContext) -> T,
751 let old_len = self.in_scope_lifetimes.len();
752 let lt_def_names = params.iter().filter_map(|param| match param.kind {
753 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
756 self.in_scope_lifetimes.extend(lt_def_names);
760 self.in_scope_lifetimes.truncate(old_len);
764 // Same as the method above, but accepts `hir::GenericParam`s
765 // instead of `ast::GenericParam`s.
766 // This should only be used with generics that have already had their
767 // in-band lifetimes added. In practice, this means that this function is
768 // only used when lowering a child item of a trait or impl.
769 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
770 params: &HirVec<hir::GenericParam>,
773 F: FnOnce(&mut LoweringContext) -> T,
775 let old_len = self.in_scope_lifetimes.len();
776 let lt_def_names = params.iter().filter_map(|param| match param.kind {
777 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
780 self.in_scope_lifetimes.extend(lt_def_names);
784 self.in_scope_lifetimes.truncate(old_len);
788 /// Appends in-band lifetime defs and argument-position `impl
789 /// Trait` defs to the existing set of generics.
791 /// Presuming that in-band lifetimes are enabled, then
792 /// `self.anonymous_lifetime_mode` will be updated to match the
793 /// argument while `f` is running (and restored afterwards).
794 fn add_in_band_defs<F, T>(
798 anonymous_lifetime_mode: AnonymousLifetimeMode,
800 ) -> (hir::Generics, T)
802 F: FnOnce(&mut LoweringContext, &mut Vec<hir::GenericParam>) -> T,
804 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
807 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
808 let mut params = Vec::new();
809 let generics = this.lower_generics(
811 ImplTraitContext::Universal(&mut params),
813 let res = f(this, &mut params);
814 (params, (generics, res))
819 lowered_generics.params = lowered_generics
826 (lowered_generics, res)
829 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
831 F: FnOnce(&mut LoweringContext) -> T,
833 let len = self.catch_scopes.len();
834 self.catch_scopes.push(catch_id);
836 let result = f(self);
839 self.catch_scopes.len(),
840 "catch scopes should be added and removed in stack order"
843 self.catch_scopes.pop().unwrap();
850 capture_clause: CaptureBy,
851 closure_node_id: NodeId,
853 body: impl FnOnce(&mut LoweringContext) -> hir::Expr,
855 let prev_is_generator = mem::replace(&mut self.is_generator, true);
856 let body_expr = body(self);
857 let span = body_expr.span;
858 let output = match ret_ty {
859 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
860 None => FunctionRetTy::Default(span),
867 let body_id = self.record_body(body_expr, Some(&decl));
868 self.is_generator = prev_is_generator;
870 let capture_clause = self.lower_capture_clause(capture_clause);
871 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
872 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
873 let generator = hir::Expr {
875 hir_id: closure_hir_id,
876 node: hir::ExprClosure(capture_clause, decl, body_id, span,
877 Some(hir::GeneratorMovability::Static)),
879 attrs: ThinVec::new(),
882 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
883 let gen_future = self.expr_std_path(
884 unstable_span, &["future", "from_generator"], None, ThinVec::new());
885 hir::ExprCall(P(gen_future), hir_vec![generator])
888 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
890 F: FnOnce(&mut LoweringContext) -> hir::Expr,
892 let prev = mem::replace(&mut self.is_generator, false);
893 let result = f(self);
894 let r = self.record_body(result, decl);
895 self.is_generator = prev;
899 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
901 F: FnOnce(&mut LoweringContext) -> T,
903 // We're no longer in the base loop's condition; we're in another loop.
904 let was_in_loop_condition = self.is_in_loop_condition;
905 self.is_in_loop_condition = false;
907 let len = self.loop_scopes.len();
908 self.loop_scopes.push(loop_id);
910 let result = f(self);
913 self.loop_scopes.len(),
914 "Loop scopes should be added and removed in stack order"
917 self.loop_scopes.pop().unwrap();
919 self.is_in_loop_condition = was_in_loop_condition;
924 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
926 F: FnOnce(&mut LoweringContext) -> T,
928 let was_in_loop_condition = self.is_in_loop_condition;
929 self.is_in_loop_condition = true;
931 let result = f(self);
933 self.is_in_loop_condition = was_in_loop_condition;
938 fn with_new_scopes<T, F>(&mut self, f: F) -> T
940 F: FnOnce(&mut LoweringContext) -> T,
942 let was_in_loop_condition = self.is_in_loop_condition;
943 self.is_in_loop_condition = false;
945 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
946 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
947 let result = f(self);
948 self.catch_scopes = catch_scopes;
949 self.loop_scopes = loop_scopes;
951 self.is_in_loop_condition = was_in_loop_condition;
956 fn def_key(&mut self, id: DefId) -> DefKey {
958 self.resolver.definitions().def_key(id.index)
960 self.cstore.def_key(id)
964 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
965 label.map(|label| hir::Label {
970 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
972 Some((id, label)) => {
973 let target_id = if let Def::Label(loop_id) = self.expect_full_def(id) {
974 Ok(self.lower_node_id(loop_id).node_id)
976 Err(hir::LoopIdError::UnresolvedLabel)
979 label: self.lower_label(Some(label)),
984 let target_id = self.loop_scopes
986 .map(|innermost_loop_id| *innermost_loop_id)
987 .map(|id| Ok(self.lower_node_id(id).node_id))
988 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
999 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1002 .map(|a| self.lower_attr(a))
1003 .collect::<Vec<_>>()
1007 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1011 path: attr.path.clone(),
1012 tokens: self.lower_token_stream(attr.tokens.clone()),
1013 is_sugared_doc: attr.is_sugared_doc,
1018 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1021 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1025 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1027 TokenTree::Token(span, token) => self.lower_token(token, span),
1028 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1031 delim: delimited.delim,
1032 tts: self.lower_token_stream(delimited.tts.into()).into(),
1038 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1040 Token::Interpolated(_) => {}
1041 other => return TokenTree::Token(span, other).into(),
1044 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1045 self.lower_token_stream(tts)
1048 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1050 attrs: self.lower_attrs(&arm.attrs),
1051 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1052 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1053 body: P(self.lower_expr(&arm.body)),
1057 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1059 id: self.lower_node_id(b.id).node_id,
1061 ty: self.lower_ty(&b.ty, itctx),
1066 fn lower_generic_arg(&mut self,
1067 arg: &ast::GenericArg,
1068 itctx: ImplTraitContext)
1069 -> hir::GenericArg {
1071 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1072 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1076 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1077 P(self.lower_ty_direct(t, itctx))
1080 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext) -> hir::Ty {
1081 let kind = match t.node {
1082 TyKind::Infer => hir::TyInfer,
1083 TyKind::Err => hir::TyErr,
1084 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1085 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1086 TyKind::Rptr(ref region, ref mt) => {
1087 let span = t.span.shrink_to_lo();
1088 let lifetime = match *region {
1089 Some(ref lt) => self.lower_lifetime(lt),
1090 None => self.elided_ref_lifetime(span),
1092 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1094 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1097 this.with_anonymous_lifetime_mode(
1098 AnonymousLifetimeMode::PassThrough,
1100 hir::TyBareFn(P(hir::BareFnTy {
1101 generic_params: this.lower_generic_params(
1104 ImplTraitContext::Disallowed,
1106 unsafety: this.lower_unsafety(f.unsafety),
1108 decl: this.lower_fn_decl(&f.decl, None, false, None),
1109 arg_names: this.lower_fn_args_to_names(&f.decl),
1115 TyKind::Never => hir::TyNever,
1116 TyKind::Tup(ref tys) => {
1117 hir::TyTup(tys.iter().map(|ty| {
1118 self.lower_ty_direct(ty, itctx.reborrow())
1121 TyKind::Paren(ref ty) => {
1122 return self.lower_ty_direct(ty, itctx);
1124 TyKind::Path(ref qself, ref path) => {
1125 let id = self.lower_node_id(t.id);
1126 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1127 let ty = self.ty_path(id, t.span, qpath);
1128 if let hir::TyTraitObject(..) = ty.node {
1129 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1133 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1136 def: self.expect_full_def(t.id),
1137 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1141 TyKind::Array(ref ty, ref length) => {
1142 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1144 TyKind::Typeof(ref expr) => {
1145 hir::TyTypeof(self.lower_anon_const(expr))
1147 TyKind::TraitObject(ref bounds, kind) => {
1148 let mut lifetime_bound = None;
1151 .filter_map(|bound| match *bound {
1152 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1153 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1155 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1156 GenericBound::Outlives(ref lifetime) => {
1157 if lifetime_bound.is_none() {
1158 lifetime_bound = Some(self.lower_lifetime(lifetime));
1164 let lifetime_bound =
1165 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1166 if kind != TraitObjectSyntax::Dyn {
1167 self.maybe_lint_bare_trait(t.span, t.id, false);
1169 hir::TyTraitObject(bounds, lifetime_bound)
1171 TyKind::ImplTrait(def_node_id, ref bounds) => {
1174 ImplTraitContext::Existential(fn_def_id) => {
1175 self.lower_existential_impl_trait(
1176 span, fn_def_id, def_node_id,
1177 |this| this.lower_param_bounds(bounds, itctx),
1180 ImplTraitContext::Universal(in_band_ty_params) => {
1181 self.lower_node_id(def_node_id);
1182 // Add a definition for the in-band TyParam
1183 let def_index = self
1186 .opt_def_index(def_node_id)
1189 let hir_bounds = self.lower_param_bounds(
1191 ImplTraitContext::Universal(in_band_ty_params),
1193 // Set the name to `impl Bound1 + Bound2`
1194 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1195 in_band_ty_params.push(hir::GenericParam {
1197 name: ParamName::Plain(ident),
1198 pure_wrt_drop: false,
1202 kind: hir::GenericParamKind::Type {
1204 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1208 hir::TyPath(hir::QPath::Resolved(
1212 def: Def::TyParam(DefId::local(def_index)),
1213 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1217 ImplTraitContext::Disallowed => {
1222 "`impl Trait` not allowed outside of function \
1223 and inherent method return types"
1229 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1232 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1241 fn lower_existential_impl_trait(
1245 exist_ty_node_id: NodeId,
1246 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1248 // Make sure we know that some funky desugaring has been going on here.
1249 // This is a first: there is code in other places like for loop
1250 // desugaring that explicitly states that we don't want to track that.
1251 // Not tracking it makes lints in rustc and clippy very fragile as
1252 // frequently opened issues show.
1253 let exist_ty_span = self.allow_internal_unstable(
1254 CompilerDesugaringKind::ExistentialReturnType,
1258 let exist_ty_def_index = self
1261 .opt_def_index(exist_ty_node_id)
1265 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1267 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1269 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1275 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1276 let exist_ty_item_kind = hir::ItemExistential(hir::ExistTy {
1277 generics: hir::Generics {
1278 params: lifetime_defs,
1279 where_clause: hir::WhereClause {
1280 id: lctx.next_id().node_id,
1281 predicates: Vec::new().into(),
1286 impl_trait_fn: Some(fn_def_id),
1288 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1289 // Generate an `existential type Foo: Trait;` declaration
1290 trace!("creating existential type with id {:#?}", exist_ty_id);
1292 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1293 let exist_ty_item = hir::Item {
1294 id: exist_ty_id.node_id,
1295 hir_id: exist_ty_id.hir_id,
1296 name: keywords::Invalid.name(),
1297 attrs: Default::default(),
1298 node: exist_ty_item_kind,
1299 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1300 span: exist_ty_span,
1303 // Insert the item into the global list. This usually happens
1304 // automatically for all AST items. But this existential type item
1305 // does not actually exist in the AST.
1306 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1308 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1309 hir::TyImplTraitExistential(
1311 id: exist_ty_id.node_id
1313 DefId::local(exist_ty_def_index),
1319 fn lifetimes_from_impl_trait_bounds(
1321 exist_ty_id: NodeId,
1322 parent_index: DefIndex,
1323 bounds: &hir::GenericBounds,
1324 ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1325 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1326 // appear in the bounds, excluding lifetimes that are created within the bounds.
1327 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1328 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1329 context: &'r mut LoweringContext<'a>,
1331 exist_ty_id: NodeId,
1332 collect_elided_lifetimes: bool,
1333 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1334 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1335 output_lifetimes: Vec<hir::Lifetime>,
1336 output_lifetime_params: Vec<hir::GenericParam>,
1339 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1340 fn nested_visit_map<'this>(
1342 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1343 hir::intravisit::NestedVisitorMap::None
1346 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1347 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1348 if parameters.parenthesized {
1349 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1350 self.collect_elided_lifetimes = false;
1351 hir::intravisit::walk_generic_args(self, span, parameters);
1352 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1354 hir::intravisit::walk_generic_args(self, span, parameters);
1358 fn visit_ty(&mut self, t: &'v hir::Ty) {
1359 // Don't collect elided lifetimes used inside of `fn()` syntax
1360 if let hir::Ty_::TyBareFn(_) = t.node {
1361 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1362 self.collect_elided_lifetimes = false;
1364 // Record the "stack height" of `for<'a>` lifetime bindings
1365 // to be able to later fully undo their introduction.
1366 let old_len = self.currently_bound_lifetimes.len();
1367 hir::intravisit::walk_ty(self, t);
1368 self.currently_bound_lifetimes.truncate(old_len);
1370 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1372 hir::intravisit::walk_ty(self, t)
1376 fn visit_poly_trait_ref(
1378 trait_ref: &'v hir::PolyTraitRef,
1379 modifier: hir::TraitBoundModifier,
1381 // Record the "stack height" of `for<'a>` lifetime bindings
1382 // to be able to later fully undo their introduction.
1383 let old_len = self.currently_bound_lifetimes.len();
1384 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1385 self.currently_bound_lifetimes.truncate(old_len);
1388 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1389 // Record the introduction of 'a in `for<'a> ...`
1390 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1391 // Introduce lifetimes one at a time so that we can handle
1392 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1393 let lt_name = hir::LifetimeName::Param(param.name);
1394 self.currently_bound_lifetimes.push(lt_name);
1397 hir::intravisit::walk_generic_param(self, param);
1400 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1401 let name = match lifetime.name {
1402 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1403 if self.collect_elided_lifetimes {
1404 // Use `'_` for both implicit and underscore lifetimes in
1405 // `abstract type Foo<'_>: SomeTrait<'_>;`
1406 hir::LifetimeName::Underscore
1411 hir::LifetimeName::Param(_) => lifetime.name,
1412 hir::LifetimeName::Static => return,
1415 if !self.currently_bound_lifetimes.contains(&name)
1416 && !self.already_defined_lifetimes.contains(&name) {
1417 self.already_defined_lifetimes.insert(name);
1419 self.output_lifetimes.push(hir::Lifetime {
1420 id: self.context.next_id().node_id,
1421 span: lifetime.span,
1425 // We need to manually create the ids here, because the
1426 // definitions will go into the explicit `existential type`
1427 // declaration and thus need to have their owner set to that item
1428 let def_node_id = self.context.sess.next_node_id();
1429 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1430 self.context.resolver.definitions().create_def_with_parent(
1433 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1434 DefIndexAddressSpace::High,
1439 let name = match name {
1440 hir::LifetimeName::Underscore => {
1441 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident())
1443 hir::LifetimeName::Param(param_name) => param_name,
1444 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1447 self.output_lifetime_params.push(hir::GenericParam {
1450 span: lifetime.span,
1451 pure_wrt_drop: false,
1454 kind: hir::GenericParamKind::Lifetime {
1462 let mut lifetime_collector = ImplTraitLifetimeCollector {
1464 parent: parent_index,
1466 collect_elided_lifetimes: true,
1467 currently_bound_lifetimes: Vec::new(),
1468 already_defined_lifetimes: HashSet::new(),
1469 output_lifetimes: Vec::new(),
1470 output_lifetime_params: Vec::new(),
1473 for bound in bounds {
1474 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1478 lifetime_collector.output_lifetimes.into(),
1479 lifetime_collector.output_lifetime_params.into(),
1483 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1488 .map(|x| self.lower_foreign_item(x))
1493 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1500 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1502 node: hir::Variant_ {
1503 name: v.node.ident.name,
1504 attrs: self.lower_attrs(&v.node.attrs),
1505 data: self.lower_variant_data(&v.node.data),
1506 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1515 qself: &Option<QSelf>,
1517 param_mode: ParamMode,
1518 mut itctx: ImplTraitContext,
1520 let qself_position = qself.as_ref().map(|q| q.position);
1521 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1523 let resolution = self.resolver
1525 .unwrap_or(PathResolution::new(Def::Err));
1527 let proj_start = p.segments.len() - resolution.unresolved_segments();
1528 let path = P(hir::Path {
1529 def: resolution.base_def(),
1530 segments: p.segments[..proj_start]
1533 .map(|(i, segment)| {
1534 let param_mode = match (qself_position, param_mode) {
1535 (Some(j), ParamMode::Optional) if i < j => {
1536 // This segment is part of the trait path in a
1537 // qualified path - one of `a`, `b` or `Trait`
1538 // in `<X as a::b::Trait>::T::U::method`.
1544 // Figure out if this is a type/trait segment,
1545 // which may need lifetime elision performed.
1546 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1547 krate: def_id.krate,
1548 index: this.def_key(def_id).parent.expect("missing parent"),
1550 let type_def_id = match resolution.base_def() {
1551 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1552 Some(parent_def_id(self, def_id))
1554 Def::Variant(def_id) if i + 1 == proj_start => {
1555 Some(parent_def_id(self, def_id))
1558 | Def::Union(def_id)
1560 | Def::TyAlias(def_id)
1561 | Def::Trait(def_id) if i + 1 == proj_start =>
1567 let parenthesized_generic_args = match resolution.base_def() {
1568 // `a::b::Trait(Args)`
1569 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1570 // `a::b::Trait(Args)::TraitItem`
1571 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1572 if i + 2 == proj_start =>
1574 ParenthesizedGenericArgs::Ok
1576 // Avoid duplicated errors
1577 Def::Err => ParenthesizedGenericArgs::Ok,
1583 | Def::Variant(..) if i + 1 == proj_start =>
1585 ParenthesizedGenericArgs::Err
1587 // A warning for now, for compatibility reasons
1588 _ => ParenthesizedGenericArgs::Warn,
1591 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1592 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1595 assert!(!def_id.is_local());
1597 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1598 let n = item_generics.own_counts().lifetimes;
1599 self.type_def_lifetime_params.insert(def_id, n);
1602 self.lower_path_segment(
1607 parenthesized_generic_args,
1615 // Simple case, either no projections, or only fully-qualified.
1616 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1617 if resolution.unresolved_segments() == 0 {
1618 return hir::QPath::Resolved(qself, path);
1621 // Create the innermost type that we're projecting from.
1622 let mut ty = if path.segments.is_empty() {
1623 // If the base path is empty that means there exists a
1624 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1625 qself.expect("missing QSelf for <T>::...")
1627 // Otherwise, the base path is an implicit `Self` type path,
1628 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1629 // `<I as Iterator>::Item::default`.
1630 let new_id = self.next_id();
1631 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1634 // Anything after the base path are associated "extensions",
1635 // out of which all but the last one are associated types,
1636 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1637 // * base path is `std::vec::Vec<T>`
1638 // * "extensions" are `IntoIter`, `Item` and `clone`
1639 // * type nodes are:
1640 // 1. `std::vec::Vec<T>` (created above)
1641 // 2. `<std::vec::Vec<T>>::IntoIter`
1642 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1643 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1644 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1645 let segment = P(self.lower_path_segment(
1650 ParenthesizedGenericArgs::Warn,
1653 let qpath = hir::QPath::TypeRelative(ty, segment);
1655 // It's finished, return the extension of the right node type.
1656 if i == p.segments.len() - 1 {
1660 // Wrap the associated extension in another type node.
1661 let new_id = self.next_id();
1662 ty = P(self.ty_path(new_id, p.span, qpath));
1665 // Should've returned in the for loop above.
1668 "lower_qpath: no final extension segment in {}..{}",
1674 fn lower_path_extra(
1678 ident: Option<Ident>,
1679 param_mode: ParamMode,
1683 segments: p.segments
1686 self.lower_path_segment(
1691 ParenthesizedGenericArgs::Err,
1692 ImplTraitContext::Disallowed,
1695 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1701 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1702 let def = self.expect_full_def(id);
1703 self.lower_path_extra(def, p, None, param_mode)
1706 fn lower_path_segment(
1709 segment: &PathSegment,
1710 param_mode: ParamMode,
1711 expected_lifetimes: usize,
1712 parenthesized_generic_args: ParenthesizedGenericArgs,
1713 itctx: ImplTraitContext,
1714 ) -> hir::PathSegment {
1715 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1716 let msg = "parenthesized parameters may only be used with a trait";
1717 match **generic_args {
1718 GenericArgs::AngleBracketed(ref data) => {
1719 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1721 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1722 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1723 ParenthesizedGenericArgs::Warn => {
1724 self.sess.buffer_lint(
1725 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1730 (hir::GenericArgs::none(), true)
1732 ParenthesizedGenericArgs::Err => {
1733 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1734 .span_label(data.span, "only traits may use parentheses")
1736 (hir::GenericArgs::none(), true)
1741 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1744 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1745 GenericArg::Lifetime(_) => true,
1748 if !generic_args.parenthesized && !has_lifetimes {
1750 self.elided_path_lifetimes(path_span, expected_lifetimes)
1752 .map(|lt| GenericArg::Lifetime(lt))
1753 .chain(generic_args.args.into_iter())
1757 hir::PathSegment::new(
1764 fn lower_angle_bracketed_parameter_data(
1766 data: &AngleBracketedArgs,
1767 param_mode: ParamMode,
1768 mut itctx: ImplTraitContext,
1769 ) -> (hir::GenericArgs, bool) {
1770 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1771 let has_types = args.iter().any(|arg| match arg {
1772 ast::GenericArg::Type(_) => true,
1776 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1777 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1778 parenthesized: false,
1780 !has_types && param_mode == ParamMode::Optional)
1783 fn lower_parenthesized_parameter_data(
1785 data: &ParenthesisedArgs,
1786 ) -> (hir::GenericArgs, bool) {
1787 // Switch to `PassThrough` mode for anonymous lifetimes: this
1788 // means that we permit things like `&Ref<T>`, where `Ref` has
1789 // a hidden lifetime parameter. This is needed for backwards
1790 // compatibility, even in contexts like an impl header where
1791 // we generally don't permit such things (see #51008).
1792 self.with_anonymous_lifetime_mode(
1793 AnonymousLifetimeMode::PassThrough,
1795 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1796 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1797 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1798 let mk_tup = |this: &mut Self, tys, span| {
1799 let LoweredNodeId { node_id, hir_id } = this.next_id();
1800 hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span }
1805 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1808 id: this.next_id().node_id,
1809 ident: Ident::from_str(FN_OUTPUT_NAME),
1812 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1813 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1814 span: output.as_ref().map_or(span, |ty| ty.span),
1817 parenthesized: true,
1825 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1826 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1832 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1833 pat: self.lower_pat(&l.pat),
1834 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1836 attrs: l.attrs.clone(),
1837 source: hir::LocalSource::Normal,
1841 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1843 Mutability::Mutable => hir::MutMutable,
1844 Mutability::Immutable => hir::MutImmutable,
1848 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1849 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1853 pat: self.lower_pat(&arg.pat),
1857 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1860 .map(|arg| match arg.pat.node {
1861 PatKind::Ident(_, ident, _) => ident,
1862 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1867 // Lowers a function declaration.
1869 // decl: the unlowered (ast) function declaration.
1870 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1871 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1872 // make_ret_async is also `Some`.
1873 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1874 // This guards against trait declarations and implementations where impl Trait is
1876 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1877 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1878 // return type impl Trait item.
1882 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
1883 impl_trait_return_allow: bool,
1884 make_ret_async: Option<NodeId>,
1885 ) -> P<hir::FnDecl> {
1886 let inputs = decl.inputs
1889 if let Some((_, ref mut ibty)) = in_band_ty_params {
1890 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
1892 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
1895 .collect::<HirVec<_>>();
1897 let output = if let Some(ret_id) = make_ret_async {
1898 self.lower_async_fn_ret_ty(
1901 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
1906 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
1907 Some((def_id, _)) if impl_trait_return_allow => {
1908 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1910 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1912 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1919 variadic: decl.variadic,
1920 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1921 TyKind::ImplicitSelf => true,
1922 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1928 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
1930 // fn_span: the span of the async function declaration. Used for error reporting.
1931 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
1932 // output: unlowered output type (`T` in `-> T`)
1933 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
1934 fn lower_async_fn_ret_ty(
1937 output: &FunctionRetTy,
1939 return_impl_trait_id: NodeId,
1940 ) -> hir::FunctionRetTy {
1941 // Get lifetimes used in the input arguments to the function. Our output type must also
1942 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
1943 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
1944 // is a subset of the other. We really want some new lifetime that is a subset of all input
1945 // lifetimes, but that doesn't exist at the moment.
1947 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
1948 context: &'r mut LoweringContext<'a>,
1949 // Lifetimes bound by HRTB
1950 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1951 // Whether to count elided lifetimes.
1952 // Disabled inside of `Fn` or `fn` syntax.
1953 collect_elided_lifetimes: bool,
1954 // The lifetime found.
1955 // Multiple different or elided lifetimes cannot appear in async fn for now.
1956 output_lifetime: Option<(hir::LifetimeName, Span)>,
1959 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
1960 fn nested_visit_map<'this>(
1962 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1963 hir::intravisit::NestedVisitorMap::None
1966 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1967 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1968 if parameters.parenthesized {
1969 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1970 self.collect_elided_lifetimes = false;
1971 hir::intravisit::walk_generic_args(self, span, parameters);
1972 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1974 hir::intravisit::walk_generic_args(self, span, parameters);
1978 fn visit_ty(&mut self, t: &'v hir::Ty) {
1979 // Don't collect elided lifetimes used inside of `fn()` syntax
1980 if let &hir::Ty_::TyBareFn(_) = &t.node {
1981 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1982 self.collect_elided_lifetimes = false;
1984 // Record the "stack height" of `for<'a>` lifetime bindings
1985 // to be able to later fully undo their introduction.
1986 let old_len = self.currently_bound_lifetimes.len();
1987 hir::intravisit::walk_ty(self, t);
1988 self.currently_bound_lifetimes.truncate(old_len);
1990 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1992 hir::intravisit::walk_ty(self, t);
1996 fn visit_poly_trait_ref(
1998 trait_ref: &'v hir::PolyTraitRef,
1999 modifier: hir::TraitBoundModifier,
2001 // Record the "stack height" of `for<'a>` lifetime bindings
2002 // to be able to later fully undo their introduction.
2003 let old_len = self.currently_bound_lifetimes.len();
2004 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2005 self.currently_bound_lifetimes.truncate(old_len);
2008 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2009 // Record the introduction of 'a in `for<'a> ...`
2010 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2011 // Introduce lifetimes one at a time so that we can handle
2012 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2013 let lt_name = hir::LifetimeName::Param(param.name);
2014 self.currently_bound_lifetimes.push(lt_name);
2017 hir::intravisit::walk_generic_param(self, param);
2020 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2021 let name = match lifetime.name {
2022 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2023 if self.collect_elided_lifetimes {
2024 // Use `'_` for both implicit and underscore lifetimes in
2025 // `abstract type Foo<'_>: SomeTrait<'_>;`
2026 hir::LifetimeName::Underscore
2031 hir::LifetimeName::Param(_) => lifetime.name,
2032 hir::LifetimeName::Static => return,
2035 if !self.currently_bound_lifetimes.contains(&name) {
2036 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2037 // We don't currently have a reliable way to desugar `async fn` with
2038 // multiple potentially unrelated input lifetimes into
2039 // `-> impl Trait + 'lt`, so we report an error in this case.
2040 if current_lt_name != name {
2043 current_lt_span.between(lifetime.span),
2045 "multiple different lifetimes used in arguments of `async fn`",
2047 .span_label(current_lt_span, "first lifetime here")
2048 .span_label(lifetime.span, "different lifetime here")
2049 .help("`async fn` can only accept borrowed values \
2050 with identical lifetimes")
2052 } else if current_lt_name.is_elided() && name.is_elided() {
2055 current_lt_span.between(lifetime.span),
2057 "multiple elided lifetimes used in arguments of `async fn`",
2059 .span_label(current_lt_span, "first lifetime here")
2060 .span_label(lifetime.span, "different lifetime here")
2061 .help("consider giving these arguments named lifetimes")
2065 self.output_lifetime = Some((name, lifetime.span));
2071 let bound_lifetime = {
2072 let mut lifetime_collector = AsyncFnLifetimeCollector {
2074 currently_bound_lifetimes: Vec::new(),
2075 collect_elided_lifetimes: true,
2076 output_lifetime: None,
2080 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2082 lifetime_collector.output_lifetime
2085 let span = match output {
2086 FunctionRetTy::Ty(ty) => ty.span,
2087 FunctionRetTy::Default(span) => *span,
2090 let impl_trait_ty = self.lower_existential_impl_trait(
2091 span, fn_def_id, return_impl_trait_id, |this| {
2092 let output_ty = match output {
2093 FunctionRetTy::Ty(ty) =>
2094 this.lower_ty(ty, ImplTraitContext::Existential(fn_def_id)),
2095 FunctionRetTy::Default(span) => {
2096 let LoweredNodeId { node_id, hir_id } = this.next_id();
2100 node: hir::TyTup(hir_vec![]),
2107 let future_params = P(hir::GenericArgs {
2109 bindings: hir_vec![hir::TypeBinding {
2110 ident: Ident::from_str(FN_OUTPUT_NAME),
2112 id: this.next_id().node_id,
2115 parenthesized: false,
2119 this.std_path(span, &["future", "Future"], Some(future_params), false);
2121 let mut bounds = vec![
2122 hir::GenericBound::Trait(
2124 trait_ref: hir::TraitRef {
2126 ref_id: this.next_id().node_id,
2128 bound_generic_params: hir_vec![],
2131 hir::TraitBoundModifier::None
2135 if let Some((name, span)) = bound_lifetime {
2136 bounds.push(hir::GenericBound::Outlives(
2137 hir::Lifetime { id: this.next_id().node_id, name, span }));
2140 hir::HirVec::from(bounds)
2143 let LoweredNodeId { node_id, hir_id } = self.next_id();
2144 let impl_trait_ty = P(hir::Ty {
2146 node: impl_trait_ty,
2151 hir::FunctionRetTy::Return(impl_trait_ty)
2154 fn lower_param_bound(
2157 itctx: ImplTraitContext,
2158 ) -> hir::GenericBound {
2160 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2161 self.lower_poly_trait_ref(ty, itctx),
2162 self.lower_trait_bound_modifier(modifier),
2164 GenericBound::Outlives(ref lifetime) => {
2165 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2170 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2171 let span = l.ident.span;
2173 ident if ident.name == keywords::StaticLifetime.name() =>
2174 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2175 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2176 match self.anonymous_lifetime_mode {
2177 AnonymousLifetimeMode::CreateParameter => {
2178 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2179 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2182 AnonymousLifetimeMode::PassThrough => {
2183 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2187 self.maybe_collect_in_band_lifetime(ident);
2188 let param_name = ParamName::Plain(ident);
2189 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2194 fn new_named_lifetime(
2198 name: hir::LifetimeName,
2199 ) -> hir::Lifetime {
2201 id: self.lower_node_id(id).node_id,
2207 fn lower_generic_params(
2209 params: &Vec<GenericParam>,
2210 add_bounds: &NodeMap<Vec<GenericBound>>,
2211 mut itctx: ImplTraitContext,
2212 ) -> hir::HirVec<hir::GenericParam> {
2213 params.iter().map(|param| {
2214 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2218 fn lower_generic_param(&mut self,
2219 param: &GenericParam,
2220 add_bounds: &NodeMap<Vec<GenericBound>>,
2221 mut itctx: ImplTraitContext)
2222 -> hir::GenericParam {
2223 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx.reborrow());
2225 GenericParamKind::Lifetime => {
2226 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2227 self.is_collecting_in_band_lifetimes = false;
2229 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2230 let param_name = match lt.name {
2231 hir::LifetimeName::Param(param_name) => param_name,
2232 _ => hir::ParamName::Plain(lt.name.ident()),
2234 let param = hir::GenericParam {
2238 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2239 attrs: self.lower_attrs(¶m.attrs),
2241 kind: hir::GenericParamKind::Lifetime { in_band: false }
2244 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2248 GenericParamKind::Type { ref default, .. } => {
2249 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2250 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2251 // Instead, use gensym("Self") to create a distinct name that looks the same.
2252 let ident = if param.ident.name == keywords::SelfType.name() {
2253 param.ident.gensym()
2258 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2259 if !add_bounds.is_empty() {
2260 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2261 bounds = bounds.into_iter()
2267 id: self.lower_node_id(param.id).node_id,
2268 name: hir::ParamName::Plain(ident),
2269 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2270 attrs: self.lower_attrs(¶m.attrs),
2273 kind: hir::GenericParamKind::Type {
2274 default: default.as_ref().map(|x| {
2275 self.lower_ty(x, ImplTraitContext::Disallowed)
2277 synthetic: param.attrs.iter()
2278 .filter(|attr| attr.check_name("rustc_synthetic"))
2279 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2289 generics: &Generics,
2290 itctx: ImplTraitContext)
2293 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2294 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2295 // paths where report_error is called are also the only paths that advance to after
2296 // the match statement, so the error reporting could probably just be moved there.
2297 let mut add_bounds = NodeMap();
2298 for pred in &generics.where_clause.predicates {
2299 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2300 'next_bound: for bound in &bound_pred.bounds {
2301 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2302 let report_error = |this: &mut Self| {
2303 this.diagnostic().span_err(
2304 bound_pred.bounded_ty.span,
2305 "`?Trait` bounds are only permitted at the \
2306 point where a type parameter is declared",
2309 // Check if the where clause type is a plain type parameter.
2310 match bound_pred.bounded_ty.node {
2311 TyKind::Path(None, ref path)
2312 if path.segments.len() == 1
2313 && bound_pred.bound_generic_params.is_empty() =>
2315 if let Some(Def::TyParam(def_id)) = self.resolver
2316 .get_resolution(bound_pred.bounded_ty.id)
2317 .map(|d| d.base_def())
2319 if let Some(node_id) =
2320 self.resolver.definitions().as_local_node_id(def_id)
2322 for param in &generics.params {
2324 GenericParamKind::Type { .. } => {
2325 if node_id == param.id {
2326 add_bounds.entry(param.id)
2327 .or_insert(Vec::new())
2328 .push(bound.clone());
2329 continue 'next_bound;
2339 _ => report_error(self),
2347 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2348 where_clause: self.lower_where_clause(&generics.where_clause),
2349 span: generics.span,
2353 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2355 id: self.lower_node_id(wc.id).node_id,
2356 predicates: wc.predicates
2358 .map(|predicate| self.lower_where_predicate(predicate))
2363 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2365 WherePredicate::BoundPredicate(WhereBoundPredicate {
2366 ref bound_generic_params,
2371 self.with_in_scope_lifetime_defs(
2372 &bound_generic_params,
2374 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2375 bound_generic_params: this.lower_generic_params(
2376 bound_generic_params,
2378 ImplTraitContext::Disallowed,
2380 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2383 .filter_map(|bound| match *bound {
2384 // Ignore `?Trait` bounds.
2385 // Tthey were copied into type parameters already.
2386 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2387 _ => Some(this.lower_param_bound(
2389 ImplTraitContext::Disallowed,
2398 WherePredicate::RegionPredicate(WhereRegionPredicate {
2402 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2404 lifetime: self.lower_lifetime(lifetime),
2405 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2407 WherePredicate::EqPredicate(WhereEqPredicate {
2412 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2413 id: self.lower_node_id(id).node_id,
2414 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2415 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2421 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2423 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2427 .map(|f| self.lower_struct_field(f))
2429 self.lower_node_id(id).node_id,
2431 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2435 .map(|f| self.lower_struct_field(f))
2437 self.lower_node_id(id).node_id,
2439 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2443 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2444 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2445 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2446 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2450 ref_id: self.lower_node_id(p.ref_id).node_id,
2454 fn lower_poly_trait_ref(
2457 mut itctx: ImplTraitContext,
2458 ) -> hir::PolyTraitRef {
2459 let bound_generic_params =
2460 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2461 let trait_ref = self.with_parent_impl_lifetime_defs(
2462 &bound_generic_params,
2463 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2467 bound_generic_params,
2473 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2476 id: self.lower_node_id(f.id).node_id,
2477 ident: match f.ident {
2478 Some(ident) => ident,
2479 // FIXME(jseyfried) positional field hygiene
2480 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2482 vis: self.lower_visibility(&f.vis, None),
2483 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2484 attrs: self.lower_attrs(&f.attrs),
2488 fn lower_field(&mut self, f: &Field) -> hir::Field {
2490 id: self.next_id().node_id,
2492 expr: P(self.lower_expr(&f.expr)),
2494 is_shorthand: f.is_shorthand,
2498 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2500 ty: self.lower_ty(&mt.ty, itctx),
2501 mutbl: self.lower_mutability(mt.mutbl),
2505 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext)
2506 -> hir::GenericBounds {
2507 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2510 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2511 let mut expr = None;
2513 let mut stmts = vec![];
2515 for (index, stmt) in b.stmts.iter().enumerate() {
2516 if index == b.stmts.len() - 1 {
2517 if let StmtKind::Expr(ref e) = stmt.node {
2518 expr = Some(P(self.lower_expr(e)));
2520 stmts.extend(self.lower_stmt(stmt));
2523 stmts.extend(self.lower_stmt(stmt));
2527 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2532 stmts: stmts.into(),
2534 rules: self.lower_block_check_mode(&b.rules),
2537 recovered: b.recovered,
2541 fn lower_async_body(
2547 self.lower_body(Some(decl), |this| {
2548 if let IsAsync::Async { closure_id, .. } = asyncness {
2549 let async_expr = this.make_async_expr(
2550 CaptureBy::Value, closure_id, None,
2552 let body = this.lower_block(body, false);
2553 this.expr_block(body, ThinVec::new())
2555 this.expr(body.span, async_expr, ThinVec::new())
2557 let body = this.lower_block(body, false);
2558 this.expr_block(body, ThinVec::new())
2567 attrs: &hir::HirVec<Attribute>,
2568 vis: &mut hir::Visibility,
2572 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2573 ItemKind::Use(ref use_tree) => {
2574 // Start with an empty prefix
2577 span: use_tree.span,
2580 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2582 ItemKind::Static(ref t, m, ref e) => {
2583 let value = self.lower_body(None, |this| this.lower_expr(e));
2585 self.lower_ty(t, ImplTraitContext::Disallowed),
2586 self.lower_mutability(m),
2590 ItemKind::Const(ref t, ref e) => {
2591 let value = self.lower_body(None, |this| this.lower_expr(e));
2592 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2594 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2595 let fn_def_id = self.resolver.definitions().local_def_id(id);
2597 self.with_new_scopes(|this| {
2598 // Note: we don't need to change the return type from `T` to
2599 // `impl Future<Output = T>` here because lower_body
2600 // only cares about the input argument patterns in the function
2601 // declaration (decl), not the return types.
2602 let body_id = this.lower_async_body(decl, header.asyncness, body);
2604 let (generics, fn_decl) = this.add_in_band_defs(
2607 AnonymousLifetimeMode::PassThrough,
2608 |this, idty| this.lower_fn_decl(
2609 decl, Some((fn_def_id, idty)), true, header.asyncness.opt_return_id()),
2614 this.lower_fn_header(header),
2620 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2621 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2622 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2623 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2624 self.lower_ty(t, ImplTraitContext::Disallowed),
2625 self.lower_generics(generics, ImplTraitContext::Disallowed),
2627 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2629 variants: enum_definition
2632 .map(|x| self.lower_variant(x))
2635 self.lower_generics(generics, ImplTraitContext::Disallowed),
2637 ItemKind::Struct(ref struct_def, ref generics) => {
2638 let struct_def = self.lower_variant_data(struct_def);
2641 self.lower_generics(generics, ImplTraitContext::Disallowed),
2644 ItemKind::Union(ref vdata, ref generics) => {
2645 let vdata = self.lower_variant_data(vdata);
2648 self.lower_generics(generics, ImplTraitContext::Disallowed),
2660 let def_id = self.resolver.definitions().local_def_id(id);
2662 // Lower the "impl header" first. This ordering is important
2663 // for in-band lifetimes! Consider `'a` here:
2665 // impl Foo<'a> for u32 {
2666 // fn method(&'a self) { .. }
2669 // Because we start by lowering the `Foo<'a> for u32`
2670 // part, we will add `'a` to the list of generics on
2671 // the impl. When we then encounter it later in the
2672 // method, it will not be considered an in-band
2673 // lifetime to be added, but rather a reference to a
2675 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2678 AnonymousLifetimeMode::CreateParameter,
2680 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2681 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2684 if let Some(ref trait_ref) = trait_ref {
2685 if let Def::Trait(def_id) = trait_ref.path.def {
2686 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2690 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2692 (trait_ref, lowered_ty)
2696 let new_impl_items = self.with_in_scope_lifetime_defs(
2697 &ast_generics.params,
2701 .map(|item| this.lower_impl_item_ref(item))
2707 self.lower_unsafety(unsafety),
2708 self.lower_impl_polarity(polarity),
2709 self.lower_defaultness(defaultness, true /* [1] */),
2716 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2717 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2720 .map(|item| self.lower_trait_item_ref(item))
2723 self.lower_is_auto(is_auto),
2724 self.lower_unsafety(unsafety),
2725 self.lower_generics(generics, ImplTraitContext::Disallowed),
2730 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2731 self.lower_generics(generics, ImplTraitContext::Disallowed),
2732 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2734 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2737 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2738 // not cause an assertion failure inside the `lower_defaultness` function
2746 vis: &mut hir::Visibility,
2748 attrs: &hir::HirVec<Attribute>,
2750 let path = &tree.prefix;
2753 UseTreeKind::Simple(rename, id1, id2) => {
2754 *name = tree.ident().name;
2756 // First apply the prefix to the path
2757 let mut path = Path {
2761 .chain(path.segments.iter())
2767 // Correctly resolve `self` imports
2768 if path.segments.len() > 1
2769 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2771 let _ = path.segments.pop();
2772 if rename.is_none() {
2773 *name = path.segments.last().unwrap().ident.name;
2777 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2778 let mut defs = self.expect_full_def_from_use(id);
2779 // we want to return *something* from this function, so hang onto the first item
2781 let mut ret_def = defs.next().unwrap_or(Def::Err);
2783 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2784 let vis = vis.clone();
2785 let name = name.clone();
2786 let span = path.span;
2787 self.resolver.definitions().create_def_with_parent(
2791 DefIndexAddressSpace::High,
2794 self.allocate_hir_id_counter(new_node_id, &path);
2796 self.with_hir_id_owner(new_node_id, |this| {
2797 let new_id = this.lower_node_id(new_node_id);
2798 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2799 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2800 let vis_kind = match vis.node {
2801 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2802 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2803 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2804 hir::VisibilityKind::Restricted { ref path, id: _ } => {
2805 hir::VisibilityKind::Restricted {
2807 // We are allocating a new NodeId here
2808 id: this.next_id().node_id,
2812 let vis = respan(vis.span, vis_kind);
2818 hir_id: new_id.hir_id,
2820 attrs: attrs.clone(),
2829 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2830 hir::ItemUse(path, hir::UseKind::Single)
2832 UseTreeKind::Glob => {
2833 let path = P(self.lower_path(
2839 .chain(path.segments.iter())
2844 ParamMode::Explicit,
2846 hir::ItemUse(path, hir::UseKind::Glob)
2848 UseTreeKind::Nested(ref trees) => {
2853 .chain(path.segments.iter())
2856 span: prefix.span.to(path.span),
2859 // Add all the nested PathListItems in the HIR
2860 for &(ref use_tree, id) in trees {
2861 self.allocate_hir_id_counter(id, &use_tree);
2865 } = self.lower_node_id(id);
2867 let mut vis = vis.clone();
2868 let mut name = name.clone();
2870 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2872 self.with_hir_id_owner(new_id, |this| {
2873 let vis_kind = match vis.node {
2874 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2875 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2876 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2877 hir::VisibilityKind::Restricted { ref path, id: _ } => {
2878 hir::VisibilityKind::Restricted {
2880 // We are allocating a new NodeId here
2881 id: this.next_id().node_id,
2885 let vis = respan(vis.span, vis_kind);
2893 attrs: attrs.clone(),
2896 span: use_tree.span,
2902 // Privatize the degenerate import base, used only to check
2903 // the stability of `use a::{};`, to avoid it showing up as
2904 // a re-export by accident when `pub`, e.g. in documentation.
2905 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2906 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
2907 hir::ItemUse(path, hir::UseKind::ListStem)
2912 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2913 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2914 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2916 let (generics, node) = match i.node {
2917 TraitItemKind::Const(ref ty, ref default) => (
2918 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2919 hir::TraitItemKind::Const(
2920 self.lower_ty(ty, ImplTraitContext::Disallowed),
2923 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2926 TraitItemKind::Method(ref sig, None) => {
2927 let names = self.lower_fn_args_to_names(&sig.decl);
2928 let (generics, sig) = self.lower_method_sig(
2935 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
2937 TraitItemKind::Method(ref sig, Some(ref body)) => {
2938 let body_id = self.lower_body(Some(&sig.decl), |this| {
2939 let body = this.lower_block(body, false);
2940 this.expr_block(body, ThinVec::new())
2943 let (generics, sig) = self.lower_method_sig(
2951 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
2953 TraitItemKind::Type(ref bounds, ref default) => (
2954 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2955 hir::TraitItemKind::Type(
2956 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2959 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2962 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2969 attrs: self.lower_attrs(&i.attrs),
2976 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2977 let (kind, has_default) = match i.node {
2978 TraitItemKind::Const(_, ref default) => {
2979 (hir::AssociatedItemKind::Const, default.is_some())
2981 TraitItemKind::Type(_, ref default) => {
2982 (hir::AssociatedItemKind::Type, default.is_some())
2984 TraitItemKind::Method(ref sig, ref default) => (
2985 hir::AssociatedItemKind::Method {
2986 has_self: sig.decl.has_self(),
2990 TraitItemKind::Macro(..) => unimplemented!(),
2993 id: hir::TraitItemId { node_id: i.id },
2996 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3001 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3002 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3003 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3005 let (generics, node) = match i.node {
3006 ImplItemKind::Const(ref ty, ref expr) => {
3007 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3009 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3010 hir::ImplItemKind::Const(
3011 self.lower_ty(ty, ImplTraitContext::Disallowed),
3016 ImplItemKind::Method(ref sig, ref body) => {
3017 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3018 let impl_trait_return_allow = !self.is_in_trait_impl;
3019 let (generics, sig) = self.lower_method_sig(
3023 impl_trait_return_allow,
3024 sig.header.asyncness.opt_return_id(),
3026 (generics, hir::ImplItemKind::Method(sig, body_id))
3028 ImplItemKind::Type(ref ty) => (
3029 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3030 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3032 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3039 attrs: self.lower_attrs(&i.attrs),
3041 vis: self.lower_visibility(&i.vis, None),
3042 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3047 // [1] since `default impl` is not yet implemented, this is always true in impls
3050 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3052 id: hir::ImplItemId { node_id: i.id },
3055 vis: self.lower_visibility(&i.vis, Some(i.id)),
3056 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3057 kind: match i.node {
3058 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3059 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3060 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3061 has_self: sig.decl.has_self(),
3063 ImplItemKind::Macro(..) => unimplemented!(),
3067 // [1] since `default impl` is not yet implemented, this is always true in impls
3070 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3073 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3077 /// Lowers `impl Trait` items and appends them to the list
3078 fn lower_impl_trait_ids(
3082 ids: &mut SmallVector<hir::ItemId>,
3084 if let Some(id) = header.asyncness.opt_return_id() {
3085 ids.push(hir::ItemId { id });
3087 struct IdVisitor<'a> { ids: &'a mut SmallVector<hir::ItemId> }
3088 impl<'a, 'b> Visitor<'a> for IdVisitor<'b> {
3089 fn visit_ty(&mut self, ty: &'a Ty) {
3095 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
3098 visit::walk_ty(self, ty);
3100 fn visit_path_segment(
3103 path_segment: &'v PathSegment,
3105 if let Some(ref p) = path_segment.args {
3106 if let GenericArgs::Parenthesized(_) = **p {
3110 visit::walk_path_segment(self, path_span, path_segment)
3113 let mut visitor = IdVisitor { ids };
3115 FunctionRetTy::Default(_) => {},
3116 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3120 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
3122 ItemKind::Use(ref use_tree) => {
3123 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
3124 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3127 ItemKind::MacroDef(..) => SmallVector::new(),
3128 ItemKind::Fn(ref decl, ref header, ..) => {
3129 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3130 self.lower_impl_trait_ids(decl, header, &mut ids);
3133 ItemKind::Impl(.., None, _, ref items) => {
3134 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3136 if let ImplItemKind::Method(ref sig, _) = item.node {
3137 self.lower_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3142 _ => SmallVector::one(hir::ItemId { id: i.id }),
3146 fn lower_item_id_use_tree(&mut self,
3149 vec: &mut SmallVector<hir::ItemId>)
3152 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3153 vec.push(hir::ItemId { id });
3154 self.lower_item_id_use_tree(nested, id, vec);
3156 UseTreeKind::Glob => {}
3157 UseTreeKind::Simple(_, id1, id2) => {
3158 for (_, &id) in self.expect_full_def_from_use(base_id)
3160 .zip([id1, id2].iter())
3162 vec.push(hir::ItemId { id });
3168 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3169 let mut name = i.ident.name;
3170 let mut vis = self.lower_visibility(&i.vis, None);
3171 let attrs = self.lower_attrs(&i.attrs);
3172 if let ItemKind::MacroDef(ref def) = i.node {
3173 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
3174 let body = self.lower_token_stream(def.stream());
3175 self.exported_macros.push(hir::MacroDef {
3188 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3190 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3203 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3204 let node_id = self.lower_node_id(i.id).node_id;
3205 let def_id = self.resolver.definitions().local_def_id(node_id);
3209 attrs: self.lower_attrs(&i.attrs),
3210 node: match i.node {
3211 ForeignItemKind::Fn(ref fdec, ref generics) => {
3212 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3215 AnonymousLifetimeMode::PassThrough,
3218 // Disallow impl Trait in foreign items
3219 this.lower_fn_decl(fdec, None, false, None),
3220 this.lower_fn_args_to_names(fdec),
3225 hir::ForeignItemFn(fn_dec, fn_args, generics)
3227 ForeignItemKind::Static(ref t, m) => {
3228 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3230 ForeignItemKind::Ty => hir::ForeignItemType,
3231 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3233 vis: self.lower_visibility(&i.vis, None),
3238 fn lower_method_sig(
3240 generics: &Generics,
3243 impl_trait_return_allow: bool,
3244 is_async: Option<NodeId>,
3245 ) -> (hir::Generics, hir::MethodSig) {
3246 let header = self.lower_fn_header(sig.header);
3247 let (generics, decl) = self.add_in_band_defs(
3250 AnonymousLifetimeMode::PassThrough,
3251 |this, idty| this.lower_fn_decl(
3253 Some((fn_def_id, idty)),
3254 impl_trait_return_allow,
3258 (generics, hir::MethodSig { header, decl })
3261 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3263 IsAuto::Yes => hir::IsAuto::Yes,
3264 IsAuto::No => hir::IsAuto::No,
3268 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3270 unsafety: self.lower_unsafety(h.unsafety),
3271 asyncness: self.lower_asyncness(h.asyncness),
3272 constness: self.lower_constness(h.constness),
3277 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3279 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3280 Unsafety::Normal => hir::Unsafety::Normal,
3284 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3286 Constness::Const => hir::Constness::Const,
3287 Constness::NotConst => hir::Constness::NotConst,
3291 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3293 IsAsync::Async { .. } => hir::IsAsync::Async,
3294 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3298 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3300 UnOp::Deref => hir::UnDeref,
3301 UnOp::Not => hir::UnNot,
3302 UnOp::Neg => hir::UnNeg,
3306 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3308 node: match b.node {
3309 BinOpKind::Add => hir::BiAdd,
3310 BinOpKind::Sub => hir::BiSub,
3311 BinOpKind::Mul => hir::BiMul,
3312 BinOpKind::Div => hir::BiDiv,
3313 BinOpKind::Rem => hir::BiRem,
3314 BinOpKind::And => hir::BiAnd,
3315 BinOpKind::Or => hir::BiOr,
3316 BinOpKind::BitXor => hir::BiBitXor,
3317 BinOpKind::BitAnd => hir::BiBitAnd,
3318 BinOpKind::BitOr => hir::BiBitOr,
3319 BinOpKind::Shl => hir::BiShl,
3320 BinOpKind::Shr => hir::BiShr,
3321 BinOpKind::Eq => hir::BiEq,
3322 BinOpKind::Lt => hir::BiLt,
3323 BinOpKind::Le => hir::BiLe,
3324 BinOpKind::Ne => hir::BiNe,
3325 BinOpKind::Ge => hir::BiGe,
3326 BinOpKind::Gt => hir::BiGt,
3332 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3333 let node = match p.node {
3334 PatKind::Wild => hir::PatKind::Wild,
3335 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3336 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3337 // `None` can occur in body-less function signatures
3338 def @ None | def @ Some(Def::Local(_)) => {
3339 let canonical_id = match def {
3340 Some(Def::Local(id)) => id,
3343 hir::PatKind::Binding(
3344 self.lower_binding_mode(binding_mode),
3347 sub.as_ref().map(|x| self.lower_pat(x)),
3350 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3355 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3360 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3361 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3362 let qpath = self.lower_qpath(
3366 ParamMode::Optional,
3367 ImplTraitContext::Disallowed,
3369 hir::PatKind::TupleStruct(
3371 pats.iter().map(|x| self.lower_pat(x)).collect(),
3375 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3379 ParamMode::Optional,
3380 ImplTraitContext::Disallowed,
3382 PatKind::Struct(ref path, ref fields, etc) => {
3383 let qpath = self.lower_qpath(
3387 ParamMode::Optional,
3388 ImplTraitContext::Disallowed,
3395 node: hir::FieldPat {
3396 id: self.next_id().node_id,
3397 ident: f.node.ident,
3398 pat: self.lower_pat(&f.node.pat),
3399 is_shorthand: f.node.is_shorthand,
3403 hir::PatKind::Struct(qpath, fs, etc)
3405 PatKind::Tuple(ref elts, ddpos) => {
3406 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3408 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3409 PatKind::Ref(ref inner, mutbl) => {
3410 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3412 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3413 P(self.lower_expr(e1)),
3414 P(self.lower_expr(e2)),
3415 self.lower_range_end(end),
3417 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3418 before.iter().map(|x| self.lower_pat(x)).collect(),
3419 slice.as_ref().map(|x| self.lower_pat(x)),
3420 after.iter().map(|x| self.lower_pat(x)).collect(),
3422 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3423 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3426 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3435 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3437 RangeEnd::Included(_) => hir::RangeEnd::Included,
3438 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3442 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3443 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3448 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3452 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3453 let kind = match e.node {
3454 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3455 ExprKind::ObsoleteInPlace(..) => {
3456 self.sess.abort_if_errors();
3457 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3459 ExprKind::Array(ref exprs) => {
3460 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3462 ExprKind::Repeat(ref expr, ref count) => {
3463 let expr = P(self.lower_expr(expr));
3464 let count = self.lower_anon_const(count);
3465 hir::ExprRepeat(expr, count)
3467 ExprKind::Tup(ref elts) => {
3468 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3470 ExprKind::Call(ref f, ref args) => {
3471 let f = P(self.lower_expr(f));
3472 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3474 ExprKind::MethodCall(ref seg, ref args) => {
3475 let hir_seg = self.lower_path_segment(
3478 ParamMode::Optional,
3480 ParenthesizedGenericArgs::Err,
3481 ImplTraitContext::Disallowed,
3483 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3484 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3486 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3487 let binop = self.lower_binop(binop);
3488 let lhs = P(self.lower_expr(lhs));
3489 let rhs = P(self.lower_expr(rhs));
3490 hir::ExprBinary(binop, lhs, rhs)
3492 ExprKind::Unary(op, ref ohs) => {
3493 let op = self.lower_unop(op);
3494 let ohs = P(self.lower_expr(ohs));
3495 hir::ExprUnary(op, ohs)
3497 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3498 ExprKind::Cast(ref expr, ref ty) => {
3499 let expr = P(self.lower_expr(expr));
3500 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3502 ExprKind::Type(ref expr, ref ty) => {
3503 let expr = P(self.lower_expr(expr));
3504 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3506 ExprKind::AddrOf(m, ref ohs) => {
3507 let m = self.lower_mutability(m);
3508 let ohs = P(self.lower_expr(ohs));
3509 hir::ExprAddrOf(m, ohs)
3511 // More complicated than you might expect because the else branch
3512 // might be `if let`.
3513 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3514 let else_opt = else_opt.as_ref().map(|els| {
3516 ExprKind::IfLet(..) => {
3517 // wrap the if-let expr in a block
3518 let span = els.span;
3519 let els = P(self.lower_expr(els));
3520 let LoweredNodeId { node_id, hir_id } = self.next_id();
3521 let blk = P(hir::Block {
3526 rules: hir::DefaultBlock,
3528 targeted_by_break: false,
3529 recovered: blk.recovered,
3531 P(self.expr_block(blk, ThinVec::new()))
3533 _ => P(self.lower_expr(els)),
3537 let then_blk = self.lower_block(blk, false);
3538 let then_expr = self.expr_block(then_blk, ThinVec::new());
3540 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3542 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3544 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3545 this.lower_block(body, false),
3546 this.lower_label(opt_label),
3549 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3551 this.lower_block(body, false),
3552 this.lower_label(opt_label),
3553 hir::LoopSource::Loop,
3556 ExprKind::Catch(ref body) => {
3557 self.with_catch_scope(body.id, |this| {
3559 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3560 let mut block = this.lower_block(body, true).into_inner();
3561 let tail = block.expr.take().map_or_else(
3563 let LoweredNodeId { node_id, hir_id } = this.next_id();
3564 let span = this.sess.codemap().end_point(unstable_span);
3568 node: hir::ExprTup(hir_vec![]),
3569 attrs: ThinVec::new(),
3573 |x: P<hir::Expr>| x.into_inner(),
3575 block.expr = Some(this.wrap_in_try_constructor(
3576 "from_ok", tail, unstable_span));
3577 hir::ExprBlock(P(block), None)
3580 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3581 P(self.lower_expr(expr)),
3582 arms.iter().map(|x| self.lower_arm(x)).collect(),
3583 hir::MatchSource::Normal,
3585 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3586 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3587 this.with_new_scopes(|this| {
3588 let block = this.lower_block(block, false);
3589 this.expr_block(block, ThinVec::new())
3594 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3596 if let IsAsync::Async { closure_id, .. } = asyncness {
3597 let outer_decl = FnDecl {
3598 inputs: decl.inputs.clone(),
3599 output: FunctionRetTy::Default(fn_decl_span),
3602 // We need to lower the declaration outside the new scope, because we
3603 // have to conserve the state of being inside a loop condition for the
3604 // closure argument types.
3605 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3607 self.with_new_scopes(|this| {
3608 // FIXME(cramertj) allow `async` non-`move` closures with
3609 if capture_clause == CaptureBy::Ref &&
3610 !decl.inputs.is_empty()
3616 "`async` non-`move` closures with arguments \
3617 are not currently supported",
3619 .help("consider using `let` statements to manually capture \
3620 variables by reference before entering an \
3621 `async move` closure")
3625 // Transform `async |x: u8| -> X { ... }` into
3626 // `|x: u8| future_from_generator(|| -> X { ... })`
3627 let body_id = this.lower_body(Some(&outer_decl), |this| {
3628 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3631 let async_body = this.make_async_expr(
3632 capture_clause, closure_id, async_ret_ty,
3634 this.with_new_scopes(|this| this.lower_expr(body))
3636 this.expr(fn_decl_span, async_body, ThinVec::new())
3639 this.lower_capture_clause(capture_clause),
3647 // Lower outside new scope to preserve `is_in_loop_condition`.
3648 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3650 self.with_new_scopes(|this| {
3651 let mut is_generator = false;
3652 let body_id = this.lower_body(Some(decl), |this| {
3653 let e = this.lower_expr(body);
3654 is_generator = this.is_generator;
3657 let generator_option = if is_generator {
3658 if !decl.inputs.is_empty() {
3663 "generators cannot have explicit arguments"
3665 this.sess.abort_if_errors();
3667 Some(match movability {
3668 Movability::Movable => hir::GeneratorMovability::Movable,
3669 Movability::Static => hir::GeneratorMovability::Static,
3672 if movability == Movability::Static {
3677 "closures cannot be static"
3683 this.lower_capture_clause(capture_clause),
3692 ExprKind::Block(ref blk, opt_label) => {
3693 hir::ExprBlock(self.lower_block(blk,
3694 opt_label.is_some()),
3695 self.lower_label(opt_label))
3697 ExprKind::Assign(ref el, ref er) => {
3698 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3700 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3701 self.lower_binop(op),
3702 P(self.lower_expr(el)),
3703 P(self.lower_expr(er)),
3705 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3706 ExprKind::Index(ref el, ref er) => {
3707 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3709 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3710 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3711 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3712 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3713 let id = self.next_id();
3714 let e1 = self.lower_expr(e1);
3715 let e2 = self.lower_expr(e2);
3716 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], None, false));
3717 let ty = P(self.ty_path(id, span, hir::QPath::Resolved(None, ty_path)));
3718 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3719 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3720 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3721 hir::ExprCall(new, hir_vec![e1, e2])
3723 ExprKind::Range(ref e1, ref e2, lims) => {
3724 use syntax::ast::RangeLimits::*;
3726 let path = match (e1, e2, lims) {
3727 (&None, &None, HalfOpen) => "RangeFull",
3728 (&Some(..), &None, HalfOpen) => "RangeFrom",
3729 (&None, &Some(..), HalfOpen) => "RangeTo",
3730 (&Some(..), &Some(..), HalfOpen) => "Range",
3731 (&None, &Some(..), Closed) => "RangeToInclusive",
3732 (&Some(..), &Some(..), Closed) => unreachable!(),
3733 (_, &None, Closed) => self.diagnostic()
3734 .span_fatal(e.span, "inclusive range with no end")
3738 let fields = e1.iter()
3739 .map(|e| ("start", e))
3740 .chain(e2.iter().map(|e| ("end", e)))
3742 let expr = P(self.lower_expr(&e));
3744 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3745 let ident = Ident::new(Symbol::intern(s), unstable_span);
3746 self.field(ident, expr, unstable_span)
3748 .collect::<P<[hir::Field]>>();
3750 let is_unit = fields.is_empty();
3752 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3753 let struct_path = iter::once("ops")
3754 .chain(iter::once(path))
3755 .collect::<Vec<_>>();
3756 let struct_path = self.std_path(unstable_span, &struct_path, None, is_unit);
3757 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3759 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3765 hir::ExprPath(struct_path)
3767 hir::ExprStruct(struct_path, fields, None)
3769 span: unstable_span,
3770 attrs: e.attrs.clone(),
3773 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3777 ParamMode::Optional,
3778 ImplTraitContext::Disallowed,
3780 ExprKind::Break(opt_label, ref opt_expr) => {
3781 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3784 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3787 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3791 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3794 ExprKind::Continue(opt_label) => {
3795 hir::ExprContinue(if self.is_in_loop_condition && opt_label.is_none() {
3798 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3801 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3804 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3805 ExprKind::InlineAsm(ref asm) => {
3806 let hir_asm = hir::InlineAsm {
3807 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3808 outputs: asm.outputs
3810 .map(|out| hir::InlineAsmOutput {
3811 constraint: out.constraint.clone(),
3813 is_indirect: out.is_indirect,
3816 asm: asm.asm.clone(),
3817 asm_str_style: asm.asm_str_style,
3818 clobbers: asm.clobbers.clone().into(),
3819 volatile: asm.volatile,
3820 alignstack: asm.alignstack,
3821 dialect: asm.dialect,
3824 let outputs = asm.outputs
3826 .map(|out| self.lower_expr(&out.expr))
3828 let inputs = asm.inputs
3830 .map(|&(_, ref input)| self.lower_expr(input))
3832 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3834 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3839 ParamMode::Optional,
3840 ImplTraitContext::Disallowed,
3842 fields.iter().map(|x| self.lower_field(x)).collect(),
3843 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3845 ExprKind::Paren(ref ex) => {
3846 let mut ex = self.lower_expr(ex);
3847 // include parens in span, but only if it is a super-span.
3848 if e.span.contains(ex.span) {
3851 // merge attributes into the inner expression.
3852 let mut attrs = e.attrs.clone();
3853 attrs.extend::<Vec<_>>(ex.attrs.into());
3858 ExprKind::Yield(ref opt_expr) => {
3859 self.is_generator = true;
3862 .map(|x| self.lower_expr(x))
3863 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3864 hir::ExprYield(P(expr))
3867 // Desugar ExprIfLet
3868 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3869 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3872 // match <sub_expr> {
3874 // _ => [<else_opt> | ()]
3877 let mut arms = vec![];
3879 // `<pat> => <body>`
3881 let body = self.lower_block(body, false);
3882 let body_expr = P(self.expr_block(body, ThinVec::new()));
3883 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3884 arms.push(self.arm(pats, body_expr));
3887 // _ => [<else_opt>|()]
3889 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3890 let wildcard_pattern = self.pat_wild(e.span);
3891 let body = if let Some(else_expr) = wildcard_arm {
3892 P(self.lower_expr(else_expr))
3894 self.expr_tuple(e.span, hir_vec![])
3896 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3899 let contains_else_clause = else_opt.is_some();
3901 let sub_expr = P(self.lower_expr(sub_expr));
3906 hir::MatchSource::IfLetDesugar {
3907 contains_else_clause,
3912 // Desugar ExprWhileLet
3913 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3914 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3917 // [opt_ident]: loop {
3918 // match <sub_expr> {
3924 // Note that the block AND the condition are evaluated in the loop scope.
3925 // This is done to allow `break` from inside the condition of the loop.
3926 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3928 this.lower_block(body, false),
3929 this.expr_break(e.span, ThinVec::new()),
3930 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3934 // `<pat> => <body>`
3936 let body_expr = P(self.expr_block(body, ThinVec::new()));
3937 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3938 self.arm(pats, body_expr)
3943 let pat_under = self.pat_wild(e.span);
3944 self.arm(hir_vec![pat_under], break_expr)
3947 // `match <sub_expr> { ... }`
3948 let arms = hir_vec![pat_arm, break_arm];
3949 let match_expr = self.expr(
3951 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3955 // `[opt_ident]: loop { ... }`
3956 let loop_block = P(self.block_expr(P(match_expr)));
3957 let loop_expr = hir::ExprLoop(
3959 self.lower_label(opt_label),
3960 hir::LoopSource::WhileLet,
3962 // add attributes to the outer returned expr node
3966 // Desugar ExprForLoop
3967 // From: `[opt_ident]: for <pat> in <head> <body>`
3968 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3972 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3974 // [opt_ident]: loop {
3976 // match ::std::iter::Iterator::next(&mut iter) {
3977 // ::std::option::Option::Some(val) => __next = val,
3978 // ::std::option::Option::None => break
3980 // let <pat> = __next;
3981 // StmtExpr(<body>);
3989 let head = self.lower_expr(head);
3990 let head_sp = head.span;
3992 let iter = self.str_to_ident("iter");
3994 let next_ident = self.str_to_ident("__next");
3995 let next_pat = self.pat_ident_binding_mode(
3998 hir::BindingAnnotation::Mutable,
4001 // `::std::option::Option::Some(val) => next = val`
4003 let val_ident = self.str_to_ident("val");
4004 let val_pat = self.pat_ident(pat.span, val_ident);
4005 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4006 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4007 let assign = P(self.expr(
4009 hir::ExprAssign(next_expr, val_expr),
4012 let some_pat = self.pat_some(pat.span, val_pat);
4013 self.arm(hir_vec![some_pat], assign)
4016 // `::std::option::Option::None => break`
4019 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4020 let pat = self.pat_none(e.span);
4021 self.arm(hir_vec![pat], break_expr)
4026 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4028 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4030 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4031 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4032 let next_path = &["iter", "Iterator", "next"];
4033 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4034 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4035 let arms = hir_vec![pat_arm, break_arm];
4039 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
4043 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
4045 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4049 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4051 // `let <pat> = __next`
4052 let pat = self.lower_pat(pat);
4053 let pat_let = self.stmt_let_pat(
4057 hir::LocalSource::ForLoopDesugar,
4060 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4061 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4062 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
4064 let loop_block = P(self.block_all(
4066 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4070 // `[opt_ident]: loop { ... }`
4071 let loop_expr = hir::ExprLoop(
4073 self.lower_label(opt_label),
4074 hir::LoopSource::ForLoop,
4076 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4077 let loop_expr = P(hir::Expr {
4082 attrs: ThinVec::new(),
4085 // `mut iter => { ... }`
4086 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4088 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4089 let into_iter_expr = {
4090 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4091 let into_iter = P(self.expr_std_path(
4092 head_sp, into_iter_path, None, ThinVec::new()));
4093 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4096 let match_expr = P(self.expr_match(
4100 hir::MatchSource::ForLoopDesugar,
4103 // `{ let _result = ...; _result }`
4104 // underscore prevents an unused_variables lint if the head diverges
4105 let result_ident = self.str_to_ident("_result");
4106 let (let_stmt, let_stmt_binding) =
4107 self.stmt_let(e.span, false, result_ident, match_expr);
4109 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4110 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4111 // add the attributes to the outer returned expr node
4112 return self.expr_block(block, e.attrs.clone());
4115 // Desugar ExprKind::Try
4117 ExprKind::Try(ref sub_expr) => {
4120 // match Try::into_result(<expr>) {
4121 // Ok(val) => #[allow(unreachable_code)] val,
4122 // Err(err) => #[allow(unreachable_code)]
4123 // // If there is an enclosing `catch {...}`
4124 // break 'catch_target Try::from_error(From::from(err)),
4126 // return Try::from_error(From::from(err)),
4130 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4132 // Try::into_result(<expr>)
4135 let sub_expr = self.lower_expr(sub_expr);
4137 let path = &["ops", "Try", "into_result"];
4138 let path = P(self.expr_std_path(
4139 unstable_span, path, None, ThinVec::new()));
4140 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4143 // #[allow(unreachable_code)]
4145 // allow(unreachable_code)
4147 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4148 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4149 let uc_nested = attr::mk_nested_word_item(uc_ident);
4150 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4152 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4154 let attrs = vec![attr];
4156 // Ok(val) => #[allow(unreachable_code)] val,
4158 let val_ident = self.str_to_ident("val");
4159 let val_pat = self.pat_ident(e.span, val_ident);
4160 let val_expr = P(self.expr_ident_with_attrs(
4164 ThinVec::from(attrs.clone()),
4166 let ok_pat = self.pat_ok(e.span, val_pat);
4168 self.arm(hir_vec![ok_pat], val_expr)
4171 // Err(err) => #[allow(unreachable_code)]
4172 // return Try::from_error(From::from(err)),
4174 let err_ident = self.str_to_ident("err");
4175 let err_local = self.pat_ident(e.span, err_ident);
4177 let path = &["convert", "From", "from"];
4178 let from = P(self.expr_std_path(
4179 e.span, path, None, ThinVec::new()));
4180 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4182 self.expr_call(e.span, from, hir_vec![err_expr])
4185 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4186 let thin_attrs = ThinVec::from(attrs);
4187 let catch_scope = self.catch_scopes.last().map(|x| *x);
4188 let ret_expr = if let Some(catch_node) = catch_scope {
4194 target_id: Ok(catch_node),
4196 Some(from_err_expr),
4201 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
4204 let err_pat = self.pat_err(e.span, err_local);
4205 self.arm(hir_vec![err_pat], ret_expr)
4210 hir_vec![err_arm, ok_arm],
4211 hir::MatchSource::TryDesugar,
4215 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4218 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4225 attrs: e.attrs.clone(),
4229 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
4230 SmallVector::one(match s.node {
4231 StmtKind::Local(ref l) => Spanned {
4232 node: hir::StmtDecl(
4234 node: hir::DeclLocal(self.lower_local(l)),
4237 self.lower_node_id(s.id).node_id,
4241 StmtKind::Item(ref it) => {
4242 // Can only use the ID once.
4243 let mut id = Some(s.id);
4244 return self.lower_item_id(it)
4246 .map(|item_id| Spanned {
4247 node: hir::StmtDecl(
4249 node: hir::DeclItem(item_id),
4253 .map(|id| self.lower_node_id(id).node_id)
4254 .unwrap_or_else(|| self.next_id().node_id),
4260 StmtKind::Expr(ref e) => Spanned {
4261 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4264 StmtKind::Semi(ref e) => Spanned {
4265 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4268 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4272 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4274 CaptureBy::Value => hir::CaptureByValue,
4275 CaptureBy::Ref => hir::CaptureByRef,
4279 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4280 /// the address space of that item instead of the item currently being
4281 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4282 /// lower a `Visibility` value although we haven't lowered the owning
4283 /// `ImplItem` in question yet.
4284 fn lower_visibility(
4287 explicit_owner: Option<NodeId>,
4288 ) -> hir::Visibility {
4289 let node = match v.node {
4290 VisibilityKind::Public => hir::VisibilityKind::Public,
4291 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4292 VisibilityKind::Restricted { ref path, id } => hir::VisibilityKind::Restricted {
4293 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4294 id: if let Some(owner) = explicit_owner {
4295 self.lower_node_id_with_owner(id, owner).node_id
4297 self.lower_node_id(id).node_id
4300 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4302 respan(v.span, node)
4305 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4307 Defaultness::Default => hir::Defaultness::Default {
4308 has_value: has_value,
4310 Defaultness::Final => {
4312 hir::Defaultness::Final
4317 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4319 BlockCheckMode::Default => hir::DefaultBlock,
4320 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4324 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4326 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4327 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4328 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4329 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4333 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4335 CompilerGenerated => hir::CompilerGenerated,
4336 UserProvided => hir::UserProvided,
4340 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4342 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4343 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4347 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4349 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4350 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4354 // Helper methods for building HIR.
4356 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4365 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4367 id: self.next_id().node_id,
4371 is_shorthand: false,
4375 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4376 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
4377 P(self.expr(span, expr_break, attrs))
4384 args: hir::HirVec<hir::Expr>,
4386 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
4389 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4390 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4393 fn expr_ident_with_attrs(
4398 attrs: ThinVec<Attribute>,
4400 let expr_path = hir::ExprPath(hir::QPath::Resolved(
4404 def: Def::Local(binding),
4405 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4409 self.expr(span, expr_path, attrs)
4412 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4413 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
4419 components: &[&str],
4420 params: Option<P<hir::GenericArgs>>,
4421 attrs: ThinVec<Attribute>,
4423 let path = self.std_path(span, components, params, true);
4426 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4435 arms: hir::HirVec<hir::Arm>,
4436 source: hir::MatchSource,
4438 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4441 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4442 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4445 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4446 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4449 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4450 let LoweredNodeId { node_id, hir_id } = self.next_id();
4463 ex: Option<P<hir::Expr>>,
4465 source: hir::LocalSource,
4467 let LoweredNodeId { node_id, hir_id } = self.next_id();
4469 let local = P(hir::Local {
4476 attrs: ThinVec::new(),
4479 let decl = respan(sp, hir::DeclLocal(local));
4480 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4489 ) -> (hir::Stmt, NodeId) {
4490 let pat = if mutbl {
4491 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4493 self.pat_ident(sp, ident)
4495 let pat_id = pat.id;
4497 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4502 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4503 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4509 stmts: hir::HirVec<hir::Stmt>,
4510 expr: Option<P<hir::Expr>>,
4512 let LoweredNodeId { node_id, hir_id } = self.next_id();
4519 rules: hir::DefaultBlock,
4521 targeted_by_break: false,
4526 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4527 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4530 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4531 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4534 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4535 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4538 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4539 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4545 components: &[&str],
4546 subpats: hir::HirVec<P<hir::Pat>>,
4548 let path = self.std_path(span, components, None, true);
4549 let qpath = hir::QPath::Resolved(None, P(path));
4550 let pt = if subpats.is_empty() {
4551 hir::PatKind::Path(qpath)
4553 hir::PatKind::TupleStruct(qpath, subpats, None)
4558 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4559 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4562 fn pat_ident_binding_mode(
4566 bm: hir::BindingAnnotation,
4568 let LoweredNodeId { node_id, hir_id } = self.next_id();
4573 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4578 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4579 self.pat(span, hir::PatKind::Wild)
4582 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4583 let LoweredNodeId { node_id, hir_id } = self.next_id();
4592 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4593 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4594 /// The path is also resolved according to `is_value`.
4598 components: &[&str],
4599 params: Option<P<hir::GenericArgs>>,
4603 .resolve_str_path(span, self.crate_root, components, params, is_value)
4606 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4608 let node = match qpath {
4609 hir::QPath::Resolved(None, path) => {
4610 // Turn trait object paths into `TyTraitObject` instead.
4611 if let Def::Trait(_) = path.def {
4612 let principal = hir::PolyTraitRef {
4613 bound_generic_params: hir::HirVec::new(),
4614 trait_ref: hir::TraitRef {
4615 path: path.and_then(|path| path),
4621 // The original ID is taken by the `PolyTraitRef`,
4622 // so the `Ty` itself needs a different one.
4623 id = self.next_id();
4624 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4626 hir::TyPath(hir::QPath::Resolved(None, path))
4629 _ => hir::TyPath(qpath),
4639 /// Invoked to create the lifetime argument for a type `&T`
4640 /// with no explicit lifetime.
4641 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4642 match self.anonymous_lifetime_mode {
4643 // Intercept when we are in an impl header and introduce an in-band lifetime.
4644 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4646 AnonymousLifetimeMode::CreateParameter => {
4647 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4649 id: self.next_id().node_id,
4651 name: hir::LifetimeName::Param(fresh_name),
4655 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4659 /// Invoked to create the lifetime argument(s) for a path like
4660 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4661 /// sorts of cases are deprecated. This may therefore report a warning or an
4662 /// error, depending on the mode.
4663 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4664 match self.anonymous_lifetime_mode {
4665 // NB. We intentionally ignore the create-parameter mode here
4666 // and instead "pass through" to resolve-lifetimes, which will then
4667 // report an error. This is because we don't want to support
4668 // impl elision for deprecated forms like
4670 // impl Foo for std::cell::Ref<u32> // note lack of '_
4671 AnonymousLifetimeMode::CreateParameter => {}
4673 // This is the normal case.
4674 AnonymousLifetimeMode::PassThrough => {}
4678 .map(|_| self.new_implicit_lifetime(span))
4682 /// Invoked to create the lifetime argument(s) for an elided trait object
4683 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4684 /// when the bound is written, even if it is written with `'_` like in
4685 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4686 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4687 match self.anonymous_lifetime_mode {
4688 // NB. We intentionally ignore the create-parameter mode here.
4689 // and instead "pass through" to resolve-lifetimes, which will apply
4690 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4691 // do not act like other elided lifetimes. In other words, given this:
4693 // impl Foo for Box<dyn Debug>
4695 // we do not introduce a fresh `'_` to serve as the bound, but instead
4696 // ultimately translate to the equivalent of:
4698 // impl Foo for Box<dyn Debug + 'static>
4700 // `resolve_lifetime` has the code to make that happen.
4701 AnonymousLifetimeMode::CreateParameter => {}
4703 // This is the normal case.
4704 AnonymousLifetimeMode::PassThrough => {}
4707 self.new_implicit_lifetime(span)
4710 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4712 id: self.next_id().node_id,
4714 name: hir::LifetimeName::Implicit,
4718 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4719 self.sess.buffer_lint_with_diagnostic(
4720 builtin::BARE_TRAIT_OBJECTS,
4723 "trait objects without an explicit `dyn` are deprecated",
4724 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4728 fn wrap_in_try_constructor(
4730 method: &'static str,
4732 unstable_span: Span,
4734 let path = &["ops", "Try", method];
4735 let from_err = P(self.expr_std_path(unstable_span, path, None,
4737 P(self.expr_call(e.span, from_err, hir_vec![e]))
4741 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4742 // Sorting by span ensures that we get things in order within a
4743 // file, and also puts the files in a sensible order.
4744 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4745 body_ids.sort_by_key(|b| bodies[b].value.span);