1 // ignore-tidy-filelength
3 //! Lowers the AST to the HIR.
5 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
6 //! much like a fold. Where lowering involves a bit more work things get more
7 //! interesting and there are some invariants you should know about. These mostly
8 //! concern spans and IDs.
10 //! Spans are assigned to AST nodes during parsing and then are modified during
11 //! expansion to indicate the origin of a node and the process it went through
12 //! being expanded. IDs are assigned to AST nodes just before lowering.
14 //! For the simpler lowering steps, IDs and spans should be preserved. Unlike
15 //! expansion we do not preserve the process of lowering in the spans, so spans
16 //! should not be modified here. When creating a new node (as opposed to
17 //! 'folding' an existing one), then you create a new ID using `next_id()`.
19 //! You must ensure that IDs are unique. That means that you should only use the
20 //! ID from an AST node in a single HIR node (you can assume that AST node-IDs
21 //! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
22 //! If you do, you must then set the new node's ID to a fresh one.
24 //! Spans are used for error messages and for tools to map semantics back to
25 //! source code. It is therefore not as important with spans as IDs to be strict
26 //! about use (you can't break the compiler by screwing up a span). Obviously, a
27 //! HIR node can only have a single span. But multiple nodes can have the same
28 //! span and spans don't need to be kept in order, etc. Where code is preserved
29 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
30 //! new it is probably best to give a span for the whole AST node being lowered.
31 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
32 //! get confused if the spans from leaf AST nodes occur in multiple places
33 //! in the HIR, especially for multiple identifiers.
38 use crate::arena::Arena;
39 use crate::dep_graph::DepGraph;
40 use crate::hir::{self, ParamName};
41 use crate::hir::HirVec;
42 use crate::hir::map::{DefKey, DefPathData, Definitions};
43 use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
44 use crate::hir::def::{Namespace, Res, DefKind, PartialRes, PerNS};
45 use crate::hir::{GenericArg, ConstArg};
46 use crate::hir::ptr::P;
48 use crate::lint::builtin::{self, ELIDED_LIFETIMES_IN_PATHS};
49 use crate::middle::cstore::CrateStore;
50 use crate::session::Session;
51 use crate::session::config::nightly_options;
52 use crate::util::common::FN_OUTPUT_NAME;
53 use crate::util::nodemap::{DefIdMap, NodeMap};
54 use errors::Applicability;
55 use rustc_data_structures::fx::FxHashSet;
56 use rustc_index::vec::IndexVec;
57 use rustc_data_structures::sync::Lrc;
59 use std::collections::BTreeMap;
61 use smallvec::SmallVec;
64 use syntax::ptr::P as AstP;
67 use syntax::print::pprust;
68 use syntax::token::{self, Nonterminal, Token};
69 use syntax::tokenstream::{TokenStream, TokenTree};
70 use syntax::sess::ParseSess;
71 use syntax::source_map::{respan, ExpnData, ExpnKind, DesugaringKind, Spanned};
72 use syntax::symbol::{kw, sym, Symbol};
73 use syntax::visit::{self, Visitor};
74 use syntax_pos::hygiene::ExpnId;
77 use rustc_error_codes::*;
79 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
81 pub struct LoweringContext<'a, 'hir: 'a> {
82 crate_root: Option<Symbol>,
84 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
87 resolver: &'a mut dyn Resolver,
89 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
90 /// if we don't have this function pointer. To avoid that dependency so that
91 /// librustc is independent of the parser, we use dynamic dispatch here.
92 nt_to_tokenstream: NtToTokenstream,
94 /// Used to allocate HIR nodes
95 arena: &'hir Arena<'hir>,
97 /// The items being lowered are collected here.
98 items: BTreeMap<hir::HirId, hir::Item<'hir>>,
100 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem<'hir>>,
101 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem<'hir>>,
102 bodies: BTreeMap<hir::BodyId, hir::Body<'hir>>,
103 exported_macros: Vec<hir::MacroDef<'hir>>,
104 non_exported_macro_attrs: Vec<ast::Attribute>,
106 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
108 modules: BTreeMap<hir::HirId, hir::ModuleItems>,
110 generator_kind: Option<hir::GeneratorKind>,
112 /// Used to get the current `fn`'s def span to point to when using `await`
113 /// outside of an `async fn`.
114 current_item: Option<Span>,
116 catch_scopes: Vec<NodeId>,
117 loop_scopes: Vec<NodeId>,
118 is_in_loop_condition: bool,
119 is_in_trait_impl: bool,
120 is_in_dyn_type: bool,
122 /// What to do when we encounter either an "anonymous lifetime
123 /// reference". The term "anonymous" is meant to encompass both
124 /// `'_` lifetimes as well as fully elided cases where nothing is
125 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
126 anonymous_lifetime_mode: AnonymousLifetimeMode,
128 /// Used to create lifetime definitions from in-band lifetime usages.
129 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
130 /// When a named lifetime is encountered in a function or impl header and
131 /// has not been defined
132 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
133 /// to this list. The results of this list are then added to the list of
134 /// lifetime definitions in the corresponding impl or function generics.
135 lifetimes_to_define: Vec<(Span, ParamName)>,
137 /// `true` if in-band lifetimes are being collected. This is used to
138 /// indicate whether or not we're in a place where new lifetimes will result
139 /// in in-band lifetime definitions, such a function or an impl header,
140 /// including implicit lifetimes from `impl_header_lifetime_elision`.
141 is_collecting_in_band_lifetimes: bool,
143 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
144 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
145 /// against this list to see if it is already in-scope, or if a definition
146 /// needs to be created for it.
148 /// We always store a `modern()` version of the param-name in this
150 in_scope_lifetimes: Vec<ParamName>,
152 current_module: hir::HirId,
154 type_def_lifetime_params: DefIdMap<usize>,
156 current_hir_id_owner: Vec<(DefIndex, u32)>,
157 item_local_id_counters: NodeMap<u32>,
158 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
160 allow_try_trait: Option<Lrc<[Symbol]>>,
161 allow_gen_future: Option<Lrc<[Symbol]>>,
165 fn cstore(&self) -> &dyn CrateStore;
167 /// Obtains resolution for a `NodeId` with a single resolution.
168 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
170 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
171 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
173 /// Obtains resolution for a label with the given `NodeId`.
174 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
176 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
177 /// This should only return `None` during testing.
178 fn definitions(&mut self) -> &mut Definitions;
180 /// Given suffix `["b", "c", "d"]`, creates an AST path for `[::crate_root]::b::c::d` and
181 /// resolves it based on `is_value`.
185 crate_root: Option<Symbol>,
186 components: &[Symbol],
188 ) -> (ast::Path, Res<NodeId>);
190 fn lint_buffer(&mut self) -> &mut lint::LintBuffer;
192 fn next_node_id(&mut self) -> NodeId;
195 type NtToTokenstream = fn(&Nonterminal, &ParseSess, Span) -> TokenStream;
197 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
198 /// and if so, what meaning it has.
200 enum ImplTraitContext<'a> {
201 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
202 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
203 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
205 /// Newly generated parameters should be inserted into the given `Vec`.
206 Universal(&'a mut Vec<hir::GenericParam>),
208 /// Treat `impl Trait` as shorthand for a new opaque type.
209 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
210 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
212 /// We optionally store a `DefId` for the parent item here so we can look up necessary
213 /// information later. It is `None` when no information about the context should be stored
214 /// (e.g., for consts and statics).
215 OpaqueTy(Option<DefId> /* fn def-ID */),
217 /// `impl Trait` is not accepted in this position.
218 Disallowed(ImplTraitPosition),
221 /// Position in which `impl Trait` is disallowed.
222 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
223 enum ImplTraitPosition {
224 /// Disallowed in `let` / `const` / `static` bindings.
227 /// All other posiitons.
231 impl<'a> ImplTraitContext<'a> {
233 fn disallowed() -> Self {
234 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
237 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
238 use self::ImplTraitContext::*;
240 Universal(params) => Universal(params),
241 OpaqueTy(fn_def_id) => OpaqueTy(*fn_def_id),
242 Disallowed(pos) => Disallowed(*pos),
247 pub fn lower_crate<'a, 'hir>(
249 dep_graph: &'a DepGraph,
251 resolver: &'a mut dyn Resolver,
252 nt_to_tokenstream: NtToTokenstream,
253 arena: &'hir Arena<'hir>,
254 ) -> hir::Crate<'hir> {
255 // We're constructing the HIR here; we don't care what we will
256 // read, since we haven't even constructed the *input* to
258 dep_graph.assert_ignored();
260 let _prof_timer = sess.prof.generic_activity("hir_lowering");
263 crate_root: sess.parse_sess.injected_crate_name.try_get().copied(),
268 items: BTreeMap::new(),
269 trait_items: BTreeMap::new(),
270 impl_items: BTreeMap::new(),
271 bodies: BTreeMap::new(),
272 trait_impls: BTreeMap::new(),
273 modules: BTreeMap::new(),
274 exported_macros: Vec::new(),
275 non_exported_macro_attrs: Vec::new(),
276 catch_scopes: Vec::new(),
277 loop_scopes: Vec::new(),
278 is_in_loop_condition: false,
279 is_in_trait_impl: false,
280 is_in_dyn_type: false,
281 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
282 type_def_lifetime_params: Default::default(),
283 current_module: hir::CRATE_HIR_ID,
284 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
285 item_local_id_counters: Default::default(),
286 node_id_to_hir_id: IndexVec::new(),
287 generator_kind: None,
289 lifetimes_to_define: Vec::new(),
290 is_collecting_in_band_lifetimes: false,
291 in_scope_lifetimes: Vec::new(),
292 allow_try_trait: Some([sym::try_trait][..].into()),
293 allow_gen_future: Some([sym::gen_future][..].into()),
297 #[derive(Copy, Clone, PartialEq)]
299 /// Any path in a type context.
301 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
303 /// The `module::Type` in `module::Type::method` in an expression.
307 enum ParenthesizedGenericArgs {
312 /// What to do when we encounter an **anonymous** lifetime
313 /// reference. Anonymous lifetime references come in two flavors. You
314 /// have implicit, or fully elided, references to lifetimes, like the
315 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
316 /// or `Ref<'_, T>`. These often behave the same, but not always:
318 /// - certain usages of implicit references are deprecated, like
319 /// `Ref<T>`, and we sometimes just give hard errors in those cases
321 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
322 /// the same as `Box<dyn Foo + '_>`.
324 /// We describe the effects of the various modes in terms of three cases:
326 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
327 /// of a `&` (e.g., the missing lifetime in something like `&T`)
328 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
329 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
330 /// elided bounds follow special rules. Note that this only covers
331 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
332 /// '_>` is a case of "modern" elision.
333 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
334 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
335 /// non-deprecated equivalent.
337 /// Currently, the handling of lifetime elision is somewhat spread out
338 /// between HIR lowering and -- as described below -- the
339 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
340 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
341 /// everything into HIR lowering.
342 #[derive(Copy, Clone, Debug)]
343 enum AnonymousLifetimeMode {
344 /// For **Modern** cases, create a new anonymous region parameter
345 /// and reference that.
347 /// For **Dyn Bound** cases, pass responsibility to
348 /// `resolve_lifetime` code.
350 /// For **Deprecated** cases, report an error.
353 /// Give a hard error when either `&` or `'_` is written. Used to
354 /// rule out things like `where T: Foo<'_>`. Does not imply an
355 /// error on default object bounds (e.g., `Box<dyn Foo>`).
358 /// Pass responsibility to `resolve_lifetime` code for all cases.
362 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
364 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
365 fn visit_ty(&mut self, ty: &'a Ty) {
371 TyKind::ImplTrait(id, _) => self.ids.push(id),
374 visit::walk_ty(self, ty);
377 fn visit_path_segment(
380 path_segment: &'v PathSegment,
382 if let Some(ref p) = path_segment.args {
383 if let GenericArgs::Parenthesized(_) = **p {
387 visit::walk_path_segment(self, path_span, path_segment)
391 impl<'a, 'hir> LoweringContext<'a, 'hir> {
392 fn lower_crate(mut self, c: &Crate) -> hir::Crate<'hir> {
393 /// Full-crate AST visitor that inserts into a fresh
394 /// `LoweringContext` any information that may be
395 /// needed from arbitrary locations in the crate,
396 /// e.g., the number of lifetime generic parameters
397 /// declared for every type and trait definition.
398 struct MiscCollector<'tcx, 'lowering, 'hir> {
399 lctx: &'tcx mut LoweringContext<'lowering, 'hir>,
400 hir_id_owner: Option<NodeId>,
403 impl MiscCollector<'_, '_, '_> {
404 fn allocate_use_tree_hir_id_counters(
410 UseTreeKind::Simple(_, id1, id2) => {
411 for &id in &[id1, id2] {
412 self.lctx.resolver.definitions().create_def_with_parent(
419 self.lctx.allocate_hir_id_counter(id);
422 UseTreeKind::Glob => (),
423 UseTreeKind::Nested(ref trees) => {
424 for &(ref use_tree, id) in trees {
425 let hir_id = self.lctx.allocate_hir_id_counter(id);
426 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
432 fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
434 F: FnOnce(&mut Self) -> T,
436 let old = mem::replace(&mut self.hir_id_owner, owner);
438 self.hir_id_owner = old;
443 impl<'tcx, 'lowering, 'hir> Visitor<'tcx> for MiscCollector<'tcx, 'lowering, 'hir> {
444 fn visit_pat(&mut self, p: &'tcx Pat) {
445 if let PatKind::Paren(..) | PatKind::Rest = p.kind {
446 // Doesn't generate a HIR node
447 } else if let Some(owner) = self.hir_id_owner {
448 self.lctx.lower_node_id_with_owner(p.id, owner);
451 visit::walk_pat(self, p)
454 fn visit_item(&mut self, item: &'tcx Item) {
455 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
458 ItemKind::Struct(_, ref generics)
459 | ItemKind::Union(_, ref generics)
460 | ItemKind::Enum(_, ref generics)
461 | ItemKind::TyAlias(_, ref generics)
462 | ItemKind::Trait(_, _, ref generics, ..) => {
463 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
467 .filter(|param| match param.kind {
468 ast::GenericParamKind::Lifetime { .. } => true,
472 self.lctx.type_def_lifetime_params.insert(def_id, count);
474 ItemKind::Use(ref use_tree) => {
475 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
480 self.with_hir_id_owner(Some(item.id), |this| {
481 visit::walk_item(this, item);
485 fn visit_trait_item(&mut self, item: &'tcx AssocItem) {
486 self.lctx.allocate_hir_id_counter(item.id);
489 AssocItemKind::Fn(_, None) => {
490 // Ignore patterns in trait methods without bodies
491 self.with_hir_id_owner(None, |this| {
492 visit::walk_trait_item(this, item)
495 _ => self.with_hir_id_owner(Some(item.id), |this| {
496 visit::walk_trait_item(this, item);
501 fn visit_impl_item(&mut self, item: &'tcx AssocItem) {
502 self.lctx.allocate_hir_id_counter(item.id);
503 self.with_hir_id_owner(Some(item.id), |this| {
504 visit::walk_impl_item(this, item);
508 fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) {
509 // Ignore patterns in foreign items
510 self.with_hir_id_owner(None, |this| {
511 visit::walk_foreign_item(this, i)
515 fn visit_ty(&mut self, t: &'tcx Ty) {
517 // Mirrors the case in visit::walk_ty
518 TyKind::BareFn(ref f) => {
524 // Mirrors visit::walk_fn_decl
525 for parameter in &f.decl.inputs {
526 // We don't lower the ids of argument patterns
527 self.with_hir_id_owner(None, |this| {
528 this.visit_pat(¶meter.pat);
530 self.visit_ty(¶meter.ty)
532 self.visit_fn_ret_ty(&f.decl.output)
534 _ => visit::walk_ty(self, t),
539 self.lower_node_id(CRATE_NODE_ID);
540 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
542 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
543 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
545 let module = self.lower_mod(&c.module);
546 let attrs = self.arena.alloc_from_iter(self.lower_attrs(&c.attrs).into_iter());
547 let body_ids = body_ids(&self.bodies);
551 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
557 exported_macros: self.arena.alloc_from_iter(self.exported_macros),
558 non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs),
560 trait_items: self.trait_items,
561 impl_items: self.impl_items,
564 trait_impls: self.trait_impls,
565 modules: self.modules,
569 fn insert_item(&mut self, item: hir::Item<'hir>) {
570 let id = item.hir_id;
571 // FIXME: Use `debug_asset-rt`.
572 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
573 self.items.insert(id, item);
574 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
577 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
578 // Set up the counter if needed.
579 self.item_local_id_counters.entry(owner).or_insert(0);
580 // Always allocate the first `HirId` for the owner itself.
581 let lowered = self.lower_node_id_with_owner(owner, owner);
582 debug_assert_eq!(lowered.local_id.as_u32(), 0);
586 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> hir::HirId
588 F: FnOnce(&mut Self) -> hir::HirId,
590 if ast_node_id == DUMMY_NODE_ID {
591 return hir::DUMMY_HIR_ID;
594 let min_size = ast_node_id.as_usize() + 1;
596 if min_size > self.node_id_to_hir_id.len() {
597 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
600 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
602 if existing_hir_id == hir::DUMMY_HIR_ID {
603 // Generate a new `HirId`.
604 let hir_id = alloc_hir_id(self);
605 self.node_id_to_hir_id[ast_node_id] = hir_id;
613 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
615 F: FnOnce(&mut Self) -> T,
617 let counter = self.item_local_id_counters
618 .insert(owner, HIR_ID_COUNTER_LOCKED)
619 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
620 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
621 self.current_hir_id_owner.push((def_index, counter));
623 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
625 debug_assert!(def_index == new_def_index);
626 debug_assert!(new_counter >= counter);
628 let prev = self.item_local_id_counters
629 .insert(owner, new_counter)
631 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
635 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
636 /// the `LoweringContext`'s `NodeId => HirId` map.
637 /// Take care not to call this method if the resulting `HirId` is then not
638 /// actually used in the HIR, as that would trigger an assertion in the
639 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
640 /// properly. Calling the method twice with the same `NodeId` is fine though.
641 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
642 self.lower_node_id_generic(ast_node_id, |this| {
643 let &mut (def_index, ref mut local_id_counter) =
644 this.current_hir_id_owner.last_mut().unwrap();
645 let local_id = *local_id_counter;
646 *local_id_counter += 1;
649 local_id: hir::ItemLocalId::from_u32(local_id),
654 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
655 self.lower_node_id_generic(ast_node_id, |this| {
656 let local_id_counter = this
657 .item_local_id_counters
659 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
660 let local_id = *local_id_counter;
662 // We want to be sure not to modify the counter in the map while it
663 // is also on the stack. Otherwise we'll get lost updates when writing
664 // back from the stack to the map.
665 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
667 *local_id_counter += 1;
671 .opt_def_index(owner)
672 .expect("you forgot to call `create_def_with_parent` or are lowering node-IDs \
673 that do not belong to the current owner");
677 local_id: hir::ItemLocalId::from_u32(local_id),
682 fn next_id(&mut self) -> hir::HirId {
683 let node_id = self.resolver.next_node_id();
684 self.lower_node_id(node_id)
687 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
689 self.lower_node_id_generic(id, |_| {
690 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
695 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
696 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
697 if pr.unresolved_segments() != 0 {
698 bug!("path not fully resolved: {:?}", pr);
704 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
705 self.resolver.get_import_res(id).present_items()
708 fn diagnostic(&self) -> &errors::Handler {
709 self.sess.diagnostic()
712 /// Reuses the span but adds information like the kind of the desugaring and features that are
713 /// allowed inside this span.
714 fn mark_span_with_reason(
716 reason: DesugaringKind,
718 allow_internal_unstable: Option<Lrc<[Symbol]>>,
720 span.fresh_expansion(ExpnData {
721 allow_internal_unstable,
722 ..ExpnData::default(ExpnKind::Desugaring(reason), span, self.sess.edition())
726 fn with_anonymous_lifetime_mode<R>(
728 anonymous_lifetime_mode: AnonymousLifetimeMode,
729 op: impl FnOnce(&mut Self) -> R,
732 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
733 anonymous_lifetime_mode,
735 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
736 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
737 let result = op(self);
738 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
739 debug!("with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
740 old_anonymous_lifetime_mode);
744 /// Creates a new `hir::GenericParam` for every new lifetime and
745 /// type parameter encountered while evaluating `f`. Definitions
746 /// are created with the parent provided. If no `parent_id` is
747 /// provided, no definitions will be returned.
749 /// Presuming that in-band lifetimes are enabled, then
750 /// `self.anonymous_lifetime_mode` will be updated to match the
751 /// parameter while `f` is running (and restored afterwards).
752 fn collect_in_band_defs<T, F>(
755 anonymous_lifetime_mode: AnonymousLifetimeMode,
757 ) -> (Vec<hir::GenericParam>, T)
759 F: FnOnce(&mut LoweringContext<'_, '_>) -> (Vec<hir::GenericParam>, T),
761 assert!(!self.is_collecting_in_band_lifetimes);
762 assert!(self.lifetimes_to_define.is_empty());
763 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
765 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
766 self.is_collecting_in_band_lifetimes = true;
768 let (in_band_ty_params, res) = f(self);
770 self.is_collecting_in_band_lifetimes = false;
771 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
773 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
775 let params = lifetimes_to_define
777 .map(|(span, hir_name)| self.lifetime_to_generic_param(
778 span, hir_name, parent_id.index,
780 .chain(in_band_ty_params.into_iter())
786 /// Converts a lifetime into a new generic parameter.
787 fn lifetime_to_generic_param(
791 parent_index: DefIndex,
792 ) -> hir::GenericParam {
793 let node_id = self.resolver.next_node_id();
795 // Get the name we'll use to make the def-path. Note
796 // that collisions are ok here and this shouldn't
797 // really show up for end-user.
798 let (str_name, kind) = match hir_name {
799 ParamName::Plain(ident) => (
801 hir::LifetimeParamKind::InBand,
803 ParamName::Fresh(_) => (
804 kw::UnderscoreLifetime,
805 hir::LifetimeParamKind::Elided,
807 ParamName::Error => (
808 kw::UnderscoreLifetime,
809 hir::LifetimeParamKind::Error,
813 // Add a definition for the in-band lifetime def.
814 self.resolver.definitions().create_def_with_parent(
817 DefPathData::LifetimeNs(str_name),
823 hir_id: self.lower_node_id(node_id),
828 pure_wrt_drop: false,
829 kind: hir::GenericParamKind::Lifetime { kind }
833 /// When there is a reference to some lifetime `'a`, and in-band
834 /// lifetimes are enabled, then we want to push that lifetime into
835 /// the vector of names to define later. In that case, it will get
836 /// added to the appropriate generics.
837 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
838 if !self.is_collecting_in_band_lifetimes {
842 if !self.sess.features_untracked().in_band_lifetimes {
846 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.modern())) {
850 let hir_name = ParamName::Plain(ident);
852 if self.lifetimes_to_define.iter()
853 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
857 self.lifetimes_to_define.push((ident.span, hir_name));
860 /// When we have either an elided or `'_` lifetime in an impl
861 /// header, we convert it to an in-band lifetime.
862 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
863 assert!(self.is_collecting_in_band_lifetimes);
864 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
865 let hir_name = ParamName::Fresh(index);
866 self.lifetimes_to_define.push((span, hir_name));
870 // Evaluates `f` with the lifetimes in `params` in-scope.
871 // This is used to track which lifetimes have already been defined, and
872 // which are new in-band lifetimes that need to have a definition created
874 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
876 F: FnOnce(&mut LoweringContext<'_, 'hir>) -> T,
878 let old_len = self.in_scope_lifetimes.len();
879 let lt_def_names = params.iter().filter_map(|param| match param.kind {
880 GenericParamKind::Lifetime { .. } => Some(ParamName::Plain(param.ident.modern())),
883 self.in_scope_lifetimes.extend(lt_def_names);
887 self.in_scope_lifetimes.truncate(old_len);
891 /// Appends in-band lifetime defs and argument-position `impl
892 /// Trait` defs to the existing set of generics.
894 /// Presuming that in-band lifetimes are enabled, then
895 /// `self.anonymous_lifetime_mode` will be updated to match the
896 /// parameter while `f` is running (and restored afterwards).
897 fn add_in_band_defs<F, T>(
901 anonymous_lifetime_mode: AnonymousLifetimeMode,
903 ) -> (hir::Generics, T)
905 F: FnOnce(&mut LoweringContext<'_, '_>, &mut Vec<hir::GenericParam>) -> T,
907 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
910 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
911 let mut params = Vec::new();
912 // Note: it is necessary to lower generics *before* calling `f`.
913 // When lowering `async fn`, there's a final step when lowering
914 // the return type that assumes that all in-scope lifetimes have
915 // already been added to either `in_scope_lifetimes` or
916 // `lifetimes_to_define`. If we swapped the order of these two,
917 // in-band-lifetimes introduced by generics or where-clauses
918 // wouldn't have been added yet.
919 let generics = this.lower_generics(
921 ImplTraitContext::Universal(&mut params),
923 let res = f(this, &mut params);
924 (params, (generics, res))
929 let mut lowered_params: Vec<_> = lowered_generics
935 // FIXME(const_generics): the compiler doesn't always cope with
936 // unsorted generic parameters at the moment, so we make sure
937 // that they're ordered correctly here for now. (When we chain
938 // the `in_band_defs`, we might make the order unsorted.)
939 lowered_params.sort_by_key(|param| {
941 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
942 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
943 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
947 lowered_generics.params = lowered_params.into();
949 (lowered_generics, res)
952 fn with_dyn_type_scope<T, F>(&mut self, in_scope: bool, f: F) -> T
954 F: FnOnce(&mut LoweringContext<'_, '_>) -> T,
956 let was_in_dyn_type = self.is_in_dyn_type;
957 self.is_in_dyn_type = in_scope;
959 let result = f(self);
961 self.is_in_dyn_type = was_in_dyn_type;
966 fn with_new_scopes<T, F>(&mut self, f: F) -> T
968 F: FnOnce(&mut LoweringContext<'_, '_>) -> T,
970 let was_in_loop_condition = self.is_in_loop_condition;
971 self.is_in_loop_condition = false;
973 let catch_scopes = mem::take(&mut self.catch_scopes);
974 let loop_scopes = mem::take(&mut self.loop_scopes);
976 self.catch_scopes = catch_scopes;
977 self.loop_scopes = loop_scopes;
979 self.is_in_loop_condition = was_in_loop_condition;
984 fn def_key(&mut self, id: DefId) -> DefKey {
986 self.resolver.definitions().def_key(id.index)
988 self.resolver.cstore().def_key(id)
992 fn lower_attrs_arena(&mut self, attrs: &[Attribute]) -> &'hir [Attribute] {
993 self.arena.alloc_from_iter(
994 attrs.iter().map(|a| self.lower_attr(a))
998 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
999 attrs.iter().map(|a| self.lower_attr(a)).collect::<Vec<_>>().into()
1002 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1003 // Note that we explicitly do not walk the path. Since we don't really
1004 // lower attributes (we use the AST version) there is nowhere to keep
1005 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1006 let kind = match attr.kind {
1007 AttrKind::Normal(ref item) => {
1008 AttrKind::Normal(AttrItem {
1009 path: item.path.clone(),
1010 args: self.lower_mac_args(&item.args),
1013 AttrKind::DocComment(comment) => AttrKind::DocComment(comment)
1024 fn lower_mac_args(&mut self, args: &MacArgs) -> MacArgs {
1026 MacArgs::Empty => MacArgs::Empty,
1027 MacArgs::Delimited(dspan, delim, ref tokens) =>
1028 MacArgs::Delimited(dspan, delim, self.lower_token_stream(tokens.clone())),
1029 MacArgs::Eq(eq_span, ref tokens) =>
1030 MacArgs::Eq(eq_span, self.lower_token_stream(tokens.clone())),
1034 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1037 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1041 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1043 TokenTree::Token(token) => self.lower_token(token),
1044 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1047 self.lower_token_stream(tts),
1052 fn lower_token(&mut self, token: Token) -> TokenStream {
1054 token::Interpolated(nt) => {
1055 let tts = (self.nt_to_tokenstream)(&nt, &self.sess.parse_sess, token.span);
1056 self.lower_token_stream(tts)
1058 _ => TokenTree::Token(token).into(),
1062 /// Given an associated type constraint like one of these:
1065 /// T: Iterator<Item: Debug>
1067 /// T: Iterator<Item = Debug>
1071 /// returns a `hir::TypeBinding` representing `Item`.
1072 fn lower_assoc_ty_constraint(
1074 constraint: &AssocTyConstraint,
1075 itctx: ImplTraitContext<'_>,
1076 ) -> hir::TypeBinding {
1077 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1079 let kind = match constraint.kind {
1080 AssocTyConstraintKind::Equality { ref ty } => hir::TypeBindingKind::Equality {
1081 ty: self.lower_ty(ty, itctx)
1083 AssocTyConstraintKind::Bound { ref bounds } => {
1084 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1085 let (desugar_to_impl_trait, itctx) = match itctx {
1086 // We are in the return position:
1088 // fn foo() -> impl Iterator<Item: Debug>
1092 // fn foo() -> impl Iterator<Item = impl Debug>
1093 ImplTraitContext::OpaqueTy(_) => (true, itctx),
1095 // We are in the argument position, but within a dyn type:
1097 // fn foo(x: dyn Iterator<Item: Debug>)
1101 // fn foo(x: dyn Iterator<Item = impl Debug>)
1102 ImplTraitContext::Universal(_) if self.is_in_dyn_type => (true, itctx),
1104 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1105 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1106 // "impl trait context" to permit `impl Debug` in this position (it desugars
1107 // then to an opaque type).
1109 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1110 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type =>
1111 (true, ImplTraitContext::OpaqueTy(None)),
1113 // We are in the parameter position, but not within a dyn type:
1115 // fn foo(x: impl Iterator<Item: Debug>)
1117 // so we leave it as is and this gets expanded in astconv to a bound like
1118 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1120 _ => (false, itctx),
1123 if desugar_to_impl_trait {
1124 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1125 // constructing the HIR for `impl bounds...` and then lowering that.
1127 let impl_trait_node_id = self.resolver.next_node_id();
1128 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1129 self.resolver.definitions().create_def_with_parent(
1132 DefPathData::ImplTrait,
1137 self.with_dyn_type_scope(false, |this| {
1138 let node_id = this.resolver.next_node_id();
1139 let ty = this.lower_ty(
1142 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1143 span: constraint.span,
1148 hir::TypeBindingKind::Equality {
1153 // Desugar `AssocTy: Bounds` into a type binding where the
1154 // later desugars into a trait predicate.
1155 let bounds = self.lower_param_bounds(bounds, itctx);
1157 hir::TypeBindingKind::Constraint {
1165 hir_id: self.lower_node_id(constraint.id),
1166 ident: constraint.ident,
1168 span: constraint.span,
1172 fn lower_generic_arg(
1174 arg: &ast::GenericArg,
1175 itctx: ImplTraitContext<'_>
1176 ) -> hir::GenericArg {
1178 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1179 ast::GenericArg::Type(ty) => {
1180 // We parse const arguments as path types as we cannot distiguish them durring
1181 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1182 // type and value namespaces. If we resolved the path in the value namespace, we
1183 // transform it into a generic const argument.
1184 if let TyKind::Path(ref qself, ref path) = ty.kind {
1185 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1186 let res = partial_res.base_res();
1187 if !res.matches_ns(Namespace::TypeNS) {
1189 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1193 // Construct a AnonConst where the expr is the "ty"'s path.
1195 let parent_def_index =
1196 self.current_hir_id_owner.last().unwrap().0;
1197 let node_id = self.resolver.next_node_id();
1199 // Add a definition for the in-band const def.
1200 self.resolver.definitions().create_def_with_parent(
1203 DefPathData::AnonConst,
1208 let path_expr = Expr {
1210 kind: ExprKind::Path(qself.clone(), path.clone()),
1212 attrs: AttrVec::new(),
1215 let ct = self.with_new_scopes(|this| {
1217 hir_id: this.lower_node_id(node_id),
1218 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1221 return GenericArg::Const(ConstArg {
1228 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1230 ast::GenericArg::Const(ct) => {
1231 GenericArg::Const(ConstArg {
1232 value: self.lower_anon_const(&ct),
1233 span: ct.value.span,
1239 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1240 P(self.lower_ty_direct(t, itctx))
1246 qself: &Option<QSelf>,
1248 param_mode: ParamMode,
1249 itctx: ImplTraitContext<'_>
1251 let id = self.lower_node_id(t.id);
1252 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1253 let ty = self.ty_path(id, t.span, qpath);
1254 if let hir::TyKind::TraitObject(..) = ty.kind {
1255 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1260 fn ty(&mut self, span: Span, kind: hir::TyKind) -> hir::Ty {
1261 hir::Ty { hir_id: self.next_id(), kind, span }
1264 fn ty_tup(&mut self, span: Span, tys: HirVec<hir::Ty>) -> hir::Ty {
1265 self.ty(span, hir::TyKind::Tup(tys))
1268 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1269 let kind = match t.kind {
1270 TyKind::Infer => hir::TyKind::Infer,
1271 TyKind::Err => hir::TyKind::Err,
1272 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1273 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1274 TyKind::Rptr(ref region, ref mt) => {
1275 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1276 let lifetime = match *region {
1277 Some(ref lt) => self.lower_lifetime(lt),
1278 None => self.elided_ref_lifetime(span),
1280 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1282 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1285 this.with_anonymous_lifetime_mode(
1286 AnonymousLifetimeMode::PassThrough,
1288 hir::TyKind::BareFn(P(hir::BareFnTy {
1289 generic_params: this.lower_generic_params(
1291 &NodeMap::default(),
1292 ImplTraitContext::disallowed(),
1294 unsafety: f.unsafety,
1295 abi: this.lower_extern(f.ext),
1296 decl: this.lower_fn_decl(&f.decl, None, false, None),
1297 param_names: this.lower_fn_params_to_names(&f.decl),
1303 TyKind::Never => hir::TyKind::Never,
1304 TyKind::Tup(ref tys) => {
1305 hir::TyKind::Tup(tys.iter().map(|ty| {
1306 self.lower_ty_direct(ty, itctx.reborrow())
1309 TyKind::Paren(ref ty) => {
1310 return self.lower_ty_direct(ty, itctx);
1312 TyKind::Path(ref qself, ref path) => {
1313 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1315 TyKind::ImplicitSelf => {
1316 let res = self.expect_full_res(t.id);
1317 let res = self.lower_res(res);
1318 hir::TyKind::Path(hir::QPath::Resolved(
1322 segments: hir_vec![hir::PathSegment::from_ident(
1323 Ident::with_dummy_span(kw::SelfUpper)
1329 TyKind::Array(ref ty, ref length) => {
1330 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1332 TyKind::Typeof(ref expr) => {
1333 hir::TyKind::Typeof(self.lower_anon_const(expr))
1335 TyKind::TraitObject(ref bounds, kind) => {
1336 let mut lifetime_bound = None;
1337 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1340 .filter_map(|bound| match *bound {
1341 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1342 Some(this.lower_poly_trait_ref(ty, itctx.reborrow()))
1344 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1345 GenericBound::Outlives(ref lifetime) => {
1346 if lifetime_bound.is_none() {
1347 lifetime_bound = Some(this.lower_lifetime(lifetime));
1353 let lifetime_bound =
1354 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1355 (bounds, lifetime_bound)
1357 if kind != TraitObjectSyntax::Dyn {
1358 self.maybe_lint_bare_trait(t.span, t.id, false);
1360 hir::TyKind::TraitObject(bounds, lifetime_bound)
1362 TyKind::ImplTrait(def_node_id, ref bounds) => {
1365 ImplTraitContext::OpaqueTy(fn_def_id) => {
1366 self.lower_opaque_impl_trait(
1367 span, fn_def_id, def_node_id,
1368 |this| this.lower_param_bounds(bounds, itctx),
1371 ImplTraitContext::Universal(in_band_ty_params) => {
1372 // Add a definition for the in-band `Param`.
1373 let def_index = self
1376 .opt_def_index(def_node_id)
1379 let hir_bounds = self.lower_param_bounds(
1381 ImplTraitContext::Universal(in_band_ty_params),
1383 // Set the name to `impl Bound1 + Bound2`.
1384 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1385 in_band_ty_params.push(hir::GenericParam {
1386 hir_id: self.lower_node_id(def_node_id),
1387 name: ParamName::Plain(ident),
1388 pure_wrt_drop: false,
1392 kind: hir::GenericParamKind::Type {
1394 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1398 hir::TyKind::Path(hir::QPath::Resolved(
1402 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1403 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1407 ImplTraitContext::Disallowed(pos) => {
1408 let allowed_in = if self.sess.features_untracked()
1409 .impl_trait_in_bindings {
1410 "bindings or function and inherent method return types"
1412 "function and inherent method return types"
1414 let mut err = struct_span_err!(
1418 "`impl Trait` not allowed outside of {}",
1421 if pos == ImplTraitPosition::Binding &&
1422 nightly_options::is_nightly_build() {
1424 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1425 attributes to enable");
1432 TyKind::Mac(_) => bug!("`TyKind::Mac` should have been expanded by now"),
1433 TyKind::CVarArgs => {
1434 self.sess.delay_span_bug(
1436 "`TyKind::CVarArgs` should have been handled elsewhere",
1445 hir_id: self.lower_node_id(t.id),
1449 fn lower_opaque_impl_trait(
1452 fn_def_id: Option<DefId>,
1453 opaque_ty_node_id: NodeId,
1454 lower_bounds: impl FnOnce(&mut LoweringContext<'_, '_>) -> hir::GenericBounds,
1457 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1463 // Make sure we know that some funky desugaring has been going on here.
1464 // This is a first: there is code in other places like for loop
1465 // desugaring that explicitly states that we don't want to track that.
1466 // Not tracking it makes lints in rustc and clippy very fragile, as
1467 // frequently opened issues show.
1468 let opaque_ty_span = self.mark_span_with_reason(
1469 DesugaringKind::OpaqueTy,
1474 let opaque_ty_def_index = self
1477 .opt_def_index(opaque_ty_node_id)
1480 self.allocate_hir_id_counter(opaque_ty_node_id);
1482 let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
1484 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1486 opaque_ty_def_index,
1491 "lower_opaque_impl_trait: lifetimes={:#?}", lifetimes,
1495 "lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs,
1498 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1499 let opaque_ty_item = hir::OpaqueTy {
1500 generics: hir::Generics {
1501 params: lifetime_defs,
1502 where_clause: hir::WhereClause {
1503 predicates: hir_vec![],
1509 impl_trait_fn: fn_def_id,
1510 origin: hir::OpaqueTyOrigin::FnReturn,
1513 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_index);
1514 let opaque_ty_id = lctx.generate_opaque_type(
1521 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1522 hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, lifetimes)
1526 /// Registers a new opaque type with the proper `NodeId`s and
1527 /// returns the lowered node-ID for the opaque type.
1528 fn generate_opaque_type(
1530 opaque_ty_node_id: NodeId,
1531 opaque_ty_item: hir::OpaqueTy,
1533 opaque_ty_span: Span,
1535 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1536 let opaque_ty_id = self.lower_node_id(opaque_ty_node_id);
1537 // Generate an `type Foo = impl Trait;` declaration.
1538 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1539 let opaque_ty_item = hir::Item {
1540 hir_id: opaque_ty_id,
1541 ident: Ident::invalid(),
1542 attrs: Default::default(),
1543 kind: opaque_ty_item_kind,
1544 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1545 span: opaque_ty_span,
1548 // Insert the item into the global item list. This usually happens
1549 // automatically for all AST items. But this opaque type item
1550 // does not actually exist in the AST.
1551 self.insert_item(opaque_ty_item);
1555 fn lifetimes_from_impl_trait_bounds(
1557 opaque_ty_id: NodeId,
1558 parent_index: DefIndex,
1559 bounds: &hir::GenericBounds,
1560 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1562 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
1563 parent_index={:?}, \
1565 opaque_ty_id, parent_index, bounds,
1568 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1569 // appear in the bounds, excluding lifetimes that are created within the bounds.
1570 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1571 struct ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1572 context: &'r mut LoweringContext<'a, 'hir>,
1574 opaque_ty_id: NodeId,
1575 collect_elided_lifetimes: bool,
1576 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1577 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1578 output_lifetimes: Vec<hir::GenericArg>,
1579 output_lifetime_params: Vec<hir::GenericParam>,
1582 impl<'r, 'a, 'v, 'hir> hir::intravisit::Visitor<'v>
1583 for ImplTraitLifetimeCollector<'r, 'a, 'hir>
1585 fn nested_visit_map<'this>(
1587 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1588 hir::intravisit::NestedVisitorMap::None
1591 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1592 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1593 if parameters.parenthesized {
1594 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1595 self.collect_elided_lifetimes = false;
1596 hir::intravisit::walk_generic_args(self, span, parameters);
1597 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1599 hir::intravisit::walk_generic_args(self, span, parameters);
1603 fn visit_ty(&mut self, t: &'v hir::Ty) {
1604 // Don't collect elided lifetimes used inside of `fn()` syntax.
1605 if let hir::TyKind::BareFn(_) = t.kind {
1606 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1607 self.collect_elided_lifetimes = false;
1609 // Record the "stack height" of `for<'a>` lifetime bindings
1610 // to be able to later fully undo their introduction.
1611 let old_len = self.currently_bound_lifetimes.len();
1612 hir::intravisit::walk_ty(self, t);
1613 self.currently_bound_lifetimes.truncate(old_len);
1615 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1617 hir::intravisit::walk_ty(self, t)
1621 fn visit_poly_trait_ref(
1623 trait_ref: &'v hir::PolyTraitRef,
1624 modifier: hir::TraitBoundModifier,
1626 // Record the "stack height" of `for<'a>` lifetime bindings
1627 // to be able to later fully undo their introduction.
1628 let old_len = self.currently_bound_lifetimes.len();
1629 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1630 self.currently_bound_lifetimes.truncate(old_len);
1633 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1634 // Record the introduction of 'a in `for<'a> ...`.
1635 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1636 // Introduce lifetimes one at a time so that we can handle
1637 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1638 let lt_name = hir::LifetimeName::Param(param.name);
1639 self.currently_bound_lifetimes.push(lt_name);
1642 hir::intravisit::walk_generic_param(self, param);
1645 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1646 let name = match lifetime.name {
1647 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1648 if self.collect_elided_lifetimes {
1649 // Use `'_` for both implicit and underscore lifetimes in
1650 // `type Foo<'_> = impl SomeTrait<'_>;`.
1651 hir::LifetimeName::Underscore
1656 hir::LifetimeName::Param(_) => lifetime.name,
1658 // Refers to some other lifetime that is "in
1659 // scope" within the type.
1660 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1662 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1665 if !self.currently_bound_lifetimes.contains(&name)
1666 && !self.already_defined_lifetimes.contains(&name) {
1667 self.already_defined_lifetimes.insert(name);
1669 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1670 hir_id: self.context.next_id(),
1671 span: lifetime.span,
1675 let def_node_id = self.context.resolver.next_node_id();
1677 self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1678 self.context.resolver.definitions().create_def_with_parent(
1681 DefPathData::LifetimeNs(name.ident().name),
1685 let (name, kind) = match name {
1686 hir::LifetimeName::Underscore => (
1687 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1688 hir::LifetimeParamKind::Elided,
1690 hir::LifetimeName::Param(param_name) => (
1692 hir::LifetimeParamKind::Explicit,
1694 _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1697 self.output_lifetime_params.push(hir::GenericParam {
1700 span: lifetime.span,
1701 pure_wrt_drop: false,
1704 kind: hir::GenericParamKind::Lifetime { kind }
1710 let mut lifetime_collector = ImplTraitLifetimeCollector {
1712 parent: parent_index,
1714 collect_elided_lifetimes: true,
1715 currently_bound_lifetimes: Vec::new(),
1716 already_defined_lifetimes: FxHashSet::default(),
1717 output_lifetimes: Vec::new(),
1718 output_lifetime_params: Vec::new(),
1721 for bound in bounds {
1722 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1726 lifetime_collector.output_lifetimes.into(),
1727 lifetime_collector.output_lifetime_params.into(),
1734 qself: &Option<QSelf>,
1736 param_mode: ParamMode,
1737 mut itctx: ImplTraitContext<'_>,
1739 let qself_position = qself.as_ref().map(|q| q.position);
1740 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1742 let partial_res = self.resolver
1743 .get_partial_res(id)
1744 .unwrap_or_else(|| PartialRes::new(Res::Err));
1746 let proj_start = p.segments.len() - partial_res.unresolved_segments();
1747 let path = P(hir::Path {
1748 res: self.lower_res(partial_res.base_res()),
1749 segments: p.segments[..proj_start]
1752 .map(|(i, segment)| {
1753 let param_mode = match (qself_position, param_mode) {
1754 (Some(j), ParamMode::Optional) if i < j => {
1755 // This segment is part of the trait path in a
1756 // qualified path - one of `a`, `b` or `Trait`
1757 // in `<X as a::b::Trait>::T::U::method`.
1763 // Figure out if this is a type/trait segment,
1764 // which may need lifetime elision performed.
1765 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1766 krate: def_id.krate,
1767 index: this.def_key(def_id).parent.expect("missing parent"),
1769 let type_def_id = match partial_res.base_res() {
1770 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1771 Some(parent_def_id(self, def_id))
1773 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1774 Some(parent_def_id(self, def_id))
1776 Res::Def(DefKind::Struct, def_id)
1777 | Res::Def(DefKind::Union, def_id)
1778 | Res::Def(DefKind::Enum, def_id)
1779 | Res::Def(DefKind::TyAlias, def_id)
1780 | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
1786 let parenthesized_generic_args = match partial_res.base_res() {
1787 // `a::b::Trait(Args)`
1788 Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
1789 ParenthesizedGenericArgs::Ok
1791 // `a::b::Trait(Args)::TraitItem`
1792 Res::Def(DefKind::Method, _) |
1793 Res::Def(DefKind::AssocConst, _) |
1794 Res::Def(DefKind::AssocTy, _) if i + 2 == proj_start => {
1795 ParenthesizedGenericArgs::Ok
1797 // Avoid duplicated errors.
1798 Res::Err => ParenthesizedGenericArgs::Ok,
1800 _ => ParenthesizedGenericArgs::Err,
1803 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1804 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1807 assert!(!def_id.is_local());
1808 let item_generics = self.resolver.cstore()
1809 .item_generics_cloned_untracked(def_id, self.sess);
1810 let n = item_generics.own_counts().lifetimes;
1811 self.type_def_lifetime_params.insert(def_id, n);
1814 self.lower_path_segment(
1819 parenthesized_generic_args,
1828 // Simple case, either no projections, or only fully-qualified.
1829 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1830 if partial_res.unresolved_segments() == 0 {
1831 return hir::QPath::Resolved(qself, path);
1834 // Create the innermost type that we're projecting from.
1835 let mut ty = if path.segments.is_empty() {
1836 // If the base path is empty that means there exists a
1837 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1838 qself.expect("missing QSelf for <T>::...")
1840 // Otherwise, the base path is an implicit `Self` type path,
1841 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1842 // `<I as Iterator>::Item::default`.
1843 let new_id = self.next_id();
1844 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1847 // Anything after the base path are associated "extensions",
1848 // out of which all but the last one are associated types,
1849 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1850 // * base path is `std::vec::Vec<T>`
1851 // * "extensions" are `IntoIter`, `Item` and `clone`
1852 // * type nodes are:
1853 // 1. `std::vec::Vec<T>` (created above)
1854 // 2. `<std::vec::Vec<T>>::IntoIter`
1855 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1856 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1857 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1858 let segment = P(self.lower_path_segment(
1863 ParenthesizedGenericArgs::Err,
1867 let qpath = hir::QPath::TypeRelative(ty, segment);
1869 // It's finished, return the extension of the right node type.
1870 if i == p.segments.len() - 1 {
1874 // Wrap the associated extension in another type node.
1875 let new_id = self.next_id();
1876 ty = P(self.ty_path(new_id, p.span, qpath));
1879 // We should've returned in the for loop above.
1882 "lower_qpath: no final extension segment in {}..{}",
1888 fn lower_path_extra(
1892 param_mode: ParamMode,
1893 explicit_owner: Option<NodeId>,
1897 segments: p.segments
1900 self.lower_path_segment(
1905 ParenthesizedGenericArgs::Err,
1906 ImplTraitContext::disallowed(),
1915 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1916 let res = self.expect_full_res(id);
1917 let res = self.lower_res(res);
1918 self.lower_path_extra(res, p, param_mode, None)
1921 fn lower_path_segment(
1924 segment: &PathSegment,
1925 param_mode: ParamMode,
1926 expected_lifetimes: usize,
1927 parenthesized_generic_args: ParenthesizedGenericArgs,
1928 itctx: ImplTraitContext<'_>,
1929 explicit_owner: Option<NodeId>,
1930 ) -> hir::PathSegment {
1931 let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
1932 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
1933 match **generic_args {
1934 GenericArgs::AngleBracketed(ref data) => {
1935 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1937 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1938 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1939 ParenthesizedGenericArgs::Err => {
1940 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
1941 err.span_label(data.span, "only `Fn` traits may use parentheses");
1942 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
1943 // Do not suggest going from `Trait()` to `Trait<>`
1944 if data.inputs.len() > 0 {
1945 if let Some(split) = snippet.find('(') {
1946 let trait_name = &snippet[0..split];
1947 let args = &snippet[split + 1 .. snippet.len() - 1];
1948 err.span_suggestion(
1950 "use angle brackets instead",
1951 format!("{}<{}>", trait_name, args),
1952 Applicability::MaybeIncorrect,
1959 self.lower_angle_bracketed_parameter_data(
1960 &data.as_angle_bracketed_args(),
1970 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1973 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1974 GenericArg::Lifetime(_) => true,
1977 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1978 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1979 if !generic_args.parenthesized && !has_lifetimes {
1981 self.elided_path_lifetimes(path_span, expected_lifetimes)
1983 .map(|lt| GenericArg::Lifetime(lt))
1984 .chain(generic_args.args.into_iter())
1986 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1987 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1988 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
1989 let no_bindings = generic_args.bindings.is_empty();
1990 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
1991 // If there are no (non-implicit) generic args or associated type
1992 // bindings, our suggestion includes the angle brackets.
1993 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1995 // Otherwise (sorry, this is kind of gross) we need to infer the
1996 // place to splice in the `'_, ` from the generics that do exist.
1997 let first_generic_span = first_generic_span
1998 .expect("already checked that non-lifetime args or bindings exist");
1999 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
2001 match self.anonymous_lifetime_mode {
2002 // In create-parameter mode we error here because we don't want to support
2003 // deprecated impl elision in new features like impl elision and `async fn`,
2004 // both of which work using the `CreateParameter` mode:
2006 // impl Foo for std::cell::Ref<u32> // note lack of '_
2007 // async fn foo(_: std::cell::Ref<u32>) { ... }
2008 AnonymousLifetimeMode::CreateParameter => {
2009 let mut err = struct_span_err!(
2013 "implicit elided lifetime not allowed here"
2015 crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
2026 AnonymousLifetimeMode::PassThrough |
2027 AnonymousLifetimeMode::ReportError => {
2028 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2029 ELIDED_LIFETIMES_IN_PATHS,
2032 "hidden lifetime parameters in types are deprecated",
2033 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2046 let res = self.expect_full_res(segment.id);
2047 let id = if let Some(owner) = explicit_owner {
2048 self.lower_node_id_with_owner(segment.id, owner)
2050 self.lower_node_id(segment.id)
2053 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2054 segment.ident, segment.id, id,
2057 hir::PathSegment::new(
2060 Some(self.lower_res(res)),
2066 fn lower_angle_bracketed_parameter_data(
2068 data: &AngleBracketedArgs,
2069 param_mode: ParamMode,
2070 mut itctx: ImplTraitContext<'_>,
2071 ) -> (hir::GenericArgs, bool) {
2072 let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
2073 let has_non_lt_args = args.iter().any(|arg| match arg {
2074 ast::GenericArg::Lifetime(_) => false,
2075 ast::GenericArg::Type(_) => true,
2076 ast::GenericArg::Const(_) => true,
2080 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2081 bindings: constraints.iter()
2082 .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow()))
2084 parenthesized: false,
2086 !has_non_lt_args && param_mode == ParamMode::Optional
2090 fn lower_parenthesized_parameter_data(
2092 data: &ParenthesizedArgs,
2093 ) -> (hir::GenericArgs, bool) {
2094 // Switch to `PassThrough` mode for anonymous lifetimes; this
2095 // means that we permit things like `&Ref<T>`, where `Ref` has
2096 // a hidden lifetime parameter. This is needed for backwards
2097 // compatibility, even in contexts like an impl header where
2098 // we generally don't permit such things (see #51008).
2099 self.with_anonymous_lifetime_mode(
2100 AnonymousLifetimeMode::PassThrough,
2102 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2105 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2107 let output_ty = match output {
2108 FunctionRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()),
2109 FunctionRetTy::Default(_) => P(this.ty_tup(span, hir::HirVec::new())),
2111 let args = hir_vec![GenericArg::Type(this.ty_tup(span, inputs))];
2112 let binding = hir::TypeBinding {
2113 hir_id: this.next_id(),
2114 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2115 span: output_ty.span,
2116 kind: hir::TypeBindingKind::Equality { ty: output_ty },
2119 hir::GenericArgs { args, bindings: hir_vec![binding], parenthesized: true },
2126 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2127 let mut ids = SmallVec::<[NodeId; 1]>::new();
2128 if self.sess.features_untracked().impl_trait_in_bindings {
2129 if let Some(ref ty) = l.ty {
2130 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2131 visitor.visit_ty(ty);
2134 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2136 hir_id: self.lower_node_id(l.id),
2139 .map(|t| self.lower_ty(t,
2140 if self.sess.features_untracked().impl_trait_in_bindings {
2141 ImplTraitContext::OpaqueTy(Some(parent_def_id))
2143 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2146 pat: self.lower_pat(&l.pat),
2147 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2149 attrs: l.attrs.clone(),
2150 source: hir::LocalSource::Normal,
2154 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2155 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2156 // as they are not explicit in HIR/Ty function signatures.
2157 // (instead, the `c_variadic` flag is set to `true`)
2158 let mut inputs = &decl.inputs[..];
2159 if decl.c_variadic() {
2160 inputs = &inputs[..inputs.len() - 1];
2164 .map(|param| match param.pat.kind {
2165 PatKind::Ident(_, ident, _) => ident,
2166 _ => Ident::new(kw::Invalid, param.pat.span),
2171 // Lowers a function declaration.
2173 // `decl`: the unlowered (AST) function declaration.
2174 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2175 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2176 // `make_ret_async` is also `Some`.
2177 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2178 // This guards against trait declarations and implementations where `impl Trait` is
2180 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2181 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2182 // return type `impl Trait` item.
2186 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2187 impl_trait_return_allow: bool,
2188 make_ret_async: Option<NodeId>,
2189 ) -> P<hir::FnDecl> {
2190 debug!("lower_fn_decl(\
2192 in_band_ty_params: {:?}, \
2193 impl_trait_return_allow: {}, \
2194 make_ret_async: {:?})",
2197 impl_trait_return_allow,
2200 let lt_mode = if make_ret_async.is_some() {
2201 // In `async fn`, argument-position elided lifetimes
2202 // must be transformed into fresh generic parameters so that
2203 // they can be applied to the opaque `impl Trait` return type.
2204 AnonymousLifetimeMode::CreateParameter
2206 self.anonymous_lifetime_mode
2209 let c_variadic = decl.c_variadic();
2211 // Remember how many lifetimes were already around so that we can
2212 // only look at the lifetime parameters introduced by the arguments.
2213 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2214 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2215 // as they are not explicit in HIR/Ty function signatures.
2216 // (instead, the `c_variadic` flag is set to `true`)
2217 let mut inputs = &decl.inputs[..];
2219 inputs = &inputs[..inputs.len() - 1];
2224 if let Some((_, ibty)) = &mut in_band_ty_params {
2225 this.lower_ty_direct(¶m.ty, ImplTraitContext::Universal(ibty))
2227 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
2230 .collect::<HirVec<_>>()
2233 let output = if let Some(ret_id) = make_ret_async {
2234 self.lower_async_fn_ret_ty(
2236 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2241 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2242 Some((def_id, _)) if impl_trait_return_allow => {
2243 hir::Return(self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(def_id))))
2246 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2249 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2257 implicit_self: decl.inputs.get(0).map_or(
2258 hir::ImplicitSelfKind::None,
2260 let is_mutable_pat = match arg.pat.kind {
2261 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2262 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2263 mt == Mutability::Mut,
2268 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2269 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2270 // Given we are only considering `ImplicitSelf` types, we needn't consider
2271 // the case where we have a mutable pattern to a reference as that would
2272 // no longer be an `ImplicitSelf`.
2273 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() &&
2274 mt.mutbl == ast::Mutability::Mut =>
2275 hir::ImplicitSelfKind::MutRef,
2276 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() =>
2277 hir::ImplicitSelfKind::ImmRef,
2278 _ => hir::ImplicitSelfKind::None,
2285 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
2286 // combined with the following definition of `OpaqueTy`:
2288 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
2290 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
2291 // `output`: unlowered output type (`T` in `-> T`)
2292 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2293 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
2294 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2295 fn lower_async_fn_ret_ty(
2297 output: &FunctionRetTy,
2299 opaque_ty_node_id: NodeId,
2300 ) -> hir::FunctionRetTy {
2302 "lower_async_fn_ret_ty(\
2305 opaque_ty_node_id={:?})",
2306 output, fn_def_id, opaque_ty_node_id,
2309 let span = output.span();
2311 let opaque_ty_span = self.mark_span_with_reason(
2312 DesugaringKind::Async,
2317 let opaque_ty_def_index = self
2320 .opt_def_index(opaque_ty_node_id)
2323 self.allocate_hir_id_counter(opaque_ty_node_id);
2325 // When we create the opaque type for this async fn, it is going to have
2326 // to capture all the lifetimes involved in the signature (including in the
2327 // return type). This is done by introducing lifetime parameters for:
2329 // - all the explicitly declared lifetimes from the impl and function itself;
2330 // - all the elided lifetimes in the fn arguments;
2331 // - all the elided lifetimes in the return type.
2333 // So for example in this snippet:
2336 // impl<'a> Foo<'a> {
2337 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
2338 // // ^ '0 ^ '1 ^ '2
2339 // // elided lifetimes used below
2344 // we would create an opaque type like:
2347 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
2350 // and we would then desugar `bar` to the equivalent of:
2353 // impl<'a> Foo<'a> {
2354 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
2358 // Note that the final parameter to `Bar` is `'_`, not `'2` --
2359 // this is because the elided lifetimes from the return type
2360 // should be figured out using the ordinary elision rules, and
2361 // this desugaring achieves that.
2363 // The variable `input_lifetimes_count` tracks the number of
2364 // lifetime parameters to the opaque type *not counting* those
2365 // lifetimes elided in the return type. This includes those
2366 // that are explicitly declared (`in_scope_lifetimes`) and
2367 // those elided lifetimes we found in the arguments (current
2368 // content of `lifetimes_to_define`). Next, we will process
2369 // the return type, which will cause `lifetimes_to_define` to
2371 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
2373 let (opaque_ty_id, lifetime_params) = self.with_hir_id_owner(opaque_ty_node_id, |this| {
2374 // We have to be careful to get elision right here. The
2375 // idea is that we create a lifetime parameter for each
2376 // lifetime in the return type. So, given a return type
2377 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
2378 // Future<Output = &'1 [ &'2 u32 ]>`.
2380 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
2381 // hence the elision takes place at the fn site.
2382 let future_bound = this.with_anonymous_lifetime_mode(
2383 AnonymousLifetimeMode::CreateParameter,
2384 |this| this.lower_async_fn_output_type_to_future_bound(
2391 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
2393 // Calculate all the lifetimes that should be captured
2394 // by the opaque type. This should include all in-scope
2395 // lifetime parameters, including those defined in-band.
2397 // Note: this must be done after lowering the output type,
2398 // as the output type may introduce new in-band lifetimes.
2399 let lifetime_params: Vec<(Span, ParamName)> =
2400 this.in_scope_lifetimes
2402 .map(|name| (name.ident().span, name))
2403 .chain(this.lifetimes_to_define.iter().cloned())
2406 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
2407 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
2408 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
2410 let generic_params =
2413 .map(|(span, hir_name)| {
2414 this.lifetime_to_generic_param(span, hir_name, opaque_ty_def_index)
2418 let opaque_ty_item = hir::OpaqueTy {
2419 generics: hir::Generics {
2420 params: generic_params,
2421 where_clause: hir::WhereClause {
2422 predicates: hir_vec![],
2427 bounds: hir_vec![future_bound],
2428 impl_trait_fn: Some(fn_def_id),
2429 origin: hir::OpaqueTyOrigin::AsyncFn,
2432 trace!("exist ty from async fn def index: {:#?}", opaque_ty_def_index);
2433 let opaque_ty_id = this.generate_opaque_type(
2440 (opaque_ty_id, lifetime_params)
2443 // As documented above on the variable
2444 // `input_lifetimes_count`, we need to create the lifetime
2445 // arguments to our opaque type. Continuing with our example,
2446 // we're creating the type arguments for the return type:
2449 // Bar<'a, 'b, '0, '1, '_>
2452 // For the "input" lifetime parameters, we wish to create
2453 // references to the parameters themselves, including the
2454 // "implicit" ones created from parameter types (`'a`, `'b`,
2457 // For the "output" lifetime parameters, we just want to
2459 let mut generic_args: Vec<_> =
2460 lifetime_params[..input_lifetimes_count]
2462 .map(|&(span, hir_name)| {
2463 // Input lifetime like `'a` or `'1`:
2464 GenericArg::Lifetime(hir::Lifetime {
2465 hir_id: self.next_id(),
2467 name: hir::LifetimeName::Param(hir_name),
2471 generic_args.extend(
2472 lifetime_params[input_lifetimes_count..]
2475 // Output lifetime like `'_`.
2476 GenericArg::Lifetime(hir::Lifetime {
2477 hir_id: self.next_id(),
2479 name: hir::LifetimeName::Implicit,
2484 // Create the `Foo<...>` reference itself. Note that the `type
2485 // Foo = impl Trait` is, internally, created as a child of the
2486 // async fn, so the *type parameters* are inherited. It's
2487 // only the lifetime parameters that we must supply.
2488 let opaque_ty_ref = hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, generic_args.into());
2489 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2490 hir::FunctionRetTy::Return(P(opaque_ty))
2493 /// Transforms `-> T` into `Future<Output = T>`
2494 fn lower_async_fn_output_type_to_future_bound(
2496 output: &FunctionRetTy,
2499 ) -> hir::GenericBound {
2500 // Compute the `T` in `Future<Output = T>` from the return type.
2501 let output_ty = match output {
2502 FunctionRetTy::Ty(ty) => self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(fn_def_id))),
2503 FunctionRetTy::Default(ret_ty_span) => P(self.ty_tup(*ret_ty_span, hir_vec![])),
2507 let future_params = P(hir::GenericArgs {
2509 bindings: hir_vec![hir::TypeBinding {
2510 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2511 kind: hir::TypeBindingKind::Equality {
2514 hir_id: self.next_id(),
2517 parenthesized: false,
2520 // ::std::future::Future<future_params>
2522 P(self.std_path(span, &[sym::future, sym::Future], Some(future_params), false));
2524 hir::GenericBound::Trait(
2526 trait_ref: hir::TraitRef {
2528 hir_ref_id: self.next_id(),
2530 bound_generic_params: hir_vec![],
2533 hir::TraitBoundModifier::None,
2537 fn lower_param_bound(
2540 itctx: ImplTraitContext<'_>,
2541 ) -> hir::GenericBound {
2543 GenericBound::Trait(ref ty, modifier) => {
2544 hir::GenericBound::Trait(
2545 self.lower_poly_trait_ref(ty, itctx),
2546 self.lower_trait_bound_modifier(modifier),
2549 GenericBound::Outlives(ref lifetime) => {
2550 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2555 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2556 let span = l.ident.span;
2558 ident if ident.name == kw::StaticLifetime =>
2559 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2560 ident if ident.name == kw::UnderscoreLifetime =>
2561 match self.anonymous_lifetime_mode {
2562 AnonymousLifetimeMode::CreateParameter => {
2563 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2564 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2567 AnonymousLifetimeMode::PassThrough => {
2568 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2571 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2574 self.maybe_collect_in_band_lifetime(ident);
2575 let param_name = ParamName::Plain(ident);
2576 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2581 fn new_named_lifetime(
2585 name: hir::LifetimeName,
2586 ) -> hir::Lifetime {
2588 hir_id: self.lower_node_id(id),
2594 fn lower_generic_params(
2596 params: &[GenericParam],
2597 add_bounds: &NodeMap<Vec<GenericBound>>,
2598 mut itctx: ImplTraitContext<'_>,
2599 ) -> hir::HirVec<hir::GenericParam> {
2600 params.iter().map(|param| {
2601 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2605 fn lower_generic_param(&mut self,
2606 param: &GenericParam,
2607 add_bounds: &NodeMap<Vec<GenericBound>>,
2608 mut itctx: ImplTraitContext<'_>)
2609 -> hir::GenericParam {
2610 let mut bounds = self.with_anonymous_lifetime_mode(
2611 AnonymousLifetimeMode::ReportError,
2612 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2615 let (name, kind) = match param.kind {
2616 GenericParamKind::Lifetime => {
2617 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2618 self.is_collecting_in_band_lifetimes = false;
2620 let lt = self.with_anonymous_lifetime_mode(
2621 AnonymousLifetimeMode::ReportError,
2622 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2624 let param_name = match lt.name {
2625 hir::LifetimeName::Param(param_name) => param_name,
2626 hir::LifetimeName::Implicit
2627 | hir::LifetimeName::Underscore
2628 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2629 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2632 "object-lifetime-default should not occur here",
2635 hir::LifetimeName::Error => ParamName::Error,
2638 let kind = hir::GenericParamKind::Lifetime {
2639 kind: hir::LifetimeParamKind::Explicit
2642 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2646 GenericParamKind::Type { ref default, .. } => {
2647 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2648 if !add_bounds.is_empty() {
2649 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2650 bounds = bounds.into_iter()
2655 let kind = hir::GenericParamKind::Type {
2656 default: default.as_ref().map(|x| {
2657 self.lower_ty(x, ImplTraitContext::OpaqueTy(None))
2659 synthetic: param.attrs.iter()
2660 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2661 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2665 (hir::ParamName::Plain(param.ident), kind)
2667 GenericParamKind::Const { ref ty } => {
2668 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2669 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2675 hir_id: self.lower_node_id(param.id),
2677 span: param.ident.span,
2678 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2679 attrs: self.lower_attrs(¶m.attrs),
2685 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2686 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2687 hir::QPath::Resolved(None, path) => path,
2688 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2692 hir_ref_id: self.lower_node_id(p.ref_id),
2696 fn lower_poly_trait_ref(
2699 mut itctx: ImplTraitContext<'_>,
2700 ) -> hir::PolyTraitRef {
2701 let bound_generic_params = self.lower_generic_params(
2702 &p.bound_generic_params,
2703 &NodeMap::default(),
2706 let trait_ref = self.with_in_scope_lifetime_defs(
2707 &p.bound_generic_params,
2708 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2712 bound_generic_params,
2718 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2720 ty: self.lower_ty(&mt.ty, itctx),
2725 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2726 -> hir::GenericBounds {
2727 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2730 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2731 let mut stmts = vec![];
2732 let mut expr = None;
2734 for (index, stmt) in b.stmts.iter().enumerate() {
2735 if index == b.stmts.len() - 1 {
2736 if let StmtKind::Expr(ref e) = stmt.kind {
2737 expr = Some(P(self.lower_expr(e)));
2739 stmts.extend(self.lower_stmt(stmt));
2742 stmts.extend(self.lower_stmt(stmt));
2747 hir_id: self.lower_node_id(b.id),
2748 stmts: stmts.into(),
2750 rules: self.lower_block_check_mode(&b.rules),
2756 /// Lowers a block directly to an expression, presuming that it
2757 /// has no attributes and is not targeted by a `break`.
2758 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr {
2759 let block = self.lower_block(b, false);
2760 self.expr_block(block, AttrVec::new())
2763 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2764 let node = match p.kind {
2765 PatKind::Wild => hir::PatKind::Wild,
2766 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2767 let lower_sub = |this: &mut Self| sub.as_ref().map(|s| this.lower_pat(&*s));
2768 let node = self.lower_pat_ident(p, binding_mode, ident, lower_sub);
2771 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
2772 PatKind::TupleStruct(ref path, ref pats) => {
2773 let qpath = self.lower_qpath(
2777 ParamMode::Optional,
2778 ImplTraitContext::disallowed(),
2780 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple struct");
2781 hir::PatKind::TupleStruct(qpath, pats, ddpos)
2783 PatKind::Or(ref pats) => {
2784 hir::PatKind::Or(pats.iter().map(|x| self.lower_pat(x)).collect())
2786 PatKind::Path(ref qself, ref path) => {
2787 let qpath = self.lower_qpath(
2791 ParamMode::Optional,
2792 ImplTraitContext::disallowed(),
2794 hir::PatKind::Path(qpath)
2796 PatKind::Struct(ref path, ref fields, etc) => {
2797 let qpath = self.lower_qpath(
2801 ParamMode::Optional,
2802 ImplTraitContext::disallowed(),
2807 .map(|f| hir::FieldPat {
2808 hir_id: self.next_id(),
2810 pat: self.lower_pat(&f.pat),
2811 is_shorthand: f.is_shorthand,
2815 hir::PatKind::Struct(qpath, fs, etc)
2817 PatKind::Tuple(ref pats) => {
2818 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple");
2819 hir::PatKind::Tuple(pats, ddpos)
2821 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
2822 PatKind::Ref(ref inner, mutbl) => {
2823 hir::PatKind::Ref(self.lower_pat(inner), mutbl)
2825 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
2826 P(self.lower_expr(e1)),
2827 P(self.lower_expr(e2)),
2828 self.lower_range_end(end),
2830 PatKind::Slice(ref pats) => self.lower_pat_slice(pats),
2832 // If we reach here the `..` pattern is not semantically allowed.
2833 self.ban_illegal_rest_pat(p.span)
2835 PatKind::Paren(ref inner) => return self.lower_pat(inner),
2836 PatKind::Mac(_) => panic!("Shouldn't exist here"),
2839 self.pat_with_node_id_of(p, node)
2846 ) -> (HirVec<P<hir::Pat>>, Option<usize>) {
2847 let mut elems = Vec::with_capacity(pats.len());
2848 let mut rest = None;
2850 let mut iter = pats.iter().enumerate();
2851 for (idx, pat) in iter.by_ref() {
2852 // Interpret the first `..` pattern as a sub-tuple pattern.
2853 // Note that unlike for slice patterns,
2854 // where `xs @ ..` is a legal sub-slice pattern,
2855 // it is not a legal sub-tuple pattern.
2857 rest = Some((idx, pat.span));
2860 // It was not a sub-tuple pattern so lower it normally.
2861 elems.push(self.lower_pat(pat));
2864 for (_, pat) in iter {
2865 // There was a previous sub-tuple pattern; make sure we don't allow more...
2867 // ...but there was one again, so error.
2868 self.ban_extra_rest_pat(pat.span, rest.unwrap().1, ctx);
2870 elems.push(self.lower_pat(pat));
2874 (elems.into(), rest.map(|(ddpos, _)| ddpos))
2877 /// Lower a slice pattern of form `[pat_0, ..., pat_n]` into
2878 /// `hir::PatKind::Slice(before, slice, after)`.
2880 /// When encountering `($binding_mode $ident @)? ..` (`slice`),
2881 /// this is interpreted as a sub-slice pattern semantically.
2882 /// Patterns that follow, which are not like `slice` -- or an error occurs, are in `after`.
2883 fn lower_pat_slice(&mut self, pats: &[AstP<Pat>]) -> hir::PatKind {
2884 let mut before = Vec::new();
2885 let mut after = Vec::new();
2886 let mut slice = None;
2887 let mut prev_rest_span = None;
2889 let mut iter = pats.iter();
2890 // Lower all the patterns until the first occurence of a sub-slice pattern.
2891 for pat in iter.by_ref() {
2893 // Found a sub-slice pattern `..`. Record, lower it to `_`, and stop here.
2895 prev_rest_span = Some(pat.span);
2896 slice = Some(self.pat_wild_with_node_id_of(pat));
2899 // Found a sub-slice pattern `$binding_mode $ident @ ..`.
2900 // Record, lower it to `$binding_mode $ident @ _`, and stop here.
2901 PatKind::Ident(ref bm, ident, Some(ref sub)) if sub.is_rest() => {
2902 prev_rest_span = Some(sub.span);
2903 let lower_sub = |this: &mut Self| Some(this.pat_wild_with_node_id_of(sub));
2904 let node = self.lower_pat_ident(pat, bm, ident, lower_sub);
2905 slice = Some(self.pat_with_node_id_of(pat, node));
2908 // It was not a subslice pattern so lower it normally.
2909 _ => before.push(self.lower_pat(pat)),
2913 // Lower all the patterns after the first sub-slice pattern.
2915 // There was a previous subslice pattern; make sure we don't allow more.
2916 let rest_span = match pat.kind {
2917 PatKind::Rest => Some(pat.span),
2918 PatKind::Ident(.., Some(ref sub)) if sub.is_rest() => {
2919 // The `HirValidator` is merciless; add a `_` pattern to avoid ICEs.
2920 after.push(self.pat_wild_with_node_id_of(pat));
2925 if let Some(rest_span) = rest_span {
2926 // We have e.g., `[a, .., b, ..]`. That's no good, error!
2927 self.ban_extra_rest_pat(rest_span, prev_rest_span.unwrap(), "slice");
2929 // Lower the pattern normally.
2930 after.push(self.lower_pat(pat));
2934 hir::PatKind::Slice(before.into(), slice, after.into())
2940 binding_mode: &BindingMode,
2942 lower_sub: impl FnOnce(&mut Self) -> Option<P<hir::Pat>>,
2944 match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
2945 // `None` can occur in body-less function signatures
2946 res @ None | res @ Some(Res::Local(_)) => {
2947 let canonical_id = match res {
2948 Some(Res::Local(id)) => id,
2952 hir::PatKind::Binding(
2953 self.lower_binding_mode(binding_mode),
2954 self.lower_node_id(canonical_id),
2959 Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
2963 res: self.lower_res(res),
2964 segments: hir_vec![hir::PathSegment::from_ident(ident)],
2970 fn pat_wild_with_node_id_of(&mut self, p: &Pat) -> P<hir::Pat> {
2971 self.pat_with_node_id_of(p, hir::PatKind::Wild)
2974 /// Construct a `Pat` with the `HirId` of `p.id` lowered.
2975 fn pat_with_node_id_of(&mut self, p: &Pat, kind: hir::PatKind) -> P<hir::Pat> {
2977 hir_id: self.lower_node_id(p.id),
2983 /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern.
2984 fn ban_extra_rest_pat(&self, sp: Span, prev_sp: Span, ctx: &str) {
2986 .struct_span_err(sp, &format!("`..` can only be used once per {} pattern", ctx))
2987 .span_label(sp, &format!("can only be used once per {} pattern", ctx))
2988 .span_label(prev_sp, "previously used here")
2992 /// Used to ban the `..` pattern in places it shouldn't be semantically.
2993 fn ban_illegal_rest_pat(&self, sp: Span) -> hir::PatKind {
2995 .struct_span_err(sp, "`..` patterns are not allowed here")
2996 .note("only allowed in tuple, tuple struct, and slice patterns")
2999 // We're not in a list context so `..` can be reasonably treated
3000 // as `_` because it should always be valid and roughly matches the
3001 // intent of `..` (notice that the rest of a single slot is that slot).
3005 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3007 RangeEnd::Included(_) => hir::RangeEnd::Included,
3008 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3012 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3013 self.with_new_scopes(|this| {
3015 hir_id: this.lower_node_id(c.id),
3016 body: this.lower_const_body(c.value.span, Some(&c.value)),
3021 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
3022 let kind = match s.kind {
3023 StmtKind::Local(ref l) => {
3024 let (l, item_ids) = self.lower_local(l);
3025 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
3028 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
3029 self.stmt(s.span, hir::StmtKind::Item(item_id))
3034 hir_id: self.lower_node_id(s.id),
3035 kind: hir::StmtKind::Local(P(l)),
3041 StmtKind::Item(ref it) => {
3042 // Can only use the ID once.
3043 let mut id = Some(s.id);
3044 return self.lower_item_id(it)
3047 let hir_id = id.take()
3048 .map(|id| self.lower_node_id(id))
3049 .unwrap_or_else(|| self.next_id());
3053 kind: hir::StmtKind::Item(item_id),
3059 StmtKind::Expr(ref e) => hir::StmtKind::Expr(P(self.lower_expr(e))),
3060 StmtKind::Semi(ref e) => hir::StmtKind::Semi(P(self.lower_expr(e))),
3061 StmtKind::Mac(..) => panic!("shouldn't exist here"),
3063 smallvec![hir::Stmt {
3064 hir_id: self.lower_node_id(s.id),
3070 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3072 BlockCheckMode::Default => hir::DefaultBlock,
3073 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3077 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3079 BindingMode::ByValue(Mutability::Not) => hir::BindingAnnotation::Unannotated,
3080 BindingMode::ByRef(Mutability::Not) => hir::BindingAnnotation::Ref,
3081 BindingMode::ByValue(Mutability::Mut) => hir::BindingAnnotation::Mutable,
3082 BindingMode::ByRef(Mutability::Mut) => hir::BindingAnnotation::RefMut,
3086 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3088 CompilerGenerated => hir::CompilerGenerated,
3089 UserProvided => hir::UserProvided,
3093 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3095 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3096 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3100 // Helper methods for building HIR.
3102 fn stmt(&mut self, span: Span, kind: hir::StmtKind) -> hir::Stmt {
3103 hir::Stmt { span, kind, hir_id: self.next_id() }
3106 fn stmt_expr(&mut self, span: Span, expr: hir::Expr) -> hir::Stmt {
3107 self.stmt(span, hir::StmtKind::Expr(P(expr)))
3114 init: Option<P<hir::Expr>>,
3116 source: hir::LocalSource,
3118 let local = hir::Local {
3120 hir_id: self.next_id(),
3127 self.stmt(span, hir::StmtKind::Local(P(local)))
3130 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
3131 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
3137 stmts: hir::HirVec<hir::Stmt>,
3138 expr: Option<P<hir::Expr>>,
3143 hir_id: self.next_id(),
3144 rules: hir::DefaultBlock,
3146 targeted_by_break: false,
3150 /// Constructs a `true` or `false` literal pattern.
3151 fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
3152 let expr = self.expr_bool(span, val);
3153 self.pat(span, hir::PatKind::Lit(P(expr)))
3156 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3157 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
3160 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3161 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
3164 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3165 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
3168 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
3169 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
3175 components: &[Symbol],
3176 subpats: hir::HirVec<P<hir::Pat>>,
3178 let path = self.std_path(span, components, None, true);
3179 let qpath = hir::QPath::Resolved(None, P(path));
3180 let pt = if subpats.is_empty() {
3181 hir::PatKind::Path(qpath)
3183 hir::PatKind::TupleStruct(qpath, subpats, None)
3188 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
3189 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
3192 fn pat_ident_binding_mode(
3196 bm: hir::BindingAnnotation,
3197 ) -> (P<hir::Pat>, hir::HirId) {
3198 let hir_id = self.next_id();
3203 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
3210 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
3211 self.pat(span, hir::PatKind::Wild)
3214 fn pat(&mut self, span: Span, kind: hir::PatKind) -> P<hir::Pat> {
3216 hir_id: self.next_id(),
3222 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
3223 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
3224 /// The path is also resolved according to `is_value`.
3228 components: &[Symbol],
3229 params: Option<P<hir::GenericArgs>>,
3232 let ns = if is_value { Namespace::ValueNS } else { Namespace::TypeNS };
3233 let (path, res) = self.resolver.resolve_str_path(span, self.crate_root, components, ns);
3235 let mut segments: Vec<_> = path.segments.iter().map(|segment| {
3236 let res = self.expect_full_res(segment.id);
3238 ident: segment.ident,
3239 hir_id: Some(self.lower_node_id(segment.id)),
3240 res: Some(self.lower_res(res)),
3245 segments.last_mut().unwrap().args = params;
3249 res: res.map_id(|_| panic!("unexpected `NodeId`")),
3250 segments: segments.into(),
3254 fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
3255 let kind = match qpath {
3256 hir::QPath::Resolved(None, path) => {
3257 // Turn trait object paths into `TyKind::TraitObject` instead.
3259 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
3260 let principal = hir::PolyTraitRef {
3261 bound_generic_params: hir::HirVec::new(),
3262 trait_ref: hir::TraitRef {
3269 // The original ID is taken by the `PolyTraitRef`,
3270 // so the `Ty` itself needs a different one.
3271 hir_id = self.next_id();
3272 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
3274 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
3277 _ => hir::TyKind::Path(qpath),
3287 /// Invoked to create the lifetime argument for a type `&T`
3288 /// with no explicit lifetime.
3289 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
3290 match self.anonymous_lifetime_mode {
3291 // Intercept when we are in an impl header or async fn and introduce an in-band
3293 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
3295 AnonymousLifetimeMode::CreateParameter => {
3296 let fresh_name = self.collect_fresh_in_band_lifetime(span);
3298 hir_id: self.next_id(),
3300 name: hir::LifetimeName::Param(fresh_name),
3304 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
3306 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
3310 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
3311 /// return a "error lifetime".
3312 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
3313 let (id, msg, label) = match id {
3314 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
3317 self.resolver.next_node_id(),
3318 "`&` without an explicit lifetime name cannot be used here",
3319 "explicit lifetime name needed here",
3323 let mut err = struct_span_err!(
3330 err.span_label(span, label);
3333 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3336 /// Invoked to create the lifetime argument(s) for a path like
3337 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
3338 /// sorts of cases are deprecated. This may therefore report a warning or an
3339 /// error, depending on the mode.
3340 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
3342 .map(|_| self.elided_path_lifetime(span))
3346 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
3347 match self.anonymous_lifetime_mode {
3348 AnonymousLifetimeMode::CreateParameter => {
3349 // We should have emitted E0726 when processing this path above
3350 self.sess.delay_span_bug(
3352 "expected 'implicit elided lifetime not allowed' error",
3354 let id = self.resolver.next_node_id();
3355 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3357 // `PassThrough` is the normal case.
3358 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
3359 // is unsuitable here, as these can occur from missing lifetime parameters in a
3360 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
3361 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
3362 // later, at which point a suitable error will be emitted.
3363 | AnonymousLifetimeMode::PassThrough
3364 | AnonymousLifetimeMode::ReportError => self.new_implicit_lifetime(span),
3368 /// Invoked to create the lifetime argument(s) for an elided trait object
3369 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
3370 /// when the bound is written, even if it is written with `'_` like in
3371 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
3372 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
3373 match self.anonymous_lifetime_mode {
3374 // NB. We intentionally ignore the create-parameter mode here.
3375 // and instead "pass through" to resolve-lifetimes, which will apply
3376 // the object-lifetime-defaulting rules. Elided object lifetime defaults
3377 // do not act like other elided lifetimes. In other words, given this:
3379 // impl Foo for Box<dyn Debug>
3381 // we do not introduce a fresh `'_` to serve as the bound, but instead
3382 // ultimately translate to the equivalent of:
3384 // impl Foo for Box<dyn Debug + 'static>
3386 // `resolve_lifetime` has the code to make that happen.
3387 AnonymousLifetimeMode::CreateParameter => {}
3389 AnonymousLifetimeMode::ReportError => {
3390 // ReportError applies to explicit use of `'_`.
3393 // This is the normal case.
3394 AnonymousLifetimeMode::PassThrough => {}
3397 let r = hir::Lifetime {
3398 hir_id: self.next_id(),
3400 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
3402 debug!("elided_dyn_bound: r={:?}", r);
3406 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
3408 hir_id: self.next_id(),
3410 name: hir::LifetimeName::Implicit,
3414 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
3415 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
3416 // call site which do not have a macro backtrace. See #61963.
3417 let is_macro_callsite = self.sess.source_map()
3418 .span_to_snippet(span)
3419 .map(|snippet| snippet.starts_with("#["))
3421 if !is_macro_callsite {
3422 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
3423 builtin::BARE_TRAIT_OBJECTS,
3426 "trait objects without an explicit `dyn` are deprecated",
3427 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
3433 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body<'hir>>) -> Vec<hir::BodyId> {
3434 // Sorting by span ensures that we get things in order within a
3435 // file, and also puts the files in a sensible order.
3436 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
3437 body_ids.sort_by_key(|b| bodies[b].value.span);