1 //! Lowers the AST to the HIR.
3 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
4 //! much like a fold. Where lowering involves a bit more work things get more
5 //! interesting and there are some invariants you should know about. These mostly
6 //! concern spans and ids.
8 //! Spans are assigned to AST nodes during parsing and then are modified during
9 //! expansion to indicate the origin of a node and the process it went through
10 //! being expanded. Ids are assigned to AST nodes just before lowering.
12 //! For the simpler lowering steps, ids and spans should be preserved. Unlike
13 //! expansion we do not preserve the process of lowering in the spans, so spans
14 //! should not be modified here. When creating a new node (as opposed to
15 //! 'folding' an existing one), then you create a new id using `next_id()`.
17 //! You must ensure that ids are unique. That means that you should only use the
18 //! id from an AST node in a single HIR node (you can assume that AST node ids
19 //! are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
20 //! If you do, you must then set the new node's id to a fresh one.
22 //! Spans are used for error messages and for tools to map semantics back to
23 //! source code. It is therefore not as important with spans as ids to be strict
24 //! about use (you can't break the compiler by screwing up a span). Obviously, a
25 //! HIR node can only have a single span. But multiple nodes can have the same
26 //! span and spans don't need to be kept in order, etc. Where code is preserved
27 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
28 //! new it is probably best to give a span for the whole AST node being lowered.
29 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
30 //! get confused if the spans from leaf AST nodes occur in multiple places
31 //! in the HIR, especially for multiple identifiers.
33 use dep_graph::DepGraph;
34 use hir::{self, ParamName};
36 use hir::map::{DefKey, DefPathData, Definitions};
37 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
38 use hir::def::{Def, PathResolution, PerNS};
40 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
41 ELIDED_LIFETIMES_IN_PATHS};
42 use middle::cstore::CrateStore;
43 use rustc_data_structures::fx::FxHashSet;
44 use rustc_data_structures::indexed_vec::IndexVec;
45 use rustc_data_structures::thin_vec::ThinVec;
47 use session::config::nightly_options;
48 use util::common::FN_OUTPUT_NAME;
49 use util::nodemap::{DefIdMap, NodeMap};
51 use std::collections::{BTreeSet, BTreeMap};
54 use smallvec::SmallVec;
59 use syntax::ext::hygiene::{Mark, SyntaxContext};
60 use syntax::print::pprust;
62 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
63 use syntax::std_inject;
64 use syntax::symbol::{keywords, Symbol};
65 use syntax::tokenstream::{TokenStream, TokenTree};
66 use syntax::parse::token::Token;
67 use syntax::visit::{self, Visitor};
68 use syntax_pos::{Span, MultiSpan};
70 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
72 pub struct LoweringContext<'a> {
73 crate_root: Option<&'static str>,
75 // Used to assign ids to HIR nodes that do not directly correspond to an AST node.
78 cstore: &'a dyn CrateStore,
80 resolver: &'a mut dyn Resolver,
82 /// The items being lowered are collected here.
83 items: BTreeMap<NodeId, hir::Item>,
85 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
86 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
87 bodies: BTreeMap<hir::BodyId, hir::Body>,
88 exported_macros: Vec<hir::MacroDef>,
90 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
91 trait_auto_impl: BTreeMap<DefId, NodeId>,
93 modules: BTreeMap<NodeId, hir::ModuleItems>,
97 catch_scopes: Vec<NodeId>,
98 loop_scopes: Vec<NodeId>,
99 is_in_loop_condition: bool,
100 is_in_trait_impl: bool,
102 /// What to do when we encounter either an "anonymous lifetime
103 /// reference". The term "anonymous" is meant to encompass both
104 /// `'_` lifetimes as well as fully elided cases where nothing is
105 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
106 anonymous_lifetime_mode: AnonymousLifetimeMode,
108 // Used to create lifetime definitions from in-band lifetime usages.
109 // e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
110 // When a named lifetime is encountered in a function or impl header and
111 // has not been defined
112 // (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
113 // to this list. The results of this list are then added to the list of
114 // lifetime definitions in the corresponding impl or function generics.
115 lifetimes_to_define: Vec<(Span, ParamName)>,
117 // Whether or not in-band lifetimes are being collected. This is used to
118 // indicate whether or not we're in a place where new lifetimes will result
119 // in in-band lifetime definitions, such a function or an impl header,
120 // including implicit lifetimes from `impl_header_lifetime_elision`.
121 is_collecting_in_band_lifetimes: bool,
123 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
124 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
125 // against this list to see if it is already in-scope, or if a definition
126 // needs to be created for it.
127 in_scope_lifetimes: Vec<Ident>,
129 current_module: NodeId,
131 type_def_lifetime_params: DefIdMap<usize>,
133 current_hir_id_owner: Vec<(DefIndex, u32)>,
134 item_local_id_counters: NodeMap<u32>,
135 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
139 /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
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
157 /// resolves it based on `is_value`.
161 crate_root: Option<&str>,
168 enum ImplTraitContext<'a> {
169 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
170 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
171 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
173 /// Newly generated parameters should be inserted into the given `Vec`.
174 Universal(&'a mut Vec<hir::GenericParam>),
176 /// Treat `impl Trait` as shorthand for a new existential parameter.
177 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
178 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
180 /// We optionally store a `DefId` for the parent item here so we can look up necessary
181 /// information later. It is `None` when no information about the context should be stored,
182 /// e.g., for consts and statics.
183 Existential(Option<DefId>),
185 /// `impl Trait` is not accepted in this position.
186 Disallowed(ImplTraitPosition),
189 /// Position in which `impl Trait` is disallowed. Used for error reporting.
190 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
191 enum ImplTraitPosition {
196 impl<'a> ImplTraitContext<'a> {
198 fn disallowed() -> Self {
199 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
202 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
203 use self::ImplTraitContext::*;
205 Universal(params) => Universal(params),
206 Existential(did) => Existential(*did),
207 Disallowed(pos) => Disallowed(*pos),
214 cstore: &dyn CrateStore,
215 dep_graph: &DepGraph,
217 resolver: &mut dyn Resolver,
219 // We're constructing the HIR here; we don't care what we will
220 // read, since we haven't even constructed the *input* to
222 dep_graph.assert_ignored();
225 crate_root: std_inject::injected_crate_name(),
229 items: BTreeMap::new(),
230 trait_items: BTreeMap::new(),
231 impl_items: BTreeMap::new(),
232 bodies: BTreeMap::new(),
233 trait_impls: BTreeMap::new(),
234 trait_auto_impl: BTreeMap::new(),
235 modules: BTreeMap::new(),
236 exported_macros: Vec::new(),
237 catch_scopes: Vec::new(),
238 loop_scopes: Vec::new(),
239 is_in_loop_condition: false,
240 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
241 type_def_lifetime_params: Default::default(),
242 current_module: CRATE_NODE_ID,
243 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
244 item_local_id_counters: Default::default(),
245 node_id_to_hir_id: IndexVec::new(),
247 is_in_trait_impl: false,
248 lifetimes_to_define: Vec::new(),
249 is_collecting_in_band_lifetimes: false,
250 in_scope_lifetimes: Vec::new(),
254 #[derive(Copy, Clone, PartialEq)]
256 /// Any path in a type context.
258 /// The `module::Type` in `module::Type::method` in an expression.
263 struct LoweredNodeId {
268 enum ParenthesizedGenericArgs {
274 /// What to do when we encounter an **anonymous** lifetime
275 /// reference. Anonymous lifetime references come in two flavors. You
276 /// have implicit, or fully elided, references to lifetimes, like the
277 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
278 /// or `Ref<'_, T>`. These often behave the same, but not always:
280 /// - certain usages of implicit references are deprecated, like
281 /// `Ref<T>`, and we sometimes just give hard errors in those cases
283 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
284 /// the same as `Box<dyn Foo + '_>`.
286 /// We describe the effects of the various modes in terms of three cases:
288 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
289 /// of a `&` (e.g., the missing lifetime in something like `&T`)
290 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
291 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
292 /// elided bounds follow special rules. Note that this only covers
293 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
294 /// '_>` is a case of "modern" elision.
295 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
296 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
297 /// non-deprecated equivalent.
299 /// Currently, the handling of lifetime elision is somewhat spread out
300 /// between HIR lowering and -- as described below -- the
301 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
302 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
303 /// everything into HIR lowering.
304 #[derive(Copy, Clone)]
305 enum AnonymousLifetimeMode {
306 /// For **Modern** cases, create a new anonymous region parameter
307 /// and reference that.
309 /// For **Dyn Bound** cases, pass responsibility to
310 /// `resolve_lifetime` code.
312 /// For **Deprecated** cases, report an error.
315 /// Give a hard error when either `&` or `'_` is written. Used to
316 /// rule out things like `where T: Foo<'_>`. Does not imply an
317 /// error on default object bounds (e.g., `Box<dyn Foo>`).
320 /// Pass responsibility to `resolve_lifetime` code for all cases.
324 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[hir::ItemId; 1]> }
326 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
327 fn visit_ty(&mut self, ty: &'a Ty) {
333 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
336 visit::walk_ty(self, ty);
339 fn visit_path_segment(
342 path_segment: &'v PathSegment,
344 if let Some(ref p) = path_segment.args {
345 if let GenericArgs::Parenthesized(_) = **p {
349 visit::walk_path_segment(self, path_span, path_segment)
353 impl<'a> LoweringContext<'a> {
354 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
355 /// Full-crate AST visitor that inserts into a fresh
356 /// `LoweringContext` any information that may be
357 /// needed from arbitrary locations in the crate,
358 /// e.g., the number of lifetime generic parameters
359 /// declared for every type and trait definition.
360 struct MiscCollector<'lcx, 'interner: 'lcx> {
361 lctx: &'lcx mut LoweringContext<'interner>,
364 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
365 fn visit_item(&mut self, item: &'lcx Item) {
366 self.lctx.allocate_hir_id_counter(item.id, item);
369 ItemKind::Struct(_, ref generics)
370 | ItemKind::Union(_, ref generics)
371 | ItemKind::Enum(_, ref generics)
372 | ItemKind::Ty(_, ref generics)
373 | ItemKind::Existential(_, ref generics)
374 | ItemKind::Trait(_, _, ref generics, ..) => {
375 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
379 .filter(|param| match param.kind {
380 ast::GenericParamKind::Lifetime { .. } => true,
384 self.lctx.type_def_lifetime_params.insert(def_id, count);
388 visit::walk_item(self, item);
391 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
392 self.lctx.allocate_hir_id_counter(item.id, item);
393 visit::walk_trait_item(self, item);
396 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
397 self.lctx.allocate_hir_id_counter(item.id, item);
398 visit::walk_impl_item(self, item);
402 struct ItemLowerer<'lcx, 'interner: 'lcx> {
403 lctx: &'lcx mut LoweringContext<'interner>,
406 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
407 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
409 F: FnOnce(&mut Self),
411 let old = self.lctx.is_in_trait_impl;
412 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
418 self.lctx.is_in_trait_impl = old;
422 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
423 fn visit_mod(&mut self, m: &'lcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
424 self.lctx.modules.insert(n, hir::ModuleItems {
425 items: BTreeSet::new(),
426 trait_items: BTreeSet::new(),
427 impl_items: BTreeSet::new(),
430 let old = self.lctx.current_module;
431 self.lctx.current_module = n;
432 visit::walk_mod(self, m);
433 self.lctx.current_module = old;
436 fn visit_item(&mut self, item: &'lcx Item) {
437 let mut item_lowered = true;
438 self.lctx.with_hir_id_owner(item.id, |lctx| {
439 if let Some(hir_item) = lctx.lower_item(item) {
440 lctx.insert_item(item.id, hir_item);
442 item_lowered = false;
447 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
448 hir::ItemKind::Impl(_, _, _, ref generics, ..)
449 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
450 generics.params.clone()
455 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
456 let this = &mut ItemLowerer { lctx: this };
457 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
458 this.with_trait_impl_ref(opt_trait_ref, |this| {
459 visit::walk_item(this, item)
462 visit::walk_item(this, item);
468 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
469 self.lctx.with_hir_id_owner(item.id, |lctx| {
470 let id = hir::TraitItemId { node_id: item.id };
471 let hir_item = lctx.lower_trait_item(item);
472 lctx.trait_items.insert(id, hir_item);
473 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
476 visit::walk_trait_item(self, item);
479 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
480 self.lctx.with_hir_id_owner(item.id, |lctx| {
481 let id = hir::ImplItemId { node_id: item.id };
482 let hir_item = lctx.lower_impl_item(item);
483 lctx.impl_items.insert(id, hir_item);
484 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
486 visit::walk_impl_item(self, item);
490 self.lower_node_id(CRATE_NODE_ID);
491 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
493 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
494 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
496 let module = self.lower_mod(&c.module);
497 let attrs = self.lower_attrs(&c.attrs);
498 let body_ids = body_ids(&self.bodies);
502 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
508 exported_macros: hir::HirVec::from(self.exported_macros),
510 trait_items: self.trait_items,
511 impl_items: self.impl_items,
514 trait_impls: self.trait_impls,
515 trait_auto_impl: self.trait_auto_impl,
516 modules: self.modules,
520 fn insert_item(&mut self, id: NodeId, item: hir::Item) {
521 self.items.insert(id, item);
522 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
525 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
526 if self.item_local_id_counters.insert(owner, 0).is_some() {
528 "Tried to allocate item_local_id_counter for {:?} twice",
532 // Always allocate the first `HirId` for the owner itself.
533 self.lower_node_id_with_owner(owner, owner)
536 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
538 F: FnOnce(&mut Self) -> hir::HirId,
540 if ast_node_id == DUMMY_NODE_ID {
541 return LoweredNodeId {
542 node_id: DUMMY_NODE_ID,
543 hir_id: hir::DUMMY_HIR_ID,
547 let min_size = ast_node_id.as_usize() + 1;
549 if min_size > self.node_id_to_hir_id.len() {
550 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
553 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
555 if existing_hir_id == hir::DUMMY_HIR_ID {
556 // Generate a new `HirId`.
557 let hir_id = alloc_hir_id(self);
558 self.node_id_to_hir_id[ast_node_id] = hir_id;
560 node_id: ast_node_id,
565 node_id: ast_node_id,
566 hir_id: existing_hir_id,
571 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
573 F: FnOnce(&mut Self) -> T,
575 let counter = self.item_local_id_counters
576 .insert(owner, HIR_ID_COUNTER_LOCKED)
577 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
578 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
579 self.current_hir_id_owner.push((def_index, counter));
581 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
583 debug_assert!(def_index == new_def_index);
584 debug_assert!(new_counter >= counter);
586 let prev = self.item_local_id_counters
587 .insert(owner, new_counter)
589 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
593 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
594 /// the `LoweringContext`'s `NodeId => HirId` map.
595 /// Take care not to call this method if the resulting `HirId` is then not
596 /// actually used in the HIR, as that would trigger an assertion in the
597 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
598 /// properly. Calling the method twice with the same `NodeId` is fine though.
599 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
600 self.lower_node_id_generic(ast_node_id, |this| {
601 let &mut (def_index, ref mut local_id_counter) =
602 this.current_hir_id_owner.last_mut().unwrap();
603 let local_id = *local_id_counter;
604 *local_id_counter += 1;
607 local_id: hir::ItemLocalId::from_u32(local_id),
612 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
613 self.lower_node_id_generic(ast_node_id, |this| {
614 let local_id_counter = this
615 .item_local_id_counters
617 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
618 let local_id = *local_id_counter;
620 // We want to be sure not to modify the counter in the map while it
621 // is also on the stack. Otherwise we'll get lost updates when writing
622 // back from the stack to the map.
623 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
625 *local_id_counter += 1;
629 .opt_def_index(owner)
630 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
631 that do not belong to the current owner");
635 local_id: hir::ItemLocalId::from_u32(local_id),
640 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
641 let body = hir::Body {
642 arguments: decl.map_or(hir_vec![], |decl| {
643 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
645 is_generator: self.is_generator,
649 self.bodies.insert(id, body);
653 fn next_id(&mut self) -> LoweredNodeId {
654 self.lower_node_id(self.sess.next_node_id())
657 fn expect_full_def(&mut self, id: NodeId) -> Def {
658 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
659 if pr.unresolved_segments() != 0 {
660 bug!("path not fully resolved: {:?}", pr);
666 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def> {
667 self.resolver.get_import(id).present_items().map(|pr| {
668 if pr.unresolved_segments() != 0 {
669 bug!("path not fully resolved: {:?}", pr);
675 fn diagnostic(&self) -> &errors::Handler {
676 self.sess.diagnostic()
679 fn str_to_ident(&self, s: &'static str) -> Ident {
680 Ident::with_empty_ctxt(Symbol::gensym(s))
683 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
684 let mark = Mark::fresh(Mark::root());
685 mark.set_expn_info(source_map::ExpnInfo {
687 def_site: Some(span),
688 format: source_map::CompilerDesugaring(reason),
689 allow_internal_unstable: true,
690 allow_internal_unsafe: false,
691 local_inner_macros: false,
692 edition: source_map::hygiene::default_edition(),
694 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
697 fn with_anonymous_lifetime_mode<R>(
699 anonymous_lifetime_mode: AnonymousLifetimeMode,
700 op: impl FnOnce(&mut Self) -> R,
702 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
703 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
704 let result = op(self);
705 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
709 /// Creates a new hir::GenericParam for every new lifetime and
710 /// type parameter encountered while evaluating `f`. Definitions
711 /// are created with the parent provided. If no `parent_id` is
712 /// provided, no definitions will be returned.
714 /// Presuming that in-band lifetimes are enabled, then
715 /// `self.anonymous_lifetime_mode` will be updated to match the
716 /// argument while `f` is running (and restored afterwards).
717 fn collect_in_band_defs<T, F>(
720 anonymous_lifetime_mode: AnonymousLifetimeMode,
722 ) -> (Vec<hir::GenericParam>, T)
724 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
726 assert!(!self.is_collecting_in_band_lifetimes);
727 assert!(self.lifetimes_to_define.is_empty());
728 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
730 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
731 self.is_collecting_in_band_lifetimes = true;
733 let (in_band_ty_params, res) = f(self);
735 self.is_collecting_in_band_lifetimes = false;
736 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
738 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
740 let params = lifetimes_to_define
742 .map(|(span, hir_name)| {
743 let def_node_id = self.next_id().node_id;
745 // Get the name we'll use to make the def-path. Note
746 // that collisions are ok here and this shouldn't
747 // really show up for end-user.
748 let (str_name, kind) = match hir_name {
749 ParamName::Plain(ident) => (
750 ident.as_interned_str(),
751 hir::LifetimeParamKind::InBand,
753 ParamName::Fresh(_) => (
754 keywords::UnderscoreLifetime.name().as_interned_str(),
755 hir::LifetimeParamKind::Elided,
757 ParamName::Error => (
758 keywords::UnderscoreLifetime.name().as_interned_str(),
759 hir::LifetimeParamKind::Error,
763 // Add a definition for the in-band lifetime def.
764 self.resolver.definitions().create_def_with_parent(
767 DefPathData::LifetimeParam(str_name),
768 DefIndexAddressSpace::High,
779 pure_wrt_drop: false,
780 kind: hir::GenericParamKind::Lifetime { kind }
783 .chain(in_band_ty_params.into_iter())
789 /// When there is a reference to some lifetime `'a`, and in-band
790 /// lifetimes are enabled, then we want to push that lifetime into
791 /// the vector of names to define later. In that case, it will get
792 /// added to the appropriate generics.
793 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
794 if !self.is_collecting_in_band_lifetimes {
798 if !self.sess.features_untracked().in_band_lifetimes {
802 if self.in_scope_lifetimes.contains(&ident.modern()) {
806 let hir_name = ParamName::Plain(ident);
808 if self.lifetimes_to_define.iter()
809 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
813 self.lifetimes_to_define.push((ident.span, hir_name));
816 /// When we have either an elided or `'_` lifetime in an impl
817 /// header, we convert it to an in-band lifetime.
818 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
819 assert!(self.is_collecting_in_band_lifetimes);
820 let index = self.lifetimes_to_define.len();
821 let hir_name = ParamName::Fresh(index);
822 self.lifetimes_to_define.push((span, hir_name));
826 // Evaluates `f` with the lifetimes in `params` in-scope.
827 // This is used to track which lifetimes have already been defined, and
828 // which are new in-band lifetimes that need to have a definition created
830 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
832 F: FnOnce(&mut LoweringContext<'_>) -> T,
834 let old_len = self.in_scope_lifetimes.len();
835 let lt_def_names = params.iter().filter_map(|param| match param.kind {
836 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
839 self.in_scope_lifetimes.extend(lt_def_names);
843 self.in_scope_lifetimes.truncate(old_len);
847 // Same as the method above, but accepts `hir::GenericParam`s
848 // instead of `ast::GenericParam`s.
849 // This should only be used with generics that have already had their
850 // in-band lifetimes added. In practice, this means that this function is
851 // only used when lowering a child item of a trait or impl.
852 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
853 params: &HirVec<hir::GenericParam>,
856 F: FnOnce(&mut LoweringContext<'_>) -> T,
858 let old_len = self.in_scope_lifetimes.len();
859 let lt_def_names = params.iter().filter_map(|param| match param.kind {
860 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
863 self.in_scope_lifetimes.extend(lt_def_names);
867 self.in_scope_lifetimes.truncate(old_len);
871 /// Appends in-band lifetime defs and argument-position `impl
872 /// Trait` defs to the existing set of generics.
874 /// Presuming that in-band lifetimes are enabled, then
875 /// `self.anonymous_lifetime_mode` will be updated to match the
876 /// argument while `f` is running (and restored afterwards).
877 fn add_in_band_defs<F, T>(
881 anonymous_lifetime_mode: AnonymousLifetimeMode,
883 ) -> (hir::Generics, T)
885 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
887 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
890 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
891 let mut params = Vec::new();
892 let generics = this.lower_generics(
894 ImplTraitContext::Universal(&mut params),
896 let res = f(this, &mut params);
897 (params, (generics, res))
902 lowered_generics.params = lowered_generics
909 (lowered_generics, res)
912 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
914 F: FnOnce(&mut LoweringContext<'_>) -> T,
916 let len = self.catch_scopes.len();
917 self.catch_scopes.push(catch_id);
919 let result = f(self);
922 self.catch_scopes.len(),
923 "catch scopes should be added and removed in stack order"
926 self.catch_scopes.pop().unwrap();
933 capture_clause: CaptureBy,
934 closure_node_id: NodeId,
936 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
938 let prev_is_generator = mem::replace(&mut self.is_generator, true);
939 let body_expr = body(self);
940 let span = body_expr.span;
941 let output = match ret_ty {
942 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
943 None => FunctionRetTy::Default(span),
950 let body_id = self.record_body(body_expr, Some(&decl));
951 self.is_generator = prev_is_generator;
953 let capture_clause = self.lower_capture_clause(capture_clause);
954 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
955 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
956 let generator = hir::Expr {
958 hir_id: closure_hir_id,
959 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
960 Some(hir::GeneratorMovability::Static)),
962 attrs: ThinVec::new(),
965 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
966 let gen_future = self.expr_std_path(
967 unstable_span, &["future", "from_generator"], None, ThinVec::new());
968 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
971 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
973 F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
975 let prev = mem::replace(&mut self.is_generator, false);
976 let result = f(self);
977 let r = self.record_body(result, decl);
978 self.is_generator = prev;
982 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
984 F: FnOnce(&mut LoweringContext<'_>) -> T,
986 // We're no longer in the base loop's condition; we're in another loop.
987 let was_in_loop_condition = self.is_in_loop_condition;
988 self.is_in_loop_condition = false;
990 let len = self.loop_scopes.len();
991 self.loop_scopes.push(loop_id);
993 let result = f(self);
996 self.loop_scopes.len(),
997 "Loop scopes should be added and removed in stack order"
1000 self.loop_scopes.pop().unwrap();
1002 self.is_in_loop_condition = was_in_loop_condition;
1007 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
1009 F: FnOnce(&mut LoweringContext<'_>) -> T,
1011 let was_in_loop_condition = self.is_in_loop_condition;
1012 self.is_in_loop_condition = true;
1014 let result = f(self);
1016 self.is_in_loop_condition = was_in_loop_condition;
1021 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1023 F: FnOnce(&mut LoweringContext<'_>) -> T,
1025 let was_in_loop_condition = self.is_in_loop_condition;
1026 self.is_in_loop_condition = false;
1028 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1029 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1031 self.catch_scopes = catch_scopes;
1032 self.loop_scopes = loop_scopes;
1034 self.is_in_loop_condition = was_in_loop_condition;
1039 fn def_key(&mut self, id: DefId) -> DefKey {
1041 self.resolver.definitions().def_key(id.index)
1043 self.cstore.def_key(id)
1047 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1048 label.map(|label| hir::Label {
1053 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1054 let target_id = match destination {
1056 if let Def::Label(loop_id) = self.expect_full_def(id) {
1057 Ok(self.lower_node_id(loop_id).node_id)
1059 Err(hir::LoopIdError::UnresolvedLabel)
1066 .map(|id| Ok(self.lower_node_id(id).node_id))
1067 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1072 label: self.lower_label(destination.map(|(_, label)| label)),
1077 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1080 .map(|a| self.lower_attr(a))
1084 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1085 // Note that we explicitly do not walk the path. Since we don't really
1086 // lower attributes (we use the AST version) there is nowhere to keep
1087 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1091 path: attr.path.clone(),
1092 tokens: self.lower_token_stream(attr.tokens.clone()),
1093 is_sugared_doc: attr.is_sugared_doc,
1098 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1101 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1105 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1107 TokenTree::Token(span, token) => self.lower_token(token, span),
1108 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1111 self.lower_token_stream(tts.into()).into(),
1116 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1118 Token::Interpolated(_) => {}
1119 other => return TokenTree::Token(span, other).into(),
1122 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1123 self.lower_token_stream(tts)
1126 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1128 attrs: self.lower_attrs(&arm.attrs),
1129 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1130 guard: match arm.guard {
1131 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1134 body: P(self.lower_expr(&arm.body)),
1138 fn lower_ty_binding(&mut self, b: &TypeBinding,
1139 itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1141 id: self.lower_node_id(b.id).node_id,
1143 ty: self.lower_ty(&b.ty, itctx),
1148 fn lower_generic_arg(&mut self,
1149 arg: &ast::GenericArg,
1150 itctx: ImplTraitContext<'_>)
1151 -> hir::GenericArg {
1153 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1154 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1158 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1159 P(self.lower_ty_direct(t, itctx))
1162 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1163 let kind = match t.node {
1164 TyKind::Infer => hir::TyKind::Infer,
1165 TyKind::Err => hir::TyKind::Err,
1166 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1167 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1168 TyKind::Rptr(ref region, ref mt) => {
1169 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1170 let lifetime = match *region {
1171 Some(ref lt) => self.lower_lifetime(lt),
1172 None => self.elided_ref_lifetime(span),
1174 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1176 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1179 this.with_anonymous_lifetime_mode(
1180 AnonymousLifetimeMode::PassThrough,
1182 hir::TyKind::BareFn(P(hir::BareFnTy {
1183 generic_params: this.lower_generic_params(
1185 &NodeMap::default(),
1186 ImplTraitContext::disallowed(),
1188 unsafety: this.lower_unsafety(f.unsafety),
1190 decl: this.lower_fn_decl(&f.decl, None, false, None),
1191 arg_names: this.lower_fn_args_to_names(&f.decl),
1197 TyKind::Never => hir::TyKind::Never,
1198 TyKind::Tup(ref tys) => {
1199 hir::TyKind::Tup(tys.iter().map(|ty| {
1200 self.lower_ty_direct(ty, itctx.reborrow())
1203 TyKind::Paren(ref ty) => {
1204 return self.lower_ty_direct(ty, itctx);
1206 TyKind::Path(ref qself, ref path) => {
1207 let id = self.lower_node_id(t.id);
1208 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1209 let ty = self.ty_path(id, t.span, qpath);
1210 if let hir::TyKind::TraitObject(..) = ty.node {
1211 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1215 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1218 def: self.expect_full_def(t.id),
1219 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfUpper.ident())],
1223 TyKind::Array(ref ty, ref length) => {
1224 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1226 TyKind::Typeof(ref expr) => {
1227 hir::TyKind::Typeof(self.lower_anon_const(expr))
1229 TyKind::TraitObject(ref bounds, kind) => {
1230 let mut lifetime_bound = None;
1233 .filter_map(|bound| match *bound {
1234 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1235 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1237 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1238 GenericBound::Outlives(ref lifetime) => {
1239 if lifetime_bound.is_none() {
1240 lifetime_bound = Some(self.lower_lifetime(lifetime));
1246 let lifetime_bound =
1247 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1248 if kind != TraitObjectSyntax::Dyn {
1249 self.maybe_lint_bare_trait(t.span, t.id, false);
1251 hir::TyKind::TraitObject(bounds, lifetime_bound)
1253 TyKind::ImplTrait(def_node_id, ref bounds) => {
1256 ImplTraitContext::Existential(fn_def_id) => {
1257 self.lower_existential_impl_trait(
1258 span, fn_def_id, def_node_id,
1259 |this| this.lower_param_bounds(bounds, itctx),
1262 ImplTraitContext::Universal(in_band_ty_params) => {
1263 self.lower_node_id(def_node_id);
1264 // Add a definition for the in-band `Param`.
1265 let def_index = self
1268 .opt_def_index(def_node_id)
1271 let hir_bounds = self.lower_param_bounds(
1273 ImplTraitContext::Universal(in_band_ty_params),
1275 // Set the name to `impl Bound1 + Bound2`.
1276 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1277 in_band_ty_params.push(hir::GenericParam {
1279 name: ParamName::Plain(ident),
1280 pure_wrt_drop: false,
1284 kind: hir::GenericParamKind::Type {
1286 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1290 hir::TyKind::Path(hir::QPath::Resolved(
1294 def: Def::TyParam(DefId::local(def_index)),
1295 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1299 ImplTraitContext::Disallowed(pos) => {
1300 let allowed_in = if self.sess.features_untracked()
1301 .impl_trait_in_bindings {
1302 "bindings or function and inherent method return types"
1304 "function and inherent method return types"
1306 let mut err = struct_span_err!(
1310 "`impl Trait` not allowed outside of {}",
1313 if pos == ImplTraitPosition::Binding &&
1314 nightly_options::is_nightly_build() {
1316 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1324 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1327 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1336 fn lower_existential_impl_trait(
1339 fn_def_id: Option<DefId>,
1340 exist_ty_node_id: NodeId,
1341 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1343 // Make sure we know that some funky desugaring has been going on here.
1344 // This is a first: there is code in other places like for loop
1345 // desugaring that explicitly states that we don't want to track that.
1346 // Not tracking it makes lints in rustc and clippy very fragile as
1347 // frequently opened issues show.
1348 let exist_ty_span = self.allow_internal_unstable(
1349 CompilerDesugaringKind::ExistentialReturnType,
1353 let exist_ty_def_index = self
1356 .opt_def_index(exist_ty_node_id)
1359 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1361 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1363 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1369 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1370 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1371 generics: hir::Generics {
1372 params: lifetime_defs,
1373 where_clause: hir::WhereClause {
1374 id: lctx.next_id().node_id,
1375 predicates: Vec::new().into(),
1380 impl_trait_fn: fn_def_id,
1382 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1383 // Generate an `existential type Foo: Trait;` declaration.
1384 trace!("creating existential type with id {:#?}", exist_ty_id);
1386 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1387 let exist_ty_item = hir::Item {
1388 id: exist_ty_id.node_id,
1389 hir_id: exist_ty_id.hir_id,
1390 ident: keywords::Invalid.ident(),
1391 attrs: Default::default(),
1392 node: exist_ty_item_kind,
1393 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1394 span: exist_ty_span,
1397 // Insert the item into the global list. This usually happens
1398 // automatically for all AST items. But this existential type item
1399 // does not actually exist in the AST.
1400 lctx.insert_item(exist_ty_id.node_id, exist_ty_item);
1402 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1403 hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes)
1407 fn lifetimes_from_impl_trait_bounds(
1409 exist_ty_id: NodeId,
1410 parent_index: DefIndex,
1411 bounds: &hir::GenericBounds,
1412 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1413 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1414 // appear in the bounds, excluding lifetimes that are created within the bounds.
1415 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1416 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1417 context: &'r mut LoweringContext<'a>,
1419 exist_ty_id: NodeId,
1420 collect_elided_lifetimes: bool,
1421 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1422 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1423 output_lifetimes: Vec<hir::GenericArg>,
1424 output_lifetime_params: Vec<hir::GenericParam>,
1427 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1428 fn nested_visit_map<'this>(
1430 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1431 hir::intravisit::NestedVisitorMap::None
1434 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1435 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1436 if parameters.parenthesized {
1437 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1438 self.collect_elided_lifetimes = false;
1439 hir::intravisit::walk_generic_args(self, span, parameters);
1440 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1442 hir::intravisit::walk_generic_args(self, span, parameters);
1446 fn visit_ty(&mut self, t: &'v hir::Ty) {
1447 // Don't collect elided lifetimes used inside of `fn()` syntax.
1448 if let hir::TyKind::BareFn(_) = t.node {
1449 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1450 self.collect_elided_lifetimes = false;
1452 // Record the "stack height" of `for<'a>` lifetime bindings
1453 // to be able to later fully undo their introduction.
1454 let old_len = self.currently_bound_lifetimes.len();
1455 hir::intravisit::walk_ty(self, t);
1456 self.currently_bound_lifetimes.truncate(old_len);
1458 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1460 hir::intravisit::walk_ty(self, t)
1464 fn visit_poly_trait_ref(
1466 trait_ref: &'v hir::PolyTraitRef,
1467 modifier: hir::TraitBoundModifier,
1469 // Record the "stack height" of `for<'a>` lifetime bindings
1470 // to be able to later fully undo their introduction.
1471 let old_len = self.currently_bound_lifetimes.len();
1472 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1473 self.currently_bound_lifetimes.truncate(old_len);
1476 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1477 // Record the introduction of 'a in `for<'a> ...`.
1478 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1479 // Introduce lifetimes one at a time so that we can handle
1480 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1481 let lt_name = hir::LifetimeName::Param(param.name);
1482 self.currently_bound_lifetimes.push(lt_name);
1485 hir::intravisit::walk_generic_param(self, param);
1488 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1489 let name = match lifetime.name {
1490 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1491 if self.collect_elided_lifetimes {
1492 // Use `'_` for both implicit and underscore lifetimes in
1493 // `abstract type Foo<'_>: SomeTrait<'_>;`.
1494 hir::LifetimeName::Underscore
1499 hir::LifetimeName::Param(_) => lifetime.name,
1500 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1503 if !self.currently_bound_lifetimes.contains(&name)
1504 && !self.already_defined_lifetimes.contains(&name) {
1505 self.already_defined_lifetimes.insert(name);
1507 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1508 id: self.context.next_id().node_id,
1509 span: lifetime.span,
1513 // We need to manually create the ids here, because the
1514 // definitions will go into the explicit `existential type`
1515 // declaration and thus need to have their owner set to that item
1516 let def_node_id = self.context.sess.next_node_id();
1517 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1518 self.context.resolver.definitions().create_def_with_parent(
1521 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1522 DefIndexAddressSpace::High,
1527 let (name, kind) = match name {
1528 hir::LifetimeName::Underscore => (
1529 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident()),
1530 hir::LifetimeParamKind::Elided,
1532 hir::LifetimeName::Param(param_name) => (
1534 hir::LifetimeParamKind::Explicit,
1536 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1539 self.output_lifetime_params.push(hir::GenericParam {
1542 span: lifetime.span,
1543 pure_wrt_drop: false,
1546 kind: hir::GenericParamKind::Lifetime { kind }
1552 let mut lifetime_collector = ImplTraitLifetimeCollector {
1554 parent: parent_index,
1556 collect_elided_lifetimes: true,
1557 currently_bound_lifetimes: Vec::new(),
1558 already_defined_lifetimes: FxHashSet::default(),
1559 output_lifetimes: Vec::new(),
1560 output_lifetime_params: Vec::new(),
1563 for bound in bounds {
1564 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1568 lifetime_collector.output_lifetimes.into(),
1569 lifetime_collector.output_lifetime_params.into(),
1573 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1578 .map(|x| self.lower_foreign_item(x))
1583 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1590 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1592 node: hir::VariantKind {
1593 ident: v.node.ident,
1594 attrs: self.lower_attrs(&v.node.attrs),
1595 data: self.lower_variant_data(&v.node.data),
1596 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1605 qself: &Option<QSelf>,
1607 param_mode: ParamMode,
1608 mut itctx: ImplTraitContext<'_>,
1610 let qself_position = qself.as_ref().map(|q| q.position);
1611 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1613 let resolution = self.resolver
1615 .unwrap_or_else(|| PathResolution::new(Def::Err));
1617 let proj_start = p.segments.len() - resolution.unresolved_segments();
1618 let path = P(hir::Path {
1619 def: resolution.base_def(),
1620 segments: p.segments[..proj_start]
1623 .map(|(i, segment)| {
1624 let param_mode = match (qself_position, param_mode) {
1625 (Some(j), ParamMode::Optional) if i < j => {
1626 // This segment is part of the trait path in a
1627 // qualified path - one of `a`, `b` or `Trait`
1628 // in `<X as a::b::Trait>::T::U::method`.
1634 // Figure out if this is a type/trait segment,
1635 // which may need lifetime elision performed.
1636 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1637 krate: def_id.krate,
1638 index: this.def_key(def_id).parent.expect("missing parent"),
1640 let type_def_id = match resolution.base_def() {
1641 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1642 Some(parent_def_id(self, def_id))
1644 Def::Variant(def_id) if i + 1 == proj_start => {
1645 Some(parent_def_id(self, def_id))
1648 | Def::Union(def_id)
1650 | Def::TyAlias(def_id)
1651 | Def::Trait(def_id) if i + 1 == proj_start =>
1657 let parenthesized_generic_args = match resolution.base_def() {
1658 // `a::b::Trait(Args)`
1659 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1660 // `a::b::Trait(Args)::TraitItem`
1661 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1662 if i + 2 == proj_start =>
1664 ParenthesizedGenericArgs::Ok
1666 // Avoid duplicated errors.
1667 Def::Err => ParenthesizedGenericArgs::Ok,
1673 | Def::Variant(..) if i + 1 == proj_start =>
1675 ParenthesizedGenericArgs::Err
1677 // A warning for now, for compatibility reasons
1678 _ => ParenthesizedGenericArgs::Warn,
1681 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1682 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1685 assert!(!def_id.is_local());
1687 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1688 let n = item_generics.own_counts().lifetimes;
1689 self.type_def_lifetime_params.insert(def_id, n);
1692 self.lower_path_segment(
1697 parenthesized_generic_args,
1706 // Simple case, either no projections, or only fully-qualified.
1707 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1708 if resolution.unresolved_segments() == 0 {
1709 return hir::QPath::Resolved(qself, path);
1712 // Create the innermost type that we're projecting from.
1713 let mut ty = if path.segments.is_empty() {
1714 // If the base path is empty that means there exists a
1715 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1716 qself.expect("missing QSelf for <T>::...")
1718 // Otherwise, the base path is an implicit `Self` type path,
1719 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1720 // `<I as Iterator>::Item::default`.
1721 let new_id = self.next_id();
1722 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1725 // Anything after the base path are associated "extensions",
1726 // out of which all but the last one are associated types,
1727 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1728 // * base path is `std::vec::Vec<T>`
1729 // * "extensions" are `IntoIter`, `Item` and `clone`
1730 // * type nodes are:
1731 // 1. `std::vec::Vec<T>` (created above)
1732 // 2. `<std::vec::Vec<T>>::IntoIter`
1733 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1734 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1735 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1736 let segment = P(self.lower_path_segment(
1741 ParenthesizedGenericArgs::Warn,
1745 let qpath = hir::QPath::TypeRelative(ty, segment);
1747 // It's finished, return the extension of the right node type.
1748 if i == p.segments.len() - 1 {
1752 // Wrap the associated extension in another type node.
1753 let new_id = self.next_id();
1754 ty = P(self.ty_path(new_id, p.span, qpath));
1757 // We should've returned in the for loop above.
1760 "lower_qpath: no final extension segment in {}..{}",
1766 fn lower_path_extra(
1770 param_mode: ParamMode,
1771 explicit_owner: Option<NodeId>,
1775 segments: p.segments
1778 self.lower_path_segment(
1783 ParenthesizedGenericArgs::Err,
1784 ImplTraitContext::disallowed(),
1793 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1794 let def = self.expect_full_def(id);
1795 self.lower_path_extra(def, p, param_mode, None)
1798 fn lower_path_segment(
1801 segment: &PathSegment,
1802 param_mode: ParamMode,
1803 expected_lifetimes: usize,
1804 parenthesized_generic_args: ParenthesizedGenericArgs,
1805 itctx: ImplTraitContext<'_>,
1806 explicit_owner: Option<NodeId>,
1807 ) -> hir::PathSegment {
1808 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1809 let msg = "parenthesized parameters may only be used with a trait";
1810 match **generic_args {
1811 GenericArgs::AngleBracketed(ref data) => {
1812 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1814 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1815 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1816 ParenthesizedGenericArgs::Warn => {
1817 self.sess.buffer_lint(
1818 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1823 (hir::GenericArgs::none(), true)
1825 ParenthesizedGenericArgs::Err => {
1826 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1827 .span_label(data.span, "only traits may use parentheses")
1829 (hir::GenericArgs::none(), false)
1834 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1837 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1838 GenericArg::Lifetime(_) => true,
1841 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1842 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1843 if !generic_args.parenthesized && !has_lifetimes {
1845 self.elided_path_lifetimes(path_span, expected_lifetimes)
1847 .map(|lt| GenericArg::Lifetime(lt))
1848 .chain(generic_args.args.into_iter())
1850 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1851 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1852 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1853 let no_bindings = generic_args.bindings.is_empty();
1854 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1855 // If there are no (non-implicit) generic args or associated-type
1856 // bindings, our suggestion includes the angle brackets.
1857 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1859 // Otherwise—sorry, this is kind of gross—we need to infer the
1860 // place to splice in the `'_, ` from the generics that do exist.
1861 let first_generic_span = first_generic_span
1862 .expect("already checked that type args or bindings exist");
1863 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1865 self.sess.buffer_lint_with_diagnostic(
1866 ELIDED_LIFETIMES_IN_PATHS,
1869 "hidden lifetime parameters in types are deprecated",
1870 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1871 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1877 let def = self.expect_full_def(segment.id);
1878 let id = if let Some(owner) = explicit_owner {
1879 self.lower_node_id_with_owner(segment.id, owner)
1881 self.lower_node_id(segment.id)
1884 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
1885 segment.ident, segment.id, id,
1888 hir::PathSegment::new(
1897 fn lower_angle_bracketed_parameter_data(
1899 data: &AngleBracketedArgs,
1900 param_mode: ParamMode,
1901 mut itctx: ImplTraitContext<'_>,
1902 ) -> (hir::GenericArgs, bool) {
1903 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1904 let has_types = args.iter().any(|arg| match arg {
1905 ast::GenericArg::Type(_) => true,
1909 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1910 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1911 parenthesized: false,
1913 !has_types && param_mode == ParamMode::Optional)
1916 fn lower_parenthesized_parameter_data(
1918 data: &ParenthesisedArgs,
1919 ) -> (hir::GenericArgs, bool) {
1920 // Switch to `PassThrough` mode for anonymous lifetimes: this
1921 // means that we permit things like `&Ref<T>`, where `Ref` has
1922 // a hidden lifetime parameter. This is needed for backwards
1923 // compatibility, even in contexts like an impl header where
1924 // we generally don't permit such things (see #51008).
1925 self.with_anonymous_lifetime_mode(
1926 AnonymousLifetimeMode::PassThrough,
1928 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1931 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
1933 let mk_tup = |this: &mut Self, tys, span| {
1934 let LoweredNodeId { node_id, hir_id } = this.next_id();
1935 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1940 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1943 id: this.next_id().node_id,
1944 ident: Ident::from_str(FN_OUTPUT_NAME),
1947 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
1948 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1949 span: output.as_ref().map_or(span, |ty| ty.span),
1952 parenthesized: true,
1960 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[hir::ItemId; 1]>) {
1961 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1962 let mut ids = SmallVec::<[hir::ItemId; 1]>::new();
1963 if self.sess.features_untracked().impl_trait_in_bindings {
1964 if let Some(ref ty) = l.ty {
1965 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1966 visitor.visit_ty(ty);
1969 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
1975 .map(|t| self.lower_ty(t,
1976 if self.sess.features_untracked().impl_trait_in_bindings {
1977 ImplTraitContext::Existential(Some(parent_def_id))
1979 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1982 pat: self.lower_pat(&l.pat),
1983 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1985 attrs: l.attrs.clone(),
1986 source: hir::LocalSource::Normal,
1990 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1992 Mutability::Mutable => hir::MutMutable,
1993 Mutability::Immutable => hir::MutImmutable,
1997 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1998 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
2002 pat: self.lower_pat(&arg.pat),
2006 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2009 .map(|arg| match arg.pat.node {
2010 PatKind::Ident(_, ident, _) => ident,
2011 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
2016 // Lowers a function declaration.
2018 // decl: the unlowered (ast) function declaration.
2019 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
2020 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2021 // make_ret_async is also `Some`.
2022 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
2023 // This guards against trait declarations and implementations where impl Trait is
2025 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2026 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
2027 // return type impl Trait item.
2031 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2032 impl_trait_return_allow: bool,
2033 make_ret_async: Option<NodeId>,
2034 ) -> P<hir::FnDecl> {
2035 let inputs = decl.inputs
2038 if let Some((_, ref mut ibty)) = in_band_ty_params {
2039 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2041 self.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2044 .collect::<HirVec<_>>();
2046 let output = if let Some(ret_id) = make_ret_async {
2047 self.lower_async_fn_ret_ty(
2050 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2055 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2056 Some((def_id, _)) if impl_trait_return_allow => {
2057 hir::Return(self.lower_ty(ty,
2058 ImplTraitContext::Existential(Some(def_id))))
2061 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2064 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2071 variadic: decl.variadic,
2072 implicit_self: decl.inputs.get(0).map_or(
2073 hir::ImplicitSelfKind::None,
2075 let is_mutable_pat = match arg.pat.node {
2076 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2077 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2078 mt == Mutability::Mutable,
2083 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2084 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2085 // Given we are only considering `ImplicitSelf` types, we needn't consider
2086 // the case where we have a mutable pattern to a reference as that would
2087 // no longer be an `ImplicitSelf`.
2088 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2089 mt.mutbl == ast::Mutability::Mutable =>
2090 hir::ImplicitSelfKind::MutRef,
2091 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2092 hir::ImplicitSelfKind::ImmRef,
2093 _ => hir::ImplicitSelfKind::None,
2100 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
2102 // fn_span: the span of the async function declaration. Used for error reporting.
2103 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2104 // output: unlowered output type (`T` in `-> T`)
2105 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2106 fn lower_async_fn_ret_ty(
2109 output: &FunctionRetTy,
2111 return_impl_trait_id: NodeId,
2112 ) -> hir::FunctionRetTy {
2113 // Get lifetimes used in the input arguments to the function. Our output type must also
2114 // have the same lifetime.
2115 // FIXME(cramertj): multiple different lifetimes are not allowed because
2116 // `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither is a subset
2117 // of the other. We really want some new lifetime that is a subset of all input lifetimes,
2118 // but that doesn't exist at the moment.
2120 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
2121 context: &'r mut LoweringContext<'a>,
2122 // Lifetimes bound by HRTB.
2123 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2124 // Whether to count elided lifetimes.
2125 // Disabled inside of `Fn` or `fn` syntax.
2126 collect_elided_lifetimes: bool,
2127 // The lifetime found.
2128 // Multiple different or elided lifetimes cannot appear in async fn for now.
2129 output_lifetime: Option<(hir::LifetimeName, Span)>,
2132 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2133 fn nested_visit_map<'this>(
2135 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2136 hir::intravisit::NestedVisitorMap::None
2139 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2140 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2141 if parameters.parenthesized {
2142 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2143 self.collect_elided_lifetimes = false;
2144 hir::intravisit::walk_generic_args(self, span, parameters);
2145 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2147 hir::intravisit::walk_generic_args(self, span, parameters);
2151 fn visit_ty(&mut self, t: &'v hir::Ty) {
2152 // Don't collect elided lifetimes used inside of `fn()` syntax.
2153 if let &hir::TyKind::BareFn(_) = &t.node {
2154 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2155 self.collect_elided_lifetimes = false;
2157 // Record the "stack height" of `for<'a>` lifetime bindings
2158 // to be able to later fully undo their introduction.
2159 let old_len = self.currently_bound_lifetimes.len();
2160 hir::intravisit::walk_ty(self, t);
2161 self.currently_bound_lifetimes.truncate(old_len);
2163 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2165 hir::intravisit::walk_ty(self, t);
2169 fn visit_poly_trait_ref(
2171 trait_ref: &'v hir::PolyTraitRef,
2172 modifier: hir::TraitBoundModifier,
2174 // Record the "stack height" of `for<'a>` lifetime bindings
2175 // to be able to later fully undo their introduction.
2176 let old_len = self.currently_bound_lifetimes.len();
2177 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2178 self.currently_bound_lifetimes.truncate(old_len);
2181 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2182 // Record the introduction of 'a in `for<'a> ...`
2183 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2184 // Introduce lifetimes one at a time so that we can handle
2185 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2186 let lt_name = hir::LifetimeName::Param(param.name);
2187 self.currently_bound_lifetimes.push(lt_name);
2190 hir::intravisit::walk_generic_param(self, param);
2193 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2194 let name = match lifetime.name {
2195 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2196 if self.collect_elided_lifetimes {
2197 // Use `'_` for both implicit and underscore lifetimes in
2198 // `abstract type Foo<'_>: SomeTrait<'_>;`
2199 hir::LifetimeName::Underscore
2204 hir::LifetimeName::Param(_) => lifetime.name,
2205 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2208 if !self.currently_bound_lifetimes.contains(&name) {
2209 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2210 // We don't currently have a reliable way to desugar `async fn` with
2211 // multiple potentially unrelated input lifetimes into
2212 // `-> impl Trait + 'lt`, so we report an error in this case.
2213 if current_lt_name != name {
2216 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2218 "multiple different lifetimes used in arguments of `async fn`",
2220 .span_label(current_lt_span, "first lifetime here")
2221 .span_label(lifetime.span, "different lifetime here")
2222 .help("`async fn` can only accept borrowed values \
2223 with identical lifetimes")
2225 } else if current_lt_name.is_elided() && name.is_elided() {
2228 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2230 "multiple elided lifetimes used in arguments of `async fn`",
2232 .span_label(current_lt_span, "first lifetime here")
2233 .span_label(lifetime.span, "different lifetime here")
2234 .help("consider giving these arguments named lifetimes")
2238 self.output_lifetime = Some((name, lifetime.span));
2244 let bound_lifetime = {
2245 let mut lifetime_collector = AsyncFnLifetimeCollector {
2247 currently_bound_lifetimes: Vec::new(),
2248 collect_elided_lifetimes: true,
2249 output_lifetime: None,
2253 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2255 lifetime_collector.output_lifetime
2258 let span = match output {
2259 FunctionRetTy::Ty(ty) => ty.span,
2260 FunctionRetTy::Default(span) => *span,
2263 let impl_trait_ty = self.lower_existential_impl_trait(
2264 span, Some(fn_def_id), return_impl_trait_id, |this| {
2265 let output_ty = match output {
2266 FunctionRetTy::Ty(ty) => {
2267 this.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2269 FunctionRetTy::Default(span) => {
2270 let LoweredNodeId { node_id, hir_id } = this.next_id();
2274 node: hir::TyKind::Tup(hir_vec![]),
2281 let future_params = P(hir::GenericArgs {
2283 bindings: hir_vec![hir::TypeBinding {
2284 ident: Ident::from_str(FN_OUTPUT_NAME),
2286 id: this.next_id().node_id,
2289 parenthesized: false,
2293 this.std_path(span, &["future", "Future"], Some(future_params), false);
2295 let LoweredNodeId { node_id, hir_id } = this.next_id();
2296 let mut bounds = vec![
2297 hir::GenericBound::Trait(
2299 trait_ref: hir::TraitRef {
2304 bound_generic_params: hir_vec![],
2307 hir::TraitBoundModifier::None
2311 if let Some((name, span)) = bound_lifetime {
2312 bounds.push(hir::GenericBound::Outlives(
2313 hir::Lifetime { id: this.next_id().node_id, name, span }));
2316 hir::HirVec::from(bounds)
2319 let LoweredNodeId { node_id, hir_id } = self.next_id();
2320 let impl_trait_ty = P(hir::Ty {
2322 node: impl_trait_ty,
2327 hir::FunctionRetTy::Return(impl_trait_ty)
2330 fn lower_param_bound(
2333 itctx: ImplTraitContext<'_>,
2334 ) -> hir::GenericBound {
2336 GenericBound::Trait(ref ty, modifier) => {
2337 hir::GenericBound::Trait(
2338 self.lower_poly_trait_ref(ty, itctx),
2339 self.lower_trait_bound_modifier(modifier),
2342 GenericBound::Outlives(ref lifetime) => {
2343 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2348 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2349 let span = l.ident.span;
2351 ident if ident.name == keywords::StaticLifetime.name() =>
2352 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2353 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2354 match self.anonymous_lifetime_mode {
2355 AnonymousLifetimeMode::CreateParameter => {
2356 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2357 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2360 AnonymousLifetimeMode::PassThrough => {
2361 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2364 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2367 self.maybe_collect_in_band_lifetime(ident);
2368 let param_name = ParamName::Plain(ident);
2369 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2374 fn new_named_lifetime(
2378 name: hir::LifetimeName,
2379 ) -> hir::Lifetime {
2381 id: self.lower_node_id(id).node_id,
2387 fn lower_generic_params(
2389 params: &[GenericParam],
2390 add_bounds: &NodeMap<Vec<GenericBound>>,
2391 mut itctx: ImplTraitContext<'_>,
2392 ) -> hir::HirVec<hir::GenericParam> {
2393 params.iter().map(|param| {
2394 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2398 fn lower_generic_param(&mut self,
2399 param: &GenericParam,
2400 add_bounds: &NodeMap<Vec<GenericBound>>,
2401 mut itctx: ImplTraitContext<'_>)
2402 -> hir::GenericParam {
2403 let mut bounds = self.with_anonymous_lifetime_mode(
2404 AnonymousLifetimeMode::ReportError,
2405 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2409 GenericParamKind::Lifetime => {
2410 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2411 self.is_collecting_in_band_lifetimes = false;
2413 let lt = self.with_anonymous_lifetime_mode(
2414 AnonymousLifetimeMode::ReportError,
2415 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2417 let param_name = match lt.name {
2418 hir::LifetimeName::Param(param_name) => param_name,
2419 hir::LifetimeName::Implicit
2420 | hir::LifetimeName::Underscore
2421 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2422 hir::LifetimeName::Error => ParamName::Error,
2424 let param = hir::GenericParam {
2428 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2429 attrs: self.lower_attrs(¶m.attrs),
2431 kind: hir::GenericParamKind::Lifetime {
2432 kind: hir::LifetimeParamKind::Explicit,
2436 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2440 GenericParamKind::Type { ref default, .. } => {
2441 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2442 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2443 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2444 let ident = if param.ident.name == keywords::SelfUpper.name() {
2445 param.ident.gensym()
2450 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2451 if !add_bounds.is_empty() {
2452 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2453 bounds = bounds.into_iter()
2459 id: self.lower_node_id(param.id).node_id,
2460 name: hir::ParamName::Plain(ident),
2461 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2462 attrs: self.lower_attrs(¶m.attrs),
2465 kind: hir::GenericParamKind::Type {
2466 default: default.as_ref().map(|x| {
2467 self.lower_ty(x, ImplTraitContext::disallowed())
2469 synthetic: param.attrs.iter()
2470 .filter(|attr| attr.check_name("rustc_synthetic"))
2471 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2481 generics: &Generics,
2482 itctx: ImplTraitContext<'_>)
2485 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2486 // FIXME: this could probably be done with less rightward drift. Also looks like two control
2487 // paths where report_error is called are also the only paths that advance to after
2488 // the match statement, so the error reporting could probably just be moved there.
2489 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2490 for pred in &generics.where_clause.predicates {
2491 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2492 'next_bound: for bound in &bound_pred.bounds {
2493 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2494 let report_error = |this: &mut Self| {
2495 this.diagnostic().span_err(
2496 bound_pred.bounded_ty.span,
2497 "`?Trait` bounds are only permitted at the \
2498 point where a type parameter is declared",
2501 // Check if the where clause type is a plain type parameter.
2502 match bound_pred.bounded_ty.node {
2503 TyKind::Path(None, ref path)
2504 if path.segments.len() == 1
2505 && bound_pred.bound_generic_params.is_empty() =>
2507 if let Some(Def::TyParam(def_id)) = self.resolver
2508 .get_resolution(bound_pred.bounded_ty.id)
2509 .map(|d| d.base_def())
2511 if let Some(node_id) =
2512 self.resolver.definitions().as_local_node_id(def_id)
2514 for param in &generics.params {
2516 GenericParamKind::Type { .. } => {
2517 if node_id == param.id {
2518 add_bounds.entry(param.id)
2520 .push(bound.clone());
2521 continue 'next_bound;
2531 _ => report_error(self),
2539 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2540 where_clause: self.lower_where_clause(&generics.where_clause),
2541 span: generics.span,
2545 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2546 self.with_anonymous_lifetime_mode(
2547 AnonymousLifetimeMode::ReportError,
2550 id: this.lower_node_id(wc.id).node_id,
2551 predicates: wc.predicates
2553 .map(|predicate| this.lower_where_predicate(predicate))
2560 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2562 WherePredicate::BoundPredicate(WhereBoundPredicate {
2563 ref bound_generic_params,
2568 self.with_in_scope_lifetime_defs(
2569 &bound_generic_params,
2571 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2572 bound_generic_params: this.lower_generic_params(
2573 bound_generic_params,
2574 &NodeMap::default(),
2575 ImplTraitContext::disallowed(),
2577 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2580 .filter_map(|bound| match *bound {
2581 // Ignore `?Trait` bounds.
2582 // They were copied into type parameters already.
2583 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2584 _ => Some(this.lower_param_bound(
2586 ImplTraitContext::disallowed(),
2595 WherePredicate::RegionPredicate(WhereRegionPredicate {
2599 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2601 lifetime: self.lower_lifetime(lifetime),
2602 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2604 WherePredicate::EqPredicate(WhereEqPredicate {
2609 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2610 id: self.lower_node_id(id).node_id,
2611 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2612 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2618 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2620 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2624 .map(|f| self.lower_struct_field(f))
2626 self.lower_node_id(id).node_id,
2628 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2632 .map(|f| self.lower_struct_field(f))
2634 self.lower_node_id(id).node_id,
2636 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2640 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2641 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2642 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2643 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2645 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2653 fn lower_poly_trait_ref(
2656 mut itctx: ImplTraitContext<'_>,
2657 ) -> hir::PolyTraitRef {
2658 let bound_generic_params = self.lower_generic_params(
2659 &p.bound_generic_params,
2660 &NodeMap::default(),
2663 let trait_ref = self.with_parent_impl_lifetime_defs(
2664 &bound_generic_params,
2665 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2669 bound_generic_params,
2675 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2678 id: self.lower_node_id(f.id).node_id,
2679 ident: match f.ident {
2680 Some(ident) => ident,
2681 // FIXME(jseyfried): positional field hygiene
2682 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2684 vis: self.lower_visibility(&f.vis, None),
2685 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2686 attrs: self.lower_attrs(&f.attrs),
2690 fn lower_field(&mut self, f: &Field) -> hir::Field {
2692 id: self.next_id().node_id,
2694 expr: P(self.lower_expr(&f.expr)),
2696 is_shorthand: f.is_shorthand,
2700 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2702 ty: self.lower_ty(&mt.ty, itctx),
2703 mutbl: self.lower_mutability(mt.mutbl),
2707 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2708 -> hir::GenericBounds {
2709 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2712 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2713 let mut expr = None;
2715 let mut stmts = vec![];
2717 for (index, stmt) in b.stmts.iter().enumerate() {
2718 if index == b.stmts.len() - 1 {
2719 if let StmtKind::Expr(ref e) = stmt.node {
2720 expr = Some(P(self.lower_expr(e)));
2722 stmts.extend(self.lower_stmt(stmt));
2725 stmts.extend(self.lower_stmt(stmt));
2729 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2734 stmts: stmts.into(),
2736 rules: self.lower_block_check_mode(&b.rules),
2742 fn lower_async_body(
2748 self.lower_body(Some(decl), |this| {
2749 if let IsAsync::Async { closure_id, .. } = asyncness {
2750 let async_expr = this.make_async_expr(
2751 CaptureBy::Value, closure_id, None,
2753 let body = this.lower_block(body, false);
2754 this.expr_block(body, ThinVec::new())
2756 this.expr(body.span, async_expr, ThinVec::new())
2758 let body = this.lower_block(body, false);
2759 this.expr_block(body, ThinVec::new())
2768 attrs: &hir::HirVec<Attribute>,
2769 vis: &mut hir::Visibility,
2771 ) -> hir::ItemKind {
2773 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2774 ItemKind::Use(ref use_tree) => {
2775 // Start with an empty prefix
2778 span: use_tree.span,
2781 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
2783 ItemKind::Static(ref t, m, ref e) => {
2784 let value = self.lower_body(None, |this| this.lower_expr(e));
2785 hir::ItemKind::Static(
2788 if self.sess.features_untracked().impl_trait_in_bindings {
2789 ImplTraitContext::Existential(None)
2791 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2794 self.lower_mutability(m),
2798 ItemKind::Const(ref t, ref e) => {
2799 let value = self.lower_body(None, |this| this.lower_expr(e));
2800 hir::ItemKind::Const(
2803 if self.sess.features_untracked().impl_trait_in_bindings {
2804 ImplTraitContext::Existential(None)
2806 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2812 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2813 let fn_def_id = self.resolver.definitions().local_def_id(id);
2814 self.with_new_scopes(|this| {
2815 // Note: we don't need to change the return type from `T` to
2816 // `impl Future<Output = T>` here because lower_body
2817 // only cares about the input argument patterns in the function
2818 // declaration (decl), not the return types.
2819 let body_id = this.lower_async_body(decl, header.asyncness, body);
2821 let (generics, fn_decl) = this.add_in_band_defs(
2824 AnonymousLifetimeMode::PassThrough,
2825 |this, idty| this.lower_fn_decl(
2827 Some((fn_def_id, idty)),
2829 header.asyncness.opt_return_id()
2835 this.lower_fn_header(header),
2841 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2842 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2843 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2844 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2845 self.lower_ty(t, ImplTraitContext::disallowed()),
2846 self.lower_generics(generics, ImplTraitContext::disallowed()),
2848 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2849 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
2850 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
2851 impl_trait_fn: None,
2853 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2855 variants: enum_definition
2858 .map(|x| self.lower_variant(x))
2861 self.lower_generics(generics, ImplTraitContext::disallowed()),
2863 ItemKind::Struct(ref struct_def, ref generics) => {
2864 let struct_def = self.lower_variant_data(struct_def);
2865 hir::ItemKind::Struct(
2867 self.lower_generics(generics, ImplTraitContext::disallowed()),
2870 ItemKind::Union(ref vdata, ref generics) => {
2871 let vdata = self.lower_variant_data(vdata);
2872 hir::ItemKind::Union(
2874 self.lower_generics(generics, ImplTraitContext::disallowed()),
2886 let def_id = self.resolver.definitions().local_def_id(id);
2888 // Lower the "impl header" first. This ordering is important
2889 // for in-band lifetimes! Consider `'a` here:
2891 // impl Foo<'a> for u32 {
2892 // fn method(&'a self) { .. }
2895 // Because we start by lowering the `Foo<'a> for u32`
2896 // part, we will add `'a` to the list of generics on
2897 // the impl. When we then encounter it later in the
2898 // method, it will not be considered an in-band
2899 // lifetime to be added, but rather a reference to a
2901 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2904 AnonymousLifetimeMode::CreateParameter,
2906 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2907 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
2910 if let Some(ref trait_ref) = trait_ref {
2911 if let Def::Trait(def_id) = trait_ref.path.def {
2912 this.trait_impls.entry(def_id).or_default().push(id);
2916 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
2918 (trait_ref, lowered_ty)
2922 let new_impl_items = self.with_in_scope_lifetime_defs(
2923 &ast_generics.params,
2927 .map(|item| this.lower_impl_item_ref(item))
2932 hir::ItemKind::Impl(
2933 self.lower_unsafety(unsafety),
2934 self.lower_impl_polarity(polarity),
2935 self.lower_defaultness(defaultness, true /* [1] */),
2942 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2943 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
2946 .map(|item| self.lower_trait_item_ref(item))
2948 hir::ItemKind::Trait(
2949 self.lower_is_auto(is_auto),
2950 self.lower_unsafety(unsafety),
2951 self.lower_generics(generics, ImplTraitContext::disallowed()),
2956 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2957 self.lower_generics(generics, ImplTraitContext::disallowed()),
2958 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2960 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2963 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2964 // not cause an assertion failure inside the `lower_defaultness` function.
2972 vis: &mut hir::Visibility,
2974 attrs: &hir::HirVec<Attribute>,
2975 ) -> hir::ItemKind {
2976 debug!("lower_use_tree(tree={:?})", tree);
2977 debug!("lower_use_tree: vis = {:?}", vis);
2979 let path = &tree.prefix;
2980 let segments = prefix
2983 .chain(path.segments.iter())
2988 UseTreeKind::Simple(rename, id1, id2) => {
2989 *ident = tree.ident();
2991 // First, apply the prefix to the path.
2992 let mut path = Path {
2997 // Correctly resolve `self` imports.
2998 if path.segments.len() > 1
2999 && path.segments.last().unwrap().ident.name == keywords::SelfLower.name()
3001 let _ = path.segments.pop();
3002 if rename.is_none() {
3003 *ident = path.segments.last().unwrap().ident;
3007 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
3008 let mut defs = self.expect_full_def_from_use(id);
3009 // We want to return *something* from this function, so hold onto the first item
3011 let ret_def = defs.next().unwrap_or(Def::Err);
3013 // Here, we are looping over namespaces, if they exist for the definition
3014 // being imported. We only handle type and value namespaces because we
3015 // won't be dealing with macros in the rest of the compiler.
3016 // Essentially a single `use` which imports two names is desugared into
3018 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
3019 let vis = vis.clone();
3020 let ident = ident.clone();
3021 let mut path = path.clone();
3022 for seg in &mut path.segments {
3023 seg.id = self.sess.next_node_id();
3025 let span = path.span;
3026 self.resolver.definitions().create_def_with_parent(
3030 DefIndexAddressSpace::High,
3033 self.allocate_hir_id_counter(new_node_id, &path);
3035 self.with_hir_id_owner(new_node_id, |this| {
3036 let new_id = this.lower_node_id(new_node_id);
3038 this.lower_path_extra(def, &path, ParamMode::Explicit, None);
3039 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3040 let vis_kind = match vis.node {
3041 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3042 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3043 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3044 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3045 let id = this.next_id();
3046 let path = this.renumber_segment_ids(path);
3047 hir::VisibilityKind::Restricted {
3054 let vis = respan(vis.span, vis_kind);
3060 hir_id: new_id.hir_id,
3062 attrs: attrs.clone(),
3072 P(self.lower_path_extra(ret_def, &path, ParamMode::Explicit, None));
3073 hir::ItemKind::Use(path, hir::UseKind::Single)
3075 UseTreeKind::Glob => {
3076 let path = P(self.lower_path(
3082 ParamMode::Explicit,
3084 hir::ItemKind::Use(path, hir::UseKind::Glob)
3086 UseTreeKind::Nested(ref trees) => {
3087 // Nested imports are desugared into simple imports.
3088 // So, if we start with
3091 // pub(x) use foo::{a, b};
3094 // we will create three items:
3097 // pub(x) use foo::a;
3098 // pub(x) use foo::b;
3099 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3102 // The first two are produced by recursively invoking
3103 // `lower_use_tree` (and indeed there may be things
3104 // like `use foo::{a::{b, c}}` and so forth). They
3105 // wind up being directly added to
3106 // `self.items`. However, the structure of this
3107 // function also requires us to return one item, and
3108 // for that we return the `{}` import (called the
3113 span: prefix.span.to(path.span),
3116 // Add all the nested `PathListItem`s to the HIR.
3117 for &(ref use_tree, id) in trees {
3118 self.allocate_hir_id_counter(id, &use_tree);
3123 } = self.lower_node_id(id);
3125 let mut vis = vis.clone();
3126 let mut ident = ident.clone();
3127 let mut prefix = prefix.clone();
3129 // Give the segments new node-ids since they are being cloned.
3130 for seg in &mut prefix.segments {
3131 seg.id = self.sess.next_node_id();
3134 // Each `use` import is an item and thus are owners of the
3135 // names in the path. Up to this point the nested import is
3136 // the current owner, since we want each desugared import to
3137 // own its own names, we have to adjust the owner before
3138 // lowering the rest of the import.
3139 self.with_hir_id_owner(new_id, |this| {
3140 let item = this.lower_use_tree(use_tree,
3147 let vis_kind = match vis.node {
3148 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3149 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3150 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3151 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3152 let id = this.next_id();
3153 let path = this.renumber_segment_ids(path);
3154 hir::VisibilityKind::Restricted {
3161 let vis = respan(vis.span, vis_kind);
3169 attrs: attrs.clone(),
3172 span: use_tree.span,
3178 // Subtle and a bit hacky: we lower the privacy level
3179 // of the list stem to "private" most of the time, but
3180 // not for "restricted" paths. The key thing is that
3181 // we don't want it to stay as `pub` (with no caveats)
3182 // because that affects rustdoc and also the lints
3183 // about `pub` items. But we can't *always* make it
3184 // private -- particularly not for restricted paths --
3185 // because it contains node-ids that would then be
3186 // unused, failing the check that HirIds are "densely
3189 hir::VisibilityKind::Public |
3190 hir::VisibilityKind::Crate(_) |
3191 hir::VisibilityKind::Inherited => {
3192 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3194 hir::VisibilityKind::Restricted { .. } => {
3195 // Do nothing here, as described in the comment on the match.
3199 let def = self.expect_full_def_from_use(id).next().unwrap_or(Def::Err);
3200 let path = P(self.lower_path_extra(def, &prefix, ParamMode::Explicit, None));
3201 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3206 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3207 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3208 /// node-ids. (See e.g., #56128.)
3209 fn renumber_segment_ids(&mut self, path: &P<hir::Path>) -> P<hir::Path> {
3210 debug!("renumber_segment_ids(path = {:?})", path);
3211 let mut path = path.clone();
3212 for seg in path.segments.iter_mut() {
3213 if seg.id.is_some() {
3214 seg.id = Some(self.next_id().node_id);
3220 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3221 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3222 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3224 let (generics, node) = match i.node {
3225 TraitItemKind::Const(ref ty, ref default) => (
3226 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3227 hir::TraitItemKind::Const(
3228 self.lower_ty(ty, ImplTraitContext::disallowed()),
3231 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3234 TraitItemKind::Method(ref sig, None) => {
3235 let names = self.lower_fn_args_to_names(&sig.decl);
3236 let (generics, sig) = self.lower_method_sig(
3243 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3245 TraitItemKind::Method(ref sig, Some(ref body)) => {
3246 let body_id = self.lower_body(Some(&sig.decl), |this| {
3247 let body = this.lower_block(body, false);
3248 this.expr_block(body, ThinVec::new())
3250 let (generics, sig) = self.lower_method_sig(
3257 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3259 TraitItemKind::Type(ref bounds, ref default) => (
3260 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3261 hir::TraitItemKind::Type(
3262 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3265 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3268 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3275 attrs: self.lower_attrs(&i.attrs),
3282 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3283 let (kind, has_default) = match i.node {
3284 TraitItemKind::Const(_, ref default) => {
3285 (hir::AssociatedItemKind::Const, default.is_some())
3287 TraitItemKind::Type(_, ref default) => {
3288 (hir::AssociatedItemKind::Type, default.is_some())
3290 TraitItemKind::Method(ref sig, ref default) => (
3291 hir::AssociatedItemKind::Method {
3292 has_self: sig.decl.has_self(),
3296 TraitItemKind::Macro(..) => unimplemented!(),
3299 id: hir::TraitItemId { node_id: i.id },
3302 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3307 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3308 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3309 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3311 let (generics, node) = match i.node {
3312 ImplItemKind::Const(ref ty, ref expr) => {
3313 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3315 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3316 hir::ImplItemKind::Const(
3317 self.lower_ty(ty, ImplTraitContext::disallowed()),
3322 ImplItemKind::Method(ref sig, ref body) => {
3323 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3324 let impl_trait_return_allow = !self.is_in_trait_impl;
3325 let (generics, sig) = self.lower_method_sig(
3329 impl_trait_return_allow,
3330 sig.header.asyncness.opt_return_id(),
3332 (generics, hir::ImplItemKind::Method(sig, body_id))
3334 ImplItemKind::Type(ref ty) => (
3335 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3336 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3338 ImplItemKind::Existential(ref bounds) => (
3339 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3340 hir::ImplItemKind::Existential(
3341 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3344 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3351 attrs: self.lower_attrs(&i.attrs),
3353 vis: self.lower_visibility(&i.vis, None),
3354 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3359 // [1] since `default impl` is not yet implemented, this is always true in impls
3362 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3364 id: hir::ImplItemId { node_id: i.id },
3367 vis: self.lower_visibility(&i.vis, Some(i.id)),
3368 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3369 kind: match i.node {
3370 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3371 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3372 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3373 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3374 has_self: sig.decl.has_self(),
3376 ImplItemKind::Macro(..) => unimplemented!(),
3380 // [1] since `default impl` is not yet implemented, this is always true in impls
3383 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3386 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3390 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3392 ItemKind::Use(ref use_tree) => {
3393 let mut vec = smallvec![hir::ItemId { id: i.id }];
3394 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3397 ItemKind::MacroDef(..) => SmallVec::new(),
3399 ItemKind::Impl(.., None, _, _) => smallvec![hir::ItemId { id: i.id }],
3400 ItemKind::Static(ref ty, ..) => {
3401 let mut ids = smallvec![hir::ItemId { id: i.id }];
3402 if self.sess.features_untracked().impl_trait_in_bindings {
3403 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3404 visitor.visit_ty(ty);
3408 ItemKind::Const(ref ty, ..) => {
3409 let mut ids = smallvec![hir::ItemId { id: i.id }];
3410 if self.sess.features_untracked().impl_trait_in_bindings {
3411 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3412 visitor.visit_ty(ty);
3416 _ => smallvec![hir::ItemId { id: i.id }],
3420 fn lower_item_id_use_tree(&mut self,
3423 vec: &mut SmallVec<[hir::ItemId; 1]>)
3426 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3427 vec.push(hir::ItemId { id });
3428 self.lower_item_id_use_tree(nested, id, vec);
3430 UseTreeKind::Glob => {}
3431 UseTreeKind::Simple(_, id1, id2) => {
3432 for (_, &id) in self.expect_full_def_from_use(base_id)
3434 .zip([id1, id2].iter())
3436 vec.push(hir::ItemId { id });
3442 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3443 let mut ident = i.ident;
3444 let mut vis = self.lower_visibility(&i.vis, None);
3445 let attrs = self.lower_attrs(&i.attrs);
3446 if let ItemKind::MacroDef(ref def) = i.node {
3447 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3448 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3449 let body = self.lower_token_stream(def.stream());
3450 self.exported_macros.push(hir::MacroDef {
3463 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
3465 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3478 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3479 let node_id = self.lower_node_id(i.id).node_id;
3480 let def_id = self.resolver.definitions().local_def_id(node_id);
3484 attrs: self.lower_attrs(&i.attrs),
3485 node: match i.node {
3486 ForeignItemKind::Fn(ref fdec, ref generics) => {
3487 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3490 AnonymousLifetimeMode::PassThrough,
3493 // Disallow impl Trait in foreign items
3494 this.lower_fn_decl(fdec, None, false, None),
3495 this.lower_fn_args_to_names(fdec),
3500 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3502 ForeignItemKind::Static(ref t, m) => {
3503 hir::ForeignItemKind::Static(
3504 self.lower_ty(t, ImplTraitContext::disallowed()), m)
3506 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3507 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3509 vis: self.lower_visibility(&i.vis, None),
3514 fn lower_method_sig(
3516 generics: &Generics,
3519 impl_trait_return_allow: bool,
3520 is_async: Option<NodeId>,
3521 ) -> (hir::Generics, hir::MethodSig) {
3522 let header = self.lower_fn_header(sig.header);
3523 let (generics, decl) = self.add_in_band_defs(
3526 AnonymousLifetimeMode::PassThrough,
3527 |this, idty| this.lower_fn_decl(
3529 Some((fn_def_id, idty)),
3530 impl_trait_return_allow,
3534 (generics, hir::MethodSig { header, decl })
3537 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3539 IsAuto::Yes => hir::IsAuto::Yes,
3540 IsAuto::No => hir::IsAuto::No,
3544 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3546 unsafety: self.lower_unsafety(h.unsafety),
3547 asyncness: self.lower_asyncness(h.asyncness),
3548 constness: self.lower_constness(h.constness),
3553 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3555 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3556 Unsafety::Normal => hir::Unsafety::Normal,
3560 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3562 Constness::Const => hir::Constness::Const,
3563 Constness::NotConst => hir::Constness::NotConst,
3567 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3569 IsAsync::Async { .. } => hir::IsAsync::Async,
3570 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3574 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3576 UnOp::Deref => hir::UnDeref,
3577 UnOp::Not => hir::UnNot,
3578 UnOp::Neg => hir::UnNeg,
3582 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3584 node: match b.node {
3585 BinOpKind::Add => hir::BinOpKind::Add,
3586 BinOpKind::Sub => hir::BinOpKind::Sub,
3587 BinOpKind::Mul => hir::BinOpKind::Mul,
3588 BinOpKind::Div => hir::BinOpKind::Div,
3589 BinOpKind::Rem => hir::BinOpKind::Rem,
3590 BinOpKind::And => hir::BinOpKind::And,
3591 BinOpKind::Or => hir::BinOpKind::Or,
3592 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3593 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3594 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3595 BinOpKind::Shl => hir::BinOpKind::Shl,
3596 BinOpKind::Shr => hir::BinOpKind::Shr,
3597 BinOpKind::Eq => hir::BinOpKind::Eq,
3598 BinOpKind::Lt => hir::BinOpKind::Lt,
3599 BinOpKind::Le => hir::BinOpKind::Le,
3600 BinOpKind::Ne => hir::BinOpKind::Ne,
3601 BinOpKind::Ge => hir::BinOpKind::Ge,
3602 BinOpKind::Gt => hir::BinOpKind::Gt,
3608 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3609 let node = match p.node {
3610 PatKind::Wild => hir::PatKind::Wild,
3611 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3612 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3613 // `None` can occur in body-less function signatures
3614 def @ None | def @ Some(Def::Local(_)) => {
3615 let canonical_id = match def {
3616 Some(Def::Local(id)) => id,
3619 hir::PatKind::Binding(
3620 self.lower_binding_mode(binding_mode),
3623 sub.as_ref().map(|x| self.lower_pat(x)),
3626 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3631 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3636 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3637 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3638 let qpath = self.lower_qpath(
3642 ParamMode::Optional,
3643 ImplTraitContext::disallowed(),
3645 hir::PatKind::TupleStruct(
3647 pats.iter().map(|x| self.lower_pat(x)).collect(),
3651 PatKind::Path(ref qself, ref path) => {
3652 let qpath = self.lower_qpath(
3656 ParamMode::Optional,
3657 ImplTraitContext::disallowed(),
3659 hir::PatKind::Path(qpath)
3661 PatKind::Struct(ref path, ref fields, etc) => {
3662 let qpath = self.lower_qpath(
3666 ParamMode::Optional,
3667 ImplTraitContext::disallowed(),
3674 node: hir::FieldPat {
3675 id: self.next_id().node_id,
3676 ident: f.node.ident,
3677 pat: self.lower_pat(&f.node.pat),
3678 is_shorthand: f.node.is_shorthand,
3682 hir::PatKind::Struct(qpath, fs, etc)
3684 PatKind::Tuple(ref elts, ddpos) => {
3685 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3687 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3688 PatKind::Ref(ref inner, mutbl) => {
3689 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3691 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3692 P(self.lower_expr(e1)),
3693 P(self.lower_expr(e2)),
3694 self.lower_range_end(end),
3696 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3697 before.iter().map(|x| self.lower_pat(x)).collect(),
3698 slice.as_ref().map(|x| self.lower_pat(x)),
3699 after.iter().map(|x| self.lower_pat(x)).collect(),
3701 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3702 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3705 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3714 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3716 RangeEnd::Included(_) => hir::RangeEnd::Included,
3717 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3721 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3722 self.with_new_scopes(|this| {
3723 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3727 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3732 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3733 let kind = match e.node {
3734 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3735 ExprKind::ObsoleteInPlace(..) => {
3736 self.sess.abort_if_errors();
3737 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3739 ExprKind::Array(ref exprs) => {
3740 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3742 ExprKind::Repeat(ref expr, ref count) => {
3743 let expr = P(self.lower_expr(expr));
3744 let count = self.lower_anon_const(count);
3745 hir::ExprKind::Repeat(expr, count)
3747 ExprKind::Tup(ref elts) => {
3748 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3750 ExprKind::Call(ref f, ref args) => {
3751 let f = P(self.lower_expr(f));
3752 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3754 ExprKind::MethodCall(ref seg, ref args) => {
3755 let hir_seg = self.lower_path_segment(
3758 ParamMode::Optional,
3760 ParenthesizedGenericArgs::Err,
3761 ImplTraitContext::disallowed(),
3764 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3765 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3767 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3768 let binop = self.lower_binop(binop);
3769 let lhs = P(self.lower_expr(lhs));
3770 let rhs = P(self.lower_expr(rhs));
3771 hir::ExprKind::Binary(binop, lhs, rhs)
3773 ExprKind::Unary(op, ref ohs) => {
3774 let op = self.lower_unop(op);
3775 let ohs = P(self.lower_expr(ohs));
3776 hir::ExprKind::Unary(op, ohs)
3778 ExprKind::Lit(ref l) => hir::ExprKind::Lit((*l).clone()),
3779 ExprKind::Cast(ref expr, ref ty) => {
3780 let expr = P(self.lower_expr(expr));
3781 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3783 ExprKind::Type(ref expr, ref ty) => {
3784 let expr = P(self.lower_expr(expr));
3785 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3787 ExprKind::AddrOf(m, ref ohs) => {
3788 let m = self.lower_mutability(m);
3789 let ohs = P(self.lower_expr(ohs));
3790 hir::ExprKind::AddrOf(m, ohs)
3792 // More complicated than you might expect because the else branch
3793 // might be `if let`.
3794 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3795 let else_opt = else_opt.as_ref().map(|els| {
3797 ExprKind::IfLet(..) => {
3798 // Wrap the `if let` expr in a block.
3799 let span = els.span;
3800 let els = P(self.lower_expr(els));
3801 let LoweredNodeId { node_id, hir_id } = self.next_id();
3802 let blk = P(hir::Block {
3807 rules: hir::DefaultBlock,
3809 targeted_by_break: false,
3811 P(self.expr_block(blk, ThinVec::new()))
3813 _ => P(self.lower_expr(els)),
3817 let then_blk = self.lower_block(blk, false);
3818 let then_expr = self.expr_block(then_blk, ThinVec::new());
3820 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3822 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3823 hir::ExprKind::While(
3824 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3825 this.lower_block(body, false),
3826 this.lower_label(opt_label),
3829 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3830 hir::ExprKind::Loop(
3831 this.lower_block(body, false),
3832 this.lower_label(opt_label),
3833 hir::LoopSource::Loop,
3836 ExprKind::TryBlock(ref body) => {
3837 self.with_catch_scope(body.id, |this| {
3839 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3840 let mut block = this.lower_block(body, true).into_inner();
3841 let tail = block.expr.take().map_or_else(
3843 let LoweredNodeId { node_id, hir_id } = this.next_id();
3844 let span = this.sess.source_map().end_point(unstable_span);
3848 node: hir::ExprKind::Tup(hir_vec![]),
3849 attrs: ThinVec::new(),
3853 |x: P<hir::Expr>| x.into_inner(),
3855 block.expr = Some(this.wrap_in_try_constructor(
3856 "from_ok", tail, unstable_span));
3857 hir::ExprKind::Block(P(block), None)
3860 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3861 P(self.lower_expr(expr)),
3862 arms.iter().map(|x| self.lower_arm(x)).collect(),
3863 hir::MatchSource::Normal,
3865 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3866 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3867 this.with_new_scopes(|this| {
3868 let block = this.lower_block(block, false);
3869 this.expr_block(block, ThinVec::new())
3874 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3876 if let IsAsync::Async { closure_id, .. } = asyncness {
3877 let outer_decl = FnDecl {
3878 inputs: decl.inputs.clone(),
3879 output: FunctionRetTy::Default(fn_decl_span),
3882 // We need to lower the declaration outside the new scope, because we
3883 // have to conserve the state of being inside a loop condition for the
3884 // closure argument types.
3885 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3887 self.with_new_scopes(|this| {
3888 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
3889 if capture_clause == CaptureBy::Ref &&
3890 !decl.inputs.is_empty()
3896 "`async` non-`move` closures with arguments \
3897 are not currently supported",
3899 .help("consider using `let` statements to manually capture \
3900 variables by reference before entering an \
3901 `async move` closure")
3905 // Transform `async |x: u8| -> X { ... }` into
3906 // `|x: u8| future_from_generator(|| -> X { ... })`.
3907 let body_id = this.lower_body(Some(&outer_decl), |this| {
3908 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3911 let async_body = this.make_async_expr(
3912 capture_clause, closure_id, async_ret_ty,
3914 this.with_new_scopes(|this| this.lower_expr(body))
3916 this.expr(fn_decl_span, async_body, ThinVec::new())
3918 hir::ExprKind::Closure(
3919 this.lower_capture_clause(capture_clause),
3927 // Lower outside new scope to preserve `is_in_loop_condition`.
3928 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3930 self.with_new_scopes(|this| {
3931 let mut is_generator = false;
3932 let body_id = this.lower_body(Some(decl), |this| {
3933 let e = this.lower_expr(body);
3934 is_generator = this.is_generator;
3937 let generator_option = if is_generator {
3938 if !decl.inputs.is_empty() {
3943 "generators cannot have explicit arguments"
3945 this.sess.abort_if_errors();
3947 Some(match movability {
3948 Movability::Movable => hir::GeneratorMovability::Movable,
3949 Movability::Static => hir::GeneratorMovability::Static,
3952 if movability == Movability::Static {
3957 "closures cannot be static"
3962 hir::ExprKind::Closure(
3963 this.lower_capture_clause(capture_clause),
3972 ExprKind::Block(ref blk, opt_label) => {
3973 hir::ExprKind::Block(self.lower_block(blk,
3974 opt_label.is_some()),
3975 self.lower_label(opt_label))
3977 ExprKind::Assign(ref el, ref er) => {
3978 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3980 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3981 self.lower_binop(op),
3982 P(self.lower_expr(el)),
3983 P(self.lower_expr(er)),
3985 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3986 ExprKind::Index(ref el, ref er) => {
3987 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3989 // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
3990 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3991 let id = self.next_id();
3992 let e1 = self.lower_expr(e1);
3993 let e2 = self.lower_expr(e2);
3994 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3995 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3996 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3997 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3998 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3999 hir::ExprKind::Call(new, hir_vec![e1, e2])
4001 ExprKind::Range(ref e1, ref e2, lims) => {
4002 use syntax::ast::RangeLimits::*;
4004 let path = match (e1, e2, lims) {
4005 (&None, &None, HalfOpen) => "RangeFull",
4006 (&Some(..), &None, HalfOpen) => "RangeFrom",
4007 (&None, &Some(..), HalfOpen) => "RangeTo",
4008 (&Some(..), &Some(..), HalfOpen) => "Range",
4009 (&None, &Some(..), Closed) => "RangeToInclusive",
4010 (&Some(..), &Some(..), Closed) => unreachable!(),
4011 (_, &None, Closed) => self.diagnostic()
4012 .span_fatal(e.span, "inclusive range with no end")
4016 let fields = e1.iter()
4017 .map(|e| ("start", e))
4018 .chain(e2.iter().map(|e| ("end", e)))
4020 let expr = P(self.lower_expr(&e));
4021 let ident = Ident::new(Symbol::intern(s), e.span);
4022 self.field(ident, expr, e.span)
4024 .collect::<P<[hir::Field]>>();
4026 let is_unit = fields.is_empty();
4027 let struct_path = ["ops", path];
4028 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4029 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4031 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4037 hir::ExprKind::Path(struct_path)
4039 hir::ExprKind::Struct(struct_path, fields, None)
4042 attrs: e.attrs.clone(),
4045 ExprKind::Path(ref qself, ref path) => {
4046 let qpath = self.lower_qpath(
4050 ParamMode::Optional,
4051 ImplTraitContext::disallowed(),
4053 hir::ExprKind::Path(qpath)
4055 ExprKind::Break(opt_label, ref opt_expr) => {
4056 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4059 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4062 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4064 hir::ExprKind::Break(
4066 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4069 ExprKind::Continue(opt_label) => {
4070 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4073 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4076 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4079 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4080 ExprKind::InlineAsm(ref asm) => {
4081 let hir_asm = hir::InlineAsm {
4082 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4083 outputs: asm.outputs
4085 .map(|out| hir::InlineAsmOutput {
4086 constraint: out.constraint.clone(),
4088 is_indirect: out.is_indirect,
4089 span: out.expr.span,
4092 asm: asm.asm.clone(),
4093 asm_str_style: asm.asm_str_style,
4094 clobbers: asm.clobbers.clone().into(),
4095 volatile: asm.volatile,
4096 alignstack: asm.alignstack,
4097 dialect: asm.dialect,
4100 let outputs = asm.outputs
4102 .map(|out| self.lower_expr(&out.expr))
4104 let inputs = asm.inputs
4106 .map(|&(_, ref input)| self.lower_expr(input))
4108 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4110 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4115 ParamMode::Optional,
4116 ImplTraitContext::disallowed(),
4118 fields.iter().map(|x| self.lower_field(x)).collect(),
4119 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4121 ExprKind::Paren(ref ex) => {
4122 let mut ex = self.lower_expr(ex);
4123 // Include parens in span, but only if it is a super-span.
4124 if e.span.contains(ex.span) {
4127 // Merge attributes into the inner expression.
4128 let mut attrs = e.attrs.clone();
4129 attrs.extend::<Vec<_>>(ex.attrs.into());
4134 ExprKind::Yield(ref opt_expr) => {
4135 self.is_generator = true;
4138 .map(|x| self.lower_expr(x))
4140 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
4142 hir::ExprKind::Yield(P(expr))
4145 ExprKind::Err => hir::ExprKind::Err,
4147 // Desugar `ExprIfLet`
4148 // from: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4149 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4152 // match <sub_expr> {
4154 // _ => [<else_opt> | ()]
4157 let mut arms = vec![];
4159 // `<pat> => <body>`
4161 let body = self.lower_block(body, false);
4162 let body_expr = P(self.expr_block(body, ThinVec::new()));
4163 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4164 arms.push(self.arm(pats, body_expr));
4167 // _ => [<else_opt>|()]
4169 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4170 let wildcard_pattern = self.pat_wild(e.span);
4171 let body = if let Some(else_expr) = wildcard_arm {
4172 P(self.lower_expr(else_expr))
4174 self.expr_tuple(e.span, hir_vec![])
4176 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4179 let contains_else_clause = else_opt.is_some();
4181 let sub_expr = P(self.lower_expr(sub_expr));
4183 hir::ExprKind::Match(
4186 hir::MatchSource::IfLetDesugar {
4187 contains_else_clause,
4192 // Desugar `ExprWhileLet`
4193 // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4194 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4197 // [opt_ident]: loop {
4198 // match <sub_expr> {
4204 // Note that the block AND the condition are evaluated in the loop scope.
4205 // This is done to allow `break` from inside the condition of the loop.
4206 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4208 this.lower_block(body, false),
4209 this.expr_break(e.span, ThinVec::new()),
4210 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4214 // `<pat> => <body>`
4216 let body_expr = P(self.expr_block(body, ThinVec::new()));
4217 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4218 self.arm(pats, body_expr)
4223 let pat_under = self.pat_wild(e.span);
4224 self.arm(hir_vec![pat_under], break_expr)
4227 // `match <sub_expr> { ... }`
4228 let arms = hir_vec![pat_arm, break_arm];
4229 let match_expr = self.expr(
4231 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4235 // `[opt_ident]: loop { ... }`
4236 let loop_block = P(self.block_expr(P(match_expr)));
4237 let loop_expr = hir::ExprKind::Loop(
4239 self.lower_label(opt_label),
4240 hir::LoopSource::WhileLet,
4242 // Add attributes to the outer returned expr node.
4246 // Desugar `ExprForLoop`
4247 // from: `[opt_ident]: for <pat> in <head> <body>`
4248 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4252 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4254 // [opt_ident]: loop {
4256 // match ::std::iter::Iterator::next(&mut iter) {
4257 // ::std::option::Option::Some(val) => __next = val,
4258 // ::std::option::Option::None => break
4260 // let <pat> = __next;
4261 // StmtKind::Expr(<body>);
4269 let head = self.lower_expr(head);
4270 let head_sp = head.span;
4271 let desugared_span = self.allow_internal_unstable(
4272 CompilerDesugaringKind::ForLoop,
4276 let iter = self.str_to_ident("iter");
4278 let next_ident = self.str_to_ident("__next");
4279 let next_pat = self.pat_ident_binding_mode(
4282 hir::BindingAnnotation::Mutable,
4285 // `::std::option::Option::Some(val) => next = val`
4287 let val_ident = self.str_to_ident("val");
4288 let val_pat = self.pat_ident(pat.span, val_ident);
4289 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4290 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4291 let assign = P(self.expr(
4293 hir::ExprKind::Assign(next_expr, val_expr),
4296 let some_pat = self.pat_some(pat.span, val_pat);
4297 self.arm(hir_vec![some_pat], assign)
4300 // `::std::option::Option::None => break`
4303 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4304 let pat = self.pat_none(e.span);
4305 self.arm(hir_vec![pat], break_expr)
4309 let iter_pat = self.pat_ident_binding_mode(
4312 hir::BindingAnnotation::Mutable
4315 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4317 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4318 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4319 let next_path = &["iter", "Iterator", "next"];
4320 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4321 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4322 let arms = hir_vec![pat_arm, break_arm];
4326 hir::ExprKind::Match(
4329 hir::MatchSource::ForLoopDesugar
4334 let match_stmt = hir::Stmt {
4335 id: self.next_id().node_id,
4336 node: hir::StmtKind::Expr(match_expr),
4340 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4343 let next_let = self.stmt_let_pat(
4347 hir::LocalSource::ForLoopDesugar,
4350 // `let <pat> = __next`
4351 let pat = self.lower_pat(pat);
4352 let pat_let = self.stmt_let_pat(
4356 hir::LocalSource::ForLoopDesugar,
4359 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4360 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4361 let body_stmt = hir::Stmt {
4362 id: self.next_id().node_id,
4363 node: hir::StmtKind::Expr(body_expr),
4367 let loop_block = P(self.block_all(
4369 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4373 // `[opt_ident]: loop { ... }`
4374 let loop_expr = hir::ExprKind::Loop(
4376 self.lower_label(opt_label),
4377 hir::LoopSource::ForLoop,
4379 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4380 let loop_expr = P(hir::Expr {
4385 attrs: ThinVec::new(),
4388 // `mut iter => { ... }`
4389 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4391 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4392 let into_iter_expr = {
4393 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4394 let into_iter = P(self.expr_std_path(
4395 head_sp, into_iter_path, None, ThinVec::new()));
4396 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4399 let match_expr = P(self.expr_match(
4403 hir::MatchSource::ForLoopDesugar,
4406 // `{ let _result = ...; _result }`
4407 // Underscore prevents an `unused_variables` lint if the head diverges.
4408 let result_ident = self.str_to_ident("_result");
4409 let (let_stmt, let_stmt_binding) =
4410 self.stmt_let(e.span, false, result_ident, match_expr);
4412 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4413 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4414 // Add the attributes to the outer returned expr node.
4415 return self.expr_block(block, e.attrs.clone());
4418 // Desugar `ExprKind::Try`
4420 ExprKind::Try(ref sub_expr) => {
4423 // match Try::into_result(<expr>) {
4424 // Ok(val) => #[allow(unreachable_code)] val,
4425 // Err(err) => #[allow(unreachable_code)]
4426 // // If there is an enclosing `catch {...}`
4427 // break 'catch_target Try::from_error(From::from(err)),
4429 // return Try::from_error(From::from(err)),
4433 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4435 // `Try::into_result(<expr>)`
4438 let sub_expr = self.lower_expr(sub_expr);
4440 let path = &["ops", "Try", "into_result"];
4441 let path = P(self.expr_std_path(
4442 unstable_span, path, None, ThinVec::new()));
4443 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4446 // `#[allow(unreachable_code)]`
4448 // `allow(unreachable_code)`
4450 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4451 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4452 let uc_nested = attr::mk_nested_word_item(uc_ident);
4453 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4455 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4457 let attrs = vec![attr];
4459 // `Ok(val) => #[allow(unreachable_code)] val,`
4461 let val_ident = self.str_to_ident("val");
4462 let val_pat = self.pat_ident(e.span, val_ident);
4463 let val_expr = P(self.expr_ident_with_attrs(
4467 ThinVec::from(attrs.clone()),
4469 let ok_pat = self.pat_ok(e.span, val_pat);
4471 self.arm(hir_vec![ok_pat], val_expr)
4474 // `Err(err) => #[allow(unreachable_code)]
4475 // return Try::from_error(From::from(err)),`
4477 let err_ident = self.str_to_ident("err");
4478 let err_local = self.pat_ident(e.span, err_ident);
4480 let path = &["convert", "From", "from"];
4481 let from = P(self.expr_std_path(
4482 e.span, path, None, ThinVec::new()));
4483 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4485 self.expr_call(e.span, from, hir_vec![err_expr])
4488 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4489 let thin_attrs = ThinVec::from(attrs);
4490 let catch_scope = self.catch_scopes.last().map(|x| *x);
4491 let ret_expr = if let Some(catch_node) = catch_scope {
4494 hir::ExprKind::Break(
4497 target_id: Ok(catch_node),
4499 Some(from_err_expr),
4504 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4507 let err_pat = self.pat_err(e.span, err_local);
4508 self.arm(hir_vec![err_pat], ret_expr)
4511 hir::ExprKind::Match(
4513 hir_vec![err_arm, ok_arm],
4514 hir::MatchSource::TryDesugar,
4518 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4521 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4528 attrs: e.attrs.clone(),
4532 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4533 smallvec![match s.node {
4534 StmtKind::Local(ref l) => {
4535 let (l, item_ids) = self.lower_local(l);
4536 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4538 .map(|item_id| hir::Stmt {
4539 id: self.next_id().node_id,
4540 node: hir::StmtKind::Item(P(item_id)),
4544 ids.push(hir::Stmt {
4545 id: self.lower_node_id(s.id).node_id,
4546 node: hir::StmtKind::Local(P(l)),
4551 StmtKind::Item(ref it) => {
4552 // Can only use the ID once.
4553 let mut id = Some(s.id);
4554 return self.lower_item_id(it)
4556 .map(|item_id| hir::Stmt {
4558 .map(|id| self.lower_node_id(id).node_id)
4559 .unwrap_or_else(|| self.next_id().node_id),
4560 node: hir::StmtKind::Item(P(item_id)),
4565 StmtKind::Expr(ref e) => hir::Stmt {
4566 id: self.lower_node_id(s.id).node_id,
4567 node: hir::StmtKind::Expr(P(self.lower_expr(e))),
4570 StmtKind::Semi(ref e) => hir::Stmt {
4571 id: self.lower_node_id(s.id).node_id,
4572 node: hir::StmtKind::Semi(P(self.lower_expr(e))),
4575 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4579 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4581 CaptureBy::Value => hir::CaptureByValue,
4582 CaptureBy::Ref => hir::CaptureByRef,
4586 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4587 /// the address space of that item instead of the item currently being
4588 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4589 /// lower a `Visibility` value although we haven't lowered the owning
4590 /// `ImplItem` in question yet.
4591 fn lower_visibility(
4594 explicit_owner: Option<NodeId>,
4595 ) -> hir::Visibility {
4596 let node = match v.node {
4597 VisibilityKind::Public => hir::VisibilityKind::Public,
4598 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4599 VisibilityKind::Restricted { ref path, id } => {
4600 debug!("lower_visibility: restricted path id = {:?}", id);
4601 let lowered_id = if let Some(owner) = explicit_owner {
4602 self.lower_node_id_with_owner(id, owner)
4604 self.lower_node_id(id)
4606 let def = self.expect_full_def(id);
4607 hir::VisibilityKind::Restricted {
4608 path: P(self.lower_path_extra(
4611 ParamMode::Explicit,
4614 id: lowered_id.node_id,
4615 hir_id: lowered_id.hir_id,
4618 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4620 respan(v.span, node)
4623 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4625 Defaultness::Default => hir::Defaultness::Default {
4626 has_value: has_value,
4628 Defaultness::Final => {
4630 hir::Defaultness::Final
4635 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4637 BlockCheckMode::Default => hir::DefaultBlock,
4638 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4642 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4644 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4645 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4646 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4647 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4651 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4653 CompilerGenerated => hir::CompilerGenerated,
4654 UserProvided => hir::UserProvided,
4658 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4660 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4661 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4665 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4667 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4668 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4672 // Helper methods for building HIR.
4674 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4683 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4685 id: self.next_id().node_id,
4689 is_shorthand: false,
4693 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4694 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4695 P(self.expr(span, expr_break, attrs))
4702 args: hir::HirVec<hir::Expr>,
4704 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4707 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4708 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4711 fn expr_ident_with_attrs(
4716 attrs: ThinVec<Attribute>,
4718 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4722 def: Def::Local(binding),
4723 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4727 self.expr(span, expr_path, attrs)
4730 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4731 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4737 components: &[&str],
4738 params: Option<P<hir::GenericArgs>>,
4739 attrs: ThinVec<Attribute>,
4741 let path = self.std_path(span, components, params, true);
4744 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4753 arms: hir::HirVec<hir::Arm>,
4754 source: hir::MatchSource,
4756 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4759 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4760 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4763 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4764 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4767 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4768 let LoweredNodeId { node_id, hir_id } = self.next_id();
4781 ex: Option<P<hir::Expr>>,
4783 source: hir::LocalSource,
4785 let LoweredNodeId { node_id, hir_id } = self.next_id();
4787 let local = hir::Local {
4794 attrs: ThinVec::new(),
4798 id: self.next_id().node_id,
4799 node: hir::StmtKind::Local(P(local)),
4810 ) -> (hir::Stmt, NodeId) {
4811 let pat = if mutbl {
4812 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4814 self.pat_ident(sp, ident)
4816 let pat_id = pat.id;
4818 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4823 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4824 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4830 stmts: hir::HirVec<hir::Stmt>,
4831 expr: Option<P<hir::Expr>>,
4833 let LoweredNodeId { node_id, hir_id } = self.next_id();
4840 rules: hir::DefaultBlock,
4842 targeted_by_break: false,
4846 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4847 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4850 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4851 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4854 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4855 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4858 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4859 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4865 components: &[&str],
4866 subpats: hir::HirVec<P<hir::Pat>>,
4868 let path = self.std_path(span, components, None, true);
4869 let qpath = hir::QPath::Resolved(None, P(path));
4870 let pt = if subpats.is_empty() {
4871 hir::PatKind::Path(qpath)
4873 hir::PatKind::TupleStruct(qpath, subpats, None)
4878 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4879 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4882 fn pat_ident_binding_mode(
4886 bm: hir::BindingAnnotation,
4888 let LoweredNodeId { node_id, hir_id } = self.next_id();
4893 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4898 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4899 self.pat(span, hir::PatKind::Wild)
4902 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4903 let LoweredNodeId { node_id, hir_id } = self.next_id();
4912 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4913 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4914 /// The path is also resolved according to `is_value`.
4918 components: &[&str],
4919 params: Option<P<hir::GenericArgs>>,
4922 let mut path = self.resolver
4923 .resolve_str_path(span, self.crate_root, components, is_value);
4924 path.segments.last_mut().unwrap().args = params;
4927 for seg in path.segments.iter_mut() {
4928 if let Some(id) = seg.id {
4929 seg.id = Some(self.lower_node_id(id).node_id);
4935 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4937 let node = match qpath {
4938 hir::QPath::Resolved(None, path) => {
4939 // Turn trait object paths into `TyKind::TraitObject` instead.
4941 Def::Trait(_) | Def::TraitAlias(_) => {
4942 let principal = hir::PolyTraitRef {
4943 bound_generic_params: hir::HirVec::new(),
4944 trait_ref: hir::TraitRef {
4945 path: path.and_then(|path| path),
4947 hir_ref_id: id.hir_id,
4952 // The original ID is taken by the `PolyTraitRef`,
4953 // so the `Ty` itself needs a different one.
4954 id = self.next_id();
4955 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4957 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
4960 _ => hir::TyKind::Path(qpath),
4970 /// Invoked to create the lifetime argument for a type `&T`
4971 /// with no explicit lifetime.
4972 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4973 match self.anonymous_lifetime_mode {
4974 // Intercept when we are in an impl header and introduce an in-band lifetime.
4975 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4977 AnonymousLifetimeMode::CreateParameter => {
4978 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4980 id: self.next_id().node_id,
4982 name: hir::LifetimeName::Param(fresh_name),
4986 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
4988 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4992 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
4993 /// return a "error lifetime".
4994 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
4995 let (id, msg, label) = match id {
4996 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
4999 self.next_id().node_id,
5000 "`&` without an explicit lifetime name cannot be used here",
5001 "explicit lifetime name needed here",
5005 let mut err = struct_span_err!(
5012 err.span_label(span, label);
5015 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5018 /// Invoked to create the lifetime argument(s) for a path like
5019 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5020 /// sorts of cases are deprecated. This may therefore report a warning or an
5021 /// error, depending on the mode.
5022 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5023 match self.anonymous_lifetime_mode {
5024 // N.B., We intentionally ignore the create-parameter mode here
5025 // and instead "pass through" to resolve-lifetimes, which will then
5026 // report an error. This is because we don't want to support
5027 // impl elision for deprecated forms like
5029 // impl Foo for std::cell::Ref<u32> // note lack of '_
5030 AnonymousLifetimeMode::CreateParameter => {}
5032 AnonymousLifetimeMode::ReportError => {
5034 .map(|_| self.new_error_lifetime(None, span))
5038 // This is the normal case.
5039 AnonymousLifetimeMode::PassThrough => {}
5043 .map(|_| self.new_implicit_lifetime(span))
5047 /// Invoked to create the lifetime argument(s) for an elided trait object
5048 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5049 /// when the bound is written, even if it is written with `'_` like in
5050 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5051 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5052 match self.anonymous_lifetime_mode {
5053 // NB. We intentionally ignore the create-parameter mode here.
5054 // and instead "pass through" to resolve-lifetimes, which will apply
5055 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5056 // do not act like other elided lifetimes. In other words, given this:
5058 // impl Foo for Box<dyn Debug>
5060 // we do not introduce a fresh `'_` to serve as the bound, but instead
5061 // ultimately translate to the equivalent of:
5063 // impl Foo for Box<dyn Debug + 'static>
5065 // `resolve_lifetime` has the code to make that happen.
5066 AnonymousLifetimeMode::CreateParameter => {}
5068 AnonymousLifetimeMode::ReportError => {
5069 // ReportError applies to explicit use of `'_`.
5072 // This is the normal case.
5073 AnonymousLifetimeMode::PassThrough => {}
5076 self.new_implicit_lifetime(span)
5079 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5081 id: self.next_id().node_id,
5083 name: hir::LifetimeName::Implicit,
5087 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5088 self.sess.buffer_lint_with_diagnostic(
5089 builtin::BARE_TRAIT_OBJECTS,
5092 "trait objects without an explicit `dyn` are deprecated",
5093 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5097 fn wrap_in_try_constructor(
5099 method: &'static str,
5101 unstable_span: Span,
5103 let path = &["ops", "Try", method];
5104 let from_err = P(self.expr_std_path(unstable_span, path, None,
5106 P(self.expr_call(e.span, from_err, hir_vec![e]))
5110 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5111 // Sorting by span ensures that we get things in order within a
5112 // file, and also puts the files in a sensible order.
5113 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5114 body_ids.sort_by_key(|b| bodies[b].value.span);