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>,
101 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
102 bodies: BTreeMap<hir::BodyId, hir::Body>,
103 exported_macros: Vec<hir::MacroDef>,
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_extendable(&mut self, attrs: &[Attribute]) -> Vec<Attribute> {
995 .map(|a| self.lower_attr(a))
999 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1000 self.lower_attrs_extendable(attrs).into()
1003 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1004 // Note that we explicitly do not walk the path. Since we don't really
1005 // lower attributes (we use the AST version) there is nowhere to keep
1006 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1007 let kind = match attr.kind {
1008 AttrKind::Normal(ref item) => {
1009 AttrKind::Normal(AttrItem {
1010 path: item.path.clone(),
1011 args: self.lower_mac_args(&item.args),
1014 AttrKind::DocComment(comment) => AttrKind::DocComment(comment)
1025 fn lower_mac_args(&mut self, args: &MacArgs) -> MacArgs {
1027 MacArgs::Empty => MacArgs::Empty,
1028 MacArgs::Delimited(dspan, delim, ref tokens) =>
1029 MacArgs::Delimited(dspan, delim, self.lower_token_stream(tokens.clone())),
1030 MacArgs::Eq(eq_span, ref tokens) =>
1031 MacArgs::Eq(eq_span, self.lower_token_stream(tokens.clone())),
1035 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1038 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1042 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1044 TokenTree::Token(token) => self.lower_token(token),
1045 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1048 self.lower_token_stream(tts),
1053 fn lower_token(&mut self, token: Token) -> TokenStream {
1055 token::Interpolated(nt) => {
1056 let tts = (self.nt_to_tokenstream)(&nt, &self.sess.parse_sess, token.span);
1057 self.lower_token_stream(tts)
1059 _ => TokenTree::Token(token).into(),
1063 /// Given an associated type constraint like one of these:
1066 /// T: Iterator<Item: Debug>
1068 /// T: Iterator<Item = Debug>
1072 /// returns a `hir::TypeBinding` representing `Item`.
1073 fn lower_assoc_ty_constraint(
1075 constraint: &AssocTyConstraint,
1076 itctx: ImplTraitContext<'_>,
1077 ) -> hir::TypeBinding {
1078 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1080 let kind = match constraint.kind {
1081 AssocTyConstraintKind::Equality { ref ty } => hir::TypeBindingKind::Equality {
1082 ty: self.lower_ty(ty, itctx)
1084 AssocTyConstraintKind::Bound { ref bounds } => {
1085 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1086 let (desugar_to_impl_trait, itctx) = match itctx {
1087 // We are in the return position:
1089 // fn foo() -> impl Iterator<Item: Debug>
1093 // fn foo() -> impl Iterator<Item = impl Debug>
1094 ImplTraitContext::OpaqueTy(_) => (true, itctx),
1096 // We are in the argument position, but within a dyn type:
1098 // fn foo(x: dyn Iterator<Item: Debug>)
1102 // fn foo(x: dyn Iterator<Item = impl Debug>)
1103 ImplTraitContext::Universal(_) if self.is_in_dyn_type => (true, itctx),
1105 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1106 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1107 // "impl trait context" to permit `impl Debug` in this position (it desugars
1108 // then to an opaque type).
1110 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1111 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type =>
1112 (true, ImplTraitContext::OpaqueTy(None)),
1114 // We are in the parameter position, but not within a dyn type:
1116 // fn foo(x: impl Iterator<Item: Debug>)
1118 // so we leave it as is and this gets expanded in astconv to a bound like
1119 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1121 _ => (false, itctx),
1124 if desugar_to_impl_trait {
1125 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1126 // constructing the HIR for `impl bounds...` and then lowering that.
1128 let impl_trait_node_id = self.resolver.next_node_id();
1129 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1130 self.resolver.definitions().create_def_with_parent(
1133 DefPathData::ImplTrait,
1138 self.with_dyn_type_scope(false, |this| {
1139 let node_id = this.resolver.next_node_id();
1140 let ty = this.lower_ty(
1143 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1144 span: constraint.span,
1149 hir::TypeBindingKind::Equality {
1154 // Desugar `AssocTy: Bounds` into a type binding where the
1155 // later desugars into a trait predicate.
1156 let bounds = self.lower_param_bounds(bounds, itctx);
1158 hir::TypeBindingKind::Constraint {
1166 hir_id: self.lower_node_id(constraint.id),
1167 ident: constraint.ident,
1169 span: constraint.span,
1173 fn lower_generic_arg(
1175 arg: &ast::GenericArg,
1176 itctx: ImplTraitContext<'_>
1177 ) -> hir::GenericArg {
1179 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1180 ast::GenericArg::Type(ty) => {
1181 // We parse const arguments as path types as we cannot distiguish them durring
1182 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1183 // type and value namespaces. If we resolved the path in the value namespace, we
1184 // transform it into a generic const argument.
1185 if let TyKind::Path(ref qself, ref path) = ty.kind {
1186 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1187 let res = partial_res.base_res();
1188 if !res.matches_ns(Namespace::TypeNS) {
1190 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1194 // Construct a AnonConst where the expr is the "ty"'s path.
1196 let parent_def_index =
1197 self.current_hir_id_owner.last().unwrap().0;
1198 let node_id = self.resolver.next_node_id();
1200 // Add a definition for the in-band const def.
1201 self.resolver.definitions().create_def_with_parent(
1204 DefPathData::AnonConst,
1209 let path_expr = Expr {
1211 kind: ExprKind::Path(qself.clone(), path.clone()),
1213 attrs: AttrVec::new(),
1216 let ct = self.with_new_scopes(|this| {
1218 hir_id: this.lower_node_id(node_id),
1219 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1222 return GenericArg::Const(ConstArg {
1229 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1231 ast::GenericArg::Const(ct) => {
1232 GenericArg::Const(ConstArg {
1233 value: self.lower_anon_const(&ct),
1234 span: ct.value.span,
1240 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1241 P(self.lower_ty_direct(t, itctx))
1247 qself: &Option<QSelf>,
1249 param_mode: ParamMode,
1250 itctx: ImplTraitContext<'_>
1252 let id = self.lower_node_id(t.id);
1253 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1254 let ty = self.ty_path(id, t.span, qpath);
1255 if let hir::TyKind::TraitObject(..) = ty.kind {
1256 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1261 fn ty(&mut self, span: Span, kind: hir::TyKind) -> hir::Ty {
1262 hir::Ty { hir_id: self.next_id(), kind, span }
1265 fn ty_tup(&mut self, span: Span, tys: HirVec<hir::Ty>) -> hir::Ty {
1266 self.ty(span, hir::TyKind::Tup(tys))
1269 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1270 let kind = match t.kind {
1271 TyKind::Infer => hir::TyKind::Infer,
1272 TyKind::Err => hir::TyKind::Err,
1273 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1274 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1275 TyKind::Rptr(ref region, ref mt) => {
1276 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1277 let lifetime = match *region {
1278 Some(ref lt) => self.lower_lifetime(lt),
1279 None => self.elided_ref_lifetime(span),
1281 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1283 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1286 this.with_anonymous_lifetime_mode(
1287 AnonymousLifetimeMode::PassThrough,
1289 hir::TyKind::BareFn(P(hir::BareFnTy {
1290 generic_params: this.lower_generic_params(
1292 &NodeMap::default(),
1293 ImplTraitContext::disallowed(),
1295 unsafety: f.unsafety,
1296 abi: this.lower_extern(f.ext),
1297 decl: this.lower_fn_decl(&f.decl, None, false, None),
1298 param_names: this.lower_fn_params_to_names(&f.decl),
1304 TyKind::Never => hir::TyKind::Never,
1305 TyKind::Tup(ref tys) => {
1306 hir::TyKind::Tup(tys.iter().map(|ty| {
1307 self.lower_ty_direct(ty, itctx.reborrow())
1310 TyKind::Paren(ref ty) => {
1311 return self.lower_ty_direct(ty, itctx);
1313 TyKind::Path(ref qself, ref path) => {
1314 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1316 TyKind::ImplicitSelf => {
1317 let res = self.expect_full_res(t.id);
1318 let res = self.lower_res(res);
1319 hir::TyKind::Path(hir::QPath::Resolved(
1323 segments: hir_vec![hir::PathSegment::from_ident(
1324 Ident::with_dummy_span(kw::SelfUpper)
1330 TyKind::Array(ref ty, ref length) => {
1331 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1333 TyKind::Typeof(ref expr) => {
1334 hir::TyKind::Typeof(self.lower_anon_const(expr))
1336 TyKind::TraitObject(ref bounds, kind) => {
1337 let mut lifetime_bound = None;
1338 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1341 .filter_map(|bound| match *bound {
1342 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1343 Some(this.lower_poly_trait_ref(ty, itctx.reborrow()))
1345 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1346 GenericBound::Outlives(ref lifetime) => {
1347 if lifetime_bound.is_none() {
1348 lifetime_bound = Some(this.lower_lifetime(lifetime));
1354 let lifetime_bound =
1355 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1356 (bounds, lifetime_bound)
1358 if kind != TraitObjectSyntax::Dyn {
1359 self.maybe_lint_bare_trait(t.span, t.id, false);
1361 hir::TyKind::TraitObject(bounds, lifetime_bound)
1363 TyKind::ImplTrait(def_node_id, ref bounds) => {
1366 ImplTraitContext::OpaqueTy(fn_def_id) => {
1367 self.lower_opaque_impl_trait(
1368 span, fn_def_id, def_node_id,
1369 |this| this.lower_param_bounds(bounds, itctx),
1372 ImplTraitContext::Universal(in_band_ty_params) => {
1373 // Add a definition for the in-band `Param`.
1374 let def_index = self
1377 .opt_def_index(def_node_id)
1380 let hir_bounds = self.lower_param_bounds(
1382 ImplTraitContext::Universal(in_band_ty_params),
1384 // Set the name to `impl Bound1 + Bound2`.
1385 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1386 in_band_ty_params.push(hir::GenericParam {
1387 hir_id: self.lower_node_id(def_node_id),
1388 name: ParamName::Plain(ident),
1389 pure_wrt_drop: false,
1393 kind: hir::GenericParamKind::Type {
1395 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1399 hir::TyKind::Path(hir::QPath::Resolved(
1403 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1404 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1408 ImplTraitContext::Disallowed(pos) => {
1409 let allowed_in = if self.sess.features_untracked()
1410 .impl_trait_in_bindings {
1411 "bindings or function and inherent method return types"
1413 "function and inherent method return types"
1415 let mut err = struct_span_err!(
1419 "`impl Trait` not allowed outside of {}",
1422 if pos == ImplTraitPosition::Binding &&
1423 nightly_options::is_nightly_build() {
1425 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1426 attributes to enable");
1433 TyKind::Mac(_) => bug!("`TyKind::Mac` should have been expanded by now"),
1434 TyKind::CVarArgs => {
1435 self.sess.delay_span_bug(
1437 "`TyKind::CVarArgs` should have been handled elsewhere",
1446 hir_id: self.lower_node_id(t.id),
1450 fn lower_opaque_impl_trait(
1453 fn_def_id: Option<DefId>,
1454 opaque_ty_node_id: NodeId,
1455 lower_bounds: impl FnOnce(&mut LoweringContext<'_, '_>) -> hir::GenericBounds,
1458 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1464 // Make sure we know that some funky desugaring has been going on here.
1465 // This is a first: there is code in other places like for loop
1466 // desugaring that explicitly states that we don't want to track that.
1467 // Not tracking it makes lints in rustc and clippy very fragile, as
1468 // frequently opened issues show.
1469 let opaque_ty_span = self.mark_span_with_reason(
1470 DesugaringKind::OpaqueTy,
1475 let opaque_ty_def_index = self
1478 .opt_def_index(opaque_ty_node_id)
1481 self.allocate_hir_id_counter(opaque_ty_node_id);
1483 let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
1485 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1487 opaque_ty_def_index,
1492 "lower_opaque_impl_trait: lifetimes={:#?}", lifetimes,
1496 "lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs,
1499 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1500 let opaque_ty_item = hir::OpaqueTy {
1501 generics: hir::Generics {
1502 params: lifetime_defs,
1503 where_clause: hir::WhereClause {
1504 predicates: hir_vec![],
1510 impl_trait_fn: fn_def_id,
1511 origin: hir::OpaqueTyOrigin::FnReturn,
1514 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_index);
1515 let opaque_ty_id = lctx.generate_opaque_type(
1522 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1523 hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, lifetimes)
1527 /// Registers a new opaque type with the proper `NodeId`s and
1528 /// returns the lowered node-ID for the opaque type.
1529 fn generate_opaque_type(
1531 opaque_ty_node_id: NodeId,
1532 opaque_ty_item: hir::OpaqueTy,
1534 opaque_ty_span: Span,
1536 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1537 let opaque_ty_id = self.lower_node_id(opaque_ty_node_id);
1538 // Generate an `type Foo = impl Trait;` declaration.
1539 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1540 let opaque_ty_item = hir::Item {
1541 hir_id: opaque_ty_id,
1542 ident: Ident::invalid(),
1543 attrs: Default::default(),
1544 kind: opaque_ty_item_kind,
1545 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1546 span: opaque_ty_span,
1549 // Insert the item into the global item list. This usually happens
1550 // automatically for all AST items. But this opaque type item
1551 // does not actually exist in the AST.
1552 self.insert_item(opaque_ty_item);
1556 fn lifetimes_from_impl_trait_bounds(
1558 opaque_ty_id: NodeId,
1559 parent_index: DefIndex,
1560 bounds: &hir::GenericBounds,
1561 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1563 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
1564 parent_index={:?}, \
1566 opaque_ty_id, parent_index, bounds,
1569 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1570 // appear in the bounds, excluding lifetimes that are created within the bounds.
1571 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1572 struct ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1573 context: &'r mut LoweringContext<'a, 'hir>,
1575 opaque_ty_id: NodeId,
1576 collect_elided_lifetimes: bool,
1577 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1578 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1579 output_lifetimes: Vec<hir::GenericArg>,
1580 output_lifetime_params: Vec<hir::GenericParam>,
1583 impl<'r, 'a, 'v, 'hir> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1584 fn nested_visit_map<'this>(
1586 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1587 hir::intravisit::NestedVisitorMap::None
1590 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1591 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1592 if parameters.parenthesized {
1593 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1594 self.collect_elided_lifetimes = false;
1595 hir::intravisit::walk_generic_args(self, span, parameters);
1596 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1598 hir::intravisit::walk_generic_args(self, span, parameters);
1602 fn visit_ty(&mut self, t: &'v hir::Ty) {
1603 // Don't collect elided lifetimes used inside of `fn()` syntax.
1604 if let hir::TyKind::BareFn(_) = t.kind {
1605 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1606 self.collect_elided_lifetimes = false;
1608 // Record the "stack height" of `for<'a>` lifetime bindings
1609 // to be able to later fully undo their introduction.
1610 let old_len = self.currently_bound_lifetimes.len();
1611 hir::intravisit::walk_ty(self, t);
1612 self.currently_bound_lifetimes.truncate(old_len);
1614 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1616 hir::intravisit::walk_ty(self, t)
1620 fn visit_poly_trait_ref(
1622 trait_ref: &'v hir::PolyTraitRef,
1623 modifier: hir::TraitBoundModifier,
1625 // Record the "stack height" of `for<'a>` lifetime bindings
1626 // to be able to later fully undo their introduction.
1627 let old_len = self.currently_bound_lifetimes.len();
1628 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1629 self.currently_bound_lifetimes.truncate(old_len);
1632 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1633 // Record the introduction of 'a in `for<'a> ...`.
1634 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1635 // Introduce lifetimes one at a time so that we can handle
1636 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1637 let lt_name = hir::LifetimeName::Param(param.name);
1638 self.currently_bound_lifetimes.push(lt_name);
1641 hir::intravisit::walk_generic_param(self, param);
1644 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1645 let name = match lifetime.name {
1646 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1647 if self.collect_elided_lifetimes {
1648 // Use `'_` for both implicit and underscore lifetimes in
1649 // `type Foo<'_> = impl SomeTrait<'_>;`.
1650 hir::LifetimeName::Underscore
1655 hir::LifetimeName::Param(_) => lifetime.name,
1657 // Refers to some other lifetime that is "in
1658 // scope" within the type.
1659 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1661 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1664 if !self.currently_bound_lifetimes.contains(&name)
1665 && !self.already_defined_lifetimes.contains(&name) {
1666 self.already_defined_lifetimes.insert(name);
1668 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1669 hir_id: self.context.next_id(),
1670 span: lifetime.span,
1674 let def_node_id = self.context.resolver.next_node_id();
1676 self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1677 self.context.resolver.definitions().create_def_with_parent(
1680 DefPathData::LifetimeNs(name.ident().name),
1684 let (name, kind) = match name {
1685 hir::LifetimeName::Underscore => (
1686 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1687 hir::LifetimeParamKind::Elided,
1689 hir::LifetimeName::Param(param_name) => (
1691 hir::LifetimeParamKind::Explicit,
1693 _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1696 self.output_lifetime_params.push(hir::GenericParam {
1699 span: lifetime.span,
1700 pure_wrt_drop: false,
1703 kind: hir::GenericParamKind::Lifetime { kind }
1709 let mut lifetime_collector = ImplTraitLifetimeCollector {
1711 parent: parent_index,
1713 collect_elided_lifetimes: true,
1714 currently_bound_lifetimes: Vec::new(),
1715 already_defined_lifetimes: FxHashSet::default(),
1716 output_lifetimes: Vec::new(),
1717 output_lifetime_params: Vec::new(),
1720 for bound in bounds {
1721 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1725 lifetime_collector.output_lifetimes.into(),
1726 lifetime_collector.output_lifetime_params.into(),
1733 qself: &Option<QSelf>,
1735 param_mode: ParamMode,
1736 mut itctx: ImplTraitContext<'_>,
1738 let qself_position = qself.as_ref().map(|q| q.position);
1739 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1741 let partial_res = self.resolver
1742 .get_partial_res(id)
1743 .unwrap_or_else(|| PartialRes::new(Res::Err));
1745 let proj_start = p.segments.len() - partial_res.unresolved_segments();
1746 let path = P(hir::Path {
1747 res: self.lower_res(partial_res.base_res()),
1748 segments: p.segments[..proj_start]
1751 .map(|(i, segment)| {
1752 let param_mode = match (qself_position, param_mode) {
1753 (Some(j), ParamMode::Optional) if i < j => {
1754 // This segment is part of the trait path in a
1755 // qualified path - one of `a`, `b` or `Trait`
1756 // in `<X as a::b::Trait>::T::U::method`.
1762 // Figure out if this is a type/trait segment,
1763 // which may need lifetime elision performed.
1764 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1765 krate: def_id.krate,
1766 index: this.def_key(def_id).parent.expect("missing parent"),
1768 let type_def_id = match partial_res.base_res() {
1769 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1770 Some(parent_def_id(self, def_id))
1772 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1773 Some(parent_def_id(self, def_id))
1775 Res::Def(DefKind::Struct, def_id)
1776 | Res::Def(DefKind::Union, def_id)
1777 | Res::Def(DefKind::Enum, def_id)
1778 | Res::Def(DefKind::TyAlias, def_id)
1779 | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
1785 let parenthesized_generic_args = match partial_res.base_res() {
1786 // `a::b::Trait(Args)`
1787 Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
1788 ParenthesizedGenericArgs::Ok
1790 // `a::b::Trait(Args)::TraitItem`
1791 Res::Def(DefKind::Method, _) |
1792 Res::Def(DefKind::AssocConst, _) |
1793 Res::Def(DefKind::AssocTy, _) if i + 2 == proj_start => {
1794 ParenthesizedGenericArgs::Ok
1796 // Avoid duplicated errors.
1797 Res::Err => ParenthesizedGenericArgs::Ok,
1799 _ => ParenthesizedGenericArgs::Err,
1802 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1803 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1806 assert!(!def_id.is_local());
1807 let item_generics = self.resolver.cstore()
1808 .item_generics_cloned_untracked(def_id, self.sess);
1809 let n = item_generics.own_counts().lifetimes;
1810 self.type_def_lifetime_params.insert(def_id, n);
1813 self.lower_path_segment(
1818 parenthesized_generic_args,
1827 // Simple case, either no projections, or only fully-qualified.
1828 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1829 if partial_res.unresolved_segments() == 0 {
1830 return hir::QPath::Resolved(qself, path);
1833 // Create the innermost type that we're projecting from.
1834 let mut ty = if path.segments.is_empty() {
1835 // If the base path is empty that means there exists a
1836 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1837 qself.expect("missing QSelf for <T>::...")
1839 // Otherwise, the base path is an implicit `Self` type path,
1840 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1841 // `<I as Iterator>::Item::default`.
1842 let new_id = self.next_id();
1843 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1846 // Anything after the base path are associated "extensions",
1847 // out of which all but the last one are associated types,
1848 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1849 // * base path is `std::vec::Vec<T>`
1850 // * "extensions" are `IntoIter`, `Item` and `clone`
1851 // * type nodes are:
1852 // 1. `std::vec::Vec<T>` (created above)
1853 // 2. `<std::vec::Vec<T>>::IntoIter`
1854 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1855 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1856 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1857 let segment = P(self.lower_path_segment(
1862 ParenthesizedGenericArgs::Err,
1866 let qpath = hir::QPath::TypeRelative(ty, segment);
1868 // It's finished, return the extension of the right node type.
1869 if i == p.segments.len() - 1 {
1873 // Wrap the associated extension in another type node.
1874 let new_id = self.next_id();
1875 ty = P(self.ty_path(new_id, p.span, qpath));
1878 // We should've returned in the for loop above.
1881 "lower_qpath: no final extension segment in {}..{}",
1887 fn lower_path_extra(
1891 param_mode: ParamMode,
1892 explicit_owner: Option<NodeId>,
1896 segments: p.segments
1899 self.lower_path_segment(
1904 ParenthesizedGenericArgs::Err,
1905 ImplTraitContext::disallowed(),
1914 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1915 let res = self.expect_full_res(id);
1916 let res = self.lower_res(res);
1917 self.lower_path_extra(res, p, param_mode, None)
1920 fn lower_path_segment(
1923 segment: &PathSegment,
1924 param_mode: ParamMode,
1925 expected_lifetimes: usize,
1926 parenthesized_generic_args: ParenthesizedGenericArgs,
1927 itctx: ImplTraitContext<'_>,
1928 explicit_owner: Option<NodeId>,
1929 ) -> hir::PathSegment {
1930 let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
1931 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
1932 match **generic_args {
1933 GenericArgs::AngleBracketed(ref data) => {
1934 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1936 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1937 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1938 ParenthesizedGenericArgs::Err => {
1939 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
1940 err.span_label(data.span, "only `Fn` traits may use parentheses");
1941 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
1942 // Do not suggest going from `Trait()` to `Trait<>`
1943 if data.inputs.len() > 0 {
1944 if let Some(split) = snippet.find('(') {
1945 let trait_name = &snippet[0..split];
1946 let args = &snippet[split + 1 .. snippet.len() - 1];
1947 err.span_suggestion(
1949 "use angle brackets instead",
1950 format!("{}<{}>", trait_name, args),
1951 Applicability::MaybeIncorrect,
1958 self.lower_angle_bracketed_parameter_data(
1959 &data.as_angle_bracketed_args(),
1969 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1972 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1973 GenericArg::Lifetime(_) => true,
1976 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1977 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1978 if !generic_args.parenthesized && !has_lifetimes {
1980 self.elided_path_lifetimes(path_span, expected_lifetimes)
1982 .map(|lt| GenericArg::Lifetime(lt))
1983 .chain(generic_args.args.into_iter())
1985 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1986 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1987 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
1988 let no_bindings = generic_args.bindings.is_empty();
1989 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
1990 // If there are no (non-implicit) generic args or associated type
1991 // bindings, our suggestion includes the angle brackets.
1992 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1994 // Otherwise (sorry, this is kind of gross) we need to infer the
1995 // place to splice in the `'_, ` from the generics that do exist.
1996 let first_generic_span = first_generic_span
1997 .expect("already checked that non-lifetime args or bindings exist");
1998 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
2000 match self.anonymous_lifetime_mode {
2001 // In create-parameter mode we error here because we don't want to support
2002 // deprecated impl elision in new features like impl elision and `async fn`,
2003 // both of which work using the `CreateParameter` mode:
2005 // impl Foo for std::cell::Ref<u32> // note lack of '_
2006 // async fn foo(_: std::cell::Ref<u32>) { ... }
2007 AnonymousLifetimeMode::CreateParameter => {
2008 let mut err = struct_span_err!(
2012 "implicit elided lifetime not allowed here"
2014 crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
2025 AnonymousLifetimeMode::PassThrough |
2026 AnonymousLifetimeMode::ReportError => {
2027 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2028 ELIDED_LIFETIMES_IN_PATHS,
2031 "hidden lifetime parameters in types are deprecated",
2032 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2045 let res = self.expect_full_res(segment.id);
2046 let id = if let Some(owner) = explicit_owner {
2047 self.lower_node_id_with_owner(segment.id, owner)
2049 self.lower_node_id(segment.id)
2052 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2053 segment.ident, segment.id, id,
2056 hir::PathSegment::new(
2059 Some(self.lower_res(res)),
2065 fn lower_angle_bracketed_parameter_data(
2067 data: &AngleBracketedArgs,
2068 param_mode: ParamMode,
2069 mut itctx: ImplTraitContext<'_>,
2070 ) -> (hir::GenericArgs, bool) {
2071 let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
2072 let has_non_lt_args = args.iter().any(|arg| match arg {
2073 ast::GenericArg::Lifetime(_) => false,
2074 ast::GenericArg::Type(_) => true,
2075 ast::GenericArg::Const(_) => true,
2079 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2080 bindings: constraints.iter()
2081 .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow()))
2083 parenthesized: false,
2085 !has_non_lt_args && param_mode == ParamMode::Optional
2089 fn lower_parenthesized_parameter_data(
2091 data: &ParenthesizedArgs,
2092 ) -> (hir::GenericArgs, bool) {
2093 // Switch to `PassThrough` mode for anonymous lifetimes; this
2094 // means that we permit things like `&Ref<T>`, where `Ref` has
2095 // a hidden lifetime parameter. This is needed for backwards
2096 // compatibility, even in contexts like an impl header where
2097 // we generally don't permit such things (see #51008).
2098 self.with_anonymous_lifetime_mode(
2099 AnonymousLifetimeMode::PassThrough,
2101 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2104 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2106 let output_ty = match output {
2107 FunctionRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()),
2108 FunctionRetTy::Default(_) => P(this.ty_tup(span, hir::HirVec::new())),
2110 let args = hir_vec![GenericArg::Type(this.ty_tup(span, inputs))];
2111 let binding = hir::TypeBinding {
2112 hir_id: this.next_id(),
2113 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2114 span: output_ty.span,
2115 kind: hir::TypeBindingKind::Equality { ty: output_ty },
2118 hir::GenericArgs { args, bindings: hir_vec![binding], parenthesized: true },
2125 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2126 let mut ids = SmallVec::<[NodeId; 1]>::new();
2127 if self.sess.features_untracked().impl_trait_in_bindings {
2128 if let Some(ref ty) = l.ty {
2129 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2130 visitor.visit_ty(ty);
2133 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2135 hir_id: self.lower_node_id(l.id),
2138 .map(|t| self.lower_ty(t,
2139 if self.sess.features_untracked().impl_trait_in_bindings {
2140 ImplTraitContext::OpaqueTy(Some(parent_def_id))
2142 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2145 pat: self.lower_pat(&l.pat),
2146 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2148 attrs: l.attrs.clone(),
2149 source: hir::LocalSource::Normal,
2153 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2154 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2155 // as they are not explicit in HIR/Ty function signatures.
2156 // (instead, the `c_variadic` flag is set to `true`)
2157 let mut inputs = &decl.inputs[..];
2158 if decl.c_variadic() {
2159 inputs = &inputs[..inputs.len() - 1];
2163 .map(|param| match param.pat.kind {
2164 PatKind::Ident(_, ident, _) => ident,
2165 _ => Ident::new(kw::Invalid, param.pat.span),
2170 // Lowers a function declaration.
2172 // `decl`: the unlowered (AST) function declaration.
2173 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2174 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2175 // `make_ret_async` is also `Some`.
2176 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2177 // This guards against trait declarations and implementations where `impl Trait` is
2179 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2180 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2181 // return type `impl Trait` item.
2185 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2186 impl_trait_return_allow: bool,
2187 make_ret_async: Option<NodeId>,
2188 ) -> P<hir::FnDecl> {
2189 debug!("lower_fn_decl(\
2191 in_band_ty_params: {:?}, \
2192 impl_trait_return_allow: {}, \
2193 make_ret_async: {:?})",
2196 impl_trait_return_allow,
2199 let lt_mode = if make_ret_async.is_some() {
2200 // In `async fn`, argument-position elided lifetimes
2201 // must be transformed into fresh generic parameters so that
2202 // they can be applied to the opaque `impl Trait` return type.
2203 AnonymousLifetimeMode::CreateParameter
2205 self.anonymous_lifetime_mode
2208 let c_variadic = decl.c_variadic();
2210 // Remember how many lifetimes were already around so that we can
2211 // only look at the lifetime parameters introduced by the arguments.
2212 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2213 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2214 // as they are not explicit in HIR/Ty function signatures.
2215 // (instead, the `c_variadic` flag is set to `true`)
2216 let mut inputs = &decl.inputs[..];
2218 inputs = &inputs[..inputs.len() - 1];
2223 if let Some((_, ibty)) = &mut in_band_ty_params {
2224 this.lower_ty_direct(¶m.ty, ImplTraitContext::Universal(ibty))
2226 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
2229 .collect::<HirVec<_>>()
2232 let output = if let Some(ret_id) = make_ret_async {
2233 self.lower_async_fn_ret_ty(
2235 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2240 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2241 Some((def_id, _)) if impl_trait_return_allow => {
2242 hir::Return(self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(def_id))))
2245 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2248 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2256 implicit_self: decl.inputs.get(0).map_or(
2257 hir::ImplicitSelfKind::None,
2259 let is_mutable_pat = match arg.pat.kind {
2260 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2261 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2262 mt == Mutability::Mut,
2267 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2268 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2269 // Given we are only considering `ImplicitSelf` types, we needn't consider
2270 // the case where we have a mutable pattern to a reference as that would
2271 // no longer be an `ImplicitSelf`.
2272 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() &&
2273 mt.mutbl == ast::Mutability::Mut =>
2274 hir::ImplicitSelfKind::MutRef,
2275 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() =>
2276 hir::ImplicitSelfKind::ImmRef,
2277 _ => hir::ImplicitSelfKind::None,
2284 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
2285 // combined with the following definition of `OpaqueTy`:
2287 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
2289 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
2290 // `output`: unlowered output type (`T` in `-> T`)
2291 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2292 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
2293 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2294 fn lower_async_fn_ret_ty(
2296 output: &FunctionRetTy,
2298 opaque_ty_node_id: NodeId,
2299 ) -> hir::FunctionRetTy {
2301 "lower_async_fn_ret_ty(\
2304 opaque_ty_node_id={:?})",
2305 output, fn_def_id, opaque_ty_node_id,
2308 let span = output.span();
2310 let opaque_ty_span = self.mark_span_with_reason(
2311 DesugaringKind::Async,
2316 let opaque_ty_def_index = self
2319 .opt_def_index(opaque_ty_node_id)
2322 self.allocate_hir_id_counter(opaque_ty_node_id);
2324 // When we create the opaque type for this async fn, it is going to have
2325 // to capture all the lifetimes involved in the signature (including in the
2326 // return type). This is done by introducing lifetime parameters for:
2328 // - all the explicitly declared lifetimes from the impl and function itself;
2329 // - all the elided lifetimes in the fn arguments;
2330 // - all the elided lifetimes in the return type.
2332 // So for example in this snippet:
2335 // impl<'a> Foo<'a> {
2336 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
2337 // // ^ '0 ^ '1 ^ '2
2338 // // elided lifetimes used below
2343 // we would create an opaque type like:
2346 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
2349 // and we would then desugar `bar` to the equivalent of:
2352 // impl<'a> Foo<'a> {
2353 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
2357 // Note that the final parameter to `Bar` is `'_`, not `'2` --
2358 // this is because the elided lifetimes from the return type
2359 // should be figured out using the ordinary elision rules, and
2360 // this desugaring achieves that.
2362 // The variable `input_lifetimes_count` tracks the number of
2363 // lifetime parameters to the opaque type *not counting* those
2364 // lifetimes elided in the return type. This includes those
2365 // that are explicitly declared (`in_scope_lifetimes`) and
2366 // those elided lifetimes we found in the arguments (current
2367 // content of `lifetimes_to_define`). Next, we will process
2368 // the return type, which will cause `lifetimes_to_define` to
2370 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
2372 let (opaque_ty_id, lifetime_params) = self.with_hir_id_owner(opaque_ty_node_id, |this| {
2373 // We have to be careful to get elision right here. The
2374 // idea is that we create a lifetime parameter for each
2375 // lifetime in the return type. So, given a return type
2376 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
2377 // Future<Output = &'1 [ &'2 u32 ]>`.
2379 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
2380 // hence the elision takes place at the fn site.
2381 let future_bound = this.with_anonymous_lifetime_mode(
2382 AnonymousLifetimeMode::CreateParameter,
2383 |this| this.lower_async_fn_output_type_to_future_bound(
2390 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
2392 // Calculate all the lifetimes that should be captured
2393 // by the opaque type. This should include all in-scope
2394 // lifetime parameters, including those defined in-band.
2396 // Note: this must be done after lowering the output type,
2397 // as the output type may introduce new in-band lifetimes.
2398 let lifetime_params: Vec<(Span, ParamName)> =
2399 this.in_scope_lifetimes
2401 .map(|name| (name.ident().span, name))
2402 .chain(this.lifetimes_to_define.iter().cloned())
2405 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
2406 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
2407 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
2409 let generic_params =
2412 .map(|(span, hir_name)| {
2413 this.lifetime_to_generic_param(span, hir_name, opaque_ty_def_index)
2417 let opaque_ty_item = hir::OpaqueTy {
2418 generics: hir::Generics {
2419 params: generic_params,
2420 where_clause: hir::WhereClause {
2421 predicates: hir_vec![],
2426 bounds: hir_vec![future_bound],
2427 impl_trait_fn: Some(fn_def_id),
2428 origin: hir::OpaqueTyOrigin::AsyncFn,
2431 trace!("exist ty from async fn def index: {:#?}", opaque_ty_def_index);
2432 let opaque_ty_id = this.generate_opaque_type(
2439 (opaque_ty_id, lifetime_params)
2442 // As documented above on the variable
2443 // `input_lifetimes_count`, we need to create the lifetime
2444 // arguments to our opaque type. Continuing with our example,
2445 // we're creating the type arguments for the return type:
2448 // Bar<'a, 'b, '0, '1, '_>
2451 // For the "input" lifetime parameters, we wish to create
2452 // references to the parameters themselves, including the
2453 // "implicit" ones created from parameter types (`'a`, `'b`,
2456 // For the "output" lifetime parameters, we just want to
2458 let mut generic_args: Vec<_> =
2459 lifetime_params[..input_lifetimes_count]
2461 .map(|&(span, hir_name)| {
2462 // Input lifetime like `'a` or `'1`:
2463 GenericArg::Lifetime(hir::Lifetime {
2464 hir_id: self.next_id(),
2466 name: hir::LifetimeName::Param(hir_name),
2470 generic_args.extend(
2471 lifetime_params[input_lifetimes_count..]
2474 // Output lifetime like `'_`.
2475 GenericArg::Lifetime(hir::Lifetime {
2476 hir_id: self.next_id(),
2478 name: hir::LifetimeName::Implicit,
2483 // Create the `Foo<...>` reference itself. Note that the `type
2484 // Foo = impl Trait` is, internally, created as a child of the
2485 // async fn, so the *type parameters* are inherited. It's
2486 // only the lifetime parameters that we must supply.
2487 let opaque_ty_ref = hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, generic_args.into());
2488 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2489 hir::FunctionRetTy::Return(P(opaque_ty))
2492 /// Transforms `-> T` into `Future<Output = T>`
2493 fn lower_async_fn_output_type_to_future_bound(
2495 output: &FunctionRetTy,
2498 ) -> hir::GenericBound {
2499 // Compute the `T` in `Future<Output = T>` from the return type.
2500 let output_ty = match output {
2501 FunctionRetTy::Ty(ty) => self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(fn_def_id))),
2502 FunctionRetTy::Default(ret_ty_span) => P(self.ty_tup(*ret_ty_span, hir_vec![])),
2506 let future_params = P(hir::GenericArgs {
2508 bindings: hir_vec![hir::TypeBinding {
2509 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2510 kind: hir::TypeBindingKind::Equality {
2513 hir_id: self.next_id(),
2516 parenthesized: false,
2519 // ::std::future::Future<future_params>
2521 P(self.std_path(span, &[sym::future, sym::Future], Some(future_params), false));
2523 hir::GenericBound::Trait(
2525 trait_ref: hir::TraitRef {
2527 hir_ref_id: self.next_id(),
2529 bound_generic_params: hir_vec![],
2532 hir::TraitBoundModifier::None,
2536 fn lower_param_bound(
2539 itctx: ImplTraitContext<'_>,
2540 ) -> hir::GenericBound {
2542 GenericBound::Trait(ref ty, modifier) => {
2543 hir::GenericBound::Trait(
2544 self.lower_poly_trait_ref(ty, itctx),
2545 self.lower_trait_bound_modifier(modifier),
2548 GenericBound::Outlives(ref lifetime) => {
2549 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2554 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2555 let span = l.ident.span;
2557 ident if ident.name == kw::StaticLifetime =>
2558 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2559 ident if ident.name == kw::UnderscoreLifetime =>
2560 match self.anonymous_lifetime_mode {
2561 AnonymousLifetimeMode::CreateParameter => {
2562 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2563 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2566 AnonymousLifetimeMode::PassThrough => {
2567 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2570 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2573 self.maybe_collect_in_band_lifetime(ident);
2574 let param_name = ParamName::Plain(ident);
2575 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2580 fn new_named_lifetime(
2584 name: hir::LifetimeName,
2585 ) -> hir::Lifetime {
2587 hir_id: self.lower_node_id(id),
2593 fn lower_generic_params(
2595 params: &[GenericParam],
2596 add_bounds: &NodeMap<Vec<GenericBound>>,
2597 mut itctx: ImplTraitContext<'_>,
2598 ) -> hir::HirVec<hir::GenericParam> {
2599 params.iter().map(|param| {
2600 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2604 fn lower_generic_param(&mut self,
2605 param: &GenericParam,
2606 add_bounds: &NodeMap<Vec<GenericBound>>,
2607 mut itctx: ImplTraitContext<'_>)
2608 -> hir::GenericParam {
2609 let mut bounds = self.with_anonymous_lifetime_mode(
2610 AnonymousLifetimeMode::ReportError,
2611 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2614 let (name, kind) = match param.kind {
2615 GenericParamKind::Lifetime => {
2616 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2617 self.is_collecting_in_band_lifetimes = false;
2619 let lt = self.with_anonymous_lifetime_mode(
2620 AnonymousLifetimeMode::ReportError,
2621 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2623 let param_name = match lt.name {
2624 hir::LifetimeName::Param(param_name) => param_name,
2625 hir::LifetimeName::Implicit
2626 | hir::LifetimeName::Underscore
2627 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2628 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2631 "object-lifetime-default should not occur here",
2634 hir::LifetimeName::Error => ParamName::Error,
2637 let kind = hir::GenericParamKind::Lifetime {
2638 kind: hir::LifetimeParamKind::Explicit
2641 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2645 GenericParamKind::Type { ref default, .. } => {
2646 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2647 if !add_bounds.is_empty() {
2648 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2649 bounds = bounds.into_iter()
2654 let kind = hir::GenericParamKind::Type {
2655 default: default.as_ref().map(|x| {
2656 self.lower_ty(x, ImplTraitContext::OpaqueTy(None))
2658 synthetic: param.attrs.iter()
2659 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2660 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2664 (hir::ParamName::Plain(param.ident), kind)
2666 GenericParamKind::Const { ref ty } => {
2667 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2668 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2674 hir_id: self.lower_node_id(param.id),
2676 span: param.ident.span,
2677 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2678 attrs: self.lower_attrs(¶m.attrs),
2684 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2685 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2686 hir::QPath::Resolved(None, path) => path,
2687 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2691 hir_ref_id: self.lower_node_id(p.ref_id),
2695 fn lower_poly_trait_ref(
2698 mut itctx: ImplTraitContext<'_>,
2699 ) -> hir::PolyTraitRef {
2700 let bound_generic_params = self.lower_generic_params(
2701 &p.bound_generic_params,
2702 &NodeMap::default(),
2705 let trait_ref = self.with_in_scope_lifetime_defs(
2706 &p.bound_generic_params,
2707 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2711 bound_generic_params,
2717 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2719 ty: self.lower_ty(&mt.ty, itctx),
2724 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2725 -> hir::GenericBounds {
2726 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2729 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2730 let mut stmts = vec![];
2731 let mut expr = None;
2733 for (index, stmt) in b.stmts.iter().enumerate() {
2734 if index == b.stmts.len() - 1 {
2735 if let StmtKind::Expr(ref e) = stmt.kind {
2736 expr = Some(P(self.lower_expr(e)));
2738 stmts.extend(self.lower_stmt(stmt));
2741 stmts.extend(self.lower_stmt(stmt));
2746 hir_id: self.lower_node_id(b.id),
2747 stmts: stmts.into(),
2749 rules: self.lower_block_check_mode(&b.rules),
2755 /// Lowers a block directly to an expression, presuming that it
2756 /// has no attributes and is not targeted by a `break`.
2757 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr {
2758 let block = self.lower_block(b, false);
2759 self.expr_block(block, AttrVec::new())
2762 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2763 let node = match p.kind {
2764 PatKind::Wild => hir::PatKind::Wild,
2765 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2766 let lower_sub = |this: &mut Self| sub.as_ref().map(|s| this.lower_pat(&*s));
2767 let node = self.lower_pat_ident(p, binding_mode, ident, lower_sub);
2770 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
2771 PatKind::TupleStruct(ref path, ref pats) => {
2772 let qpath = self.lower_qpath(
2776 ParamMode::Optional,
2777 ImplTraitContext::disallowed(),
2779 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple struct");
2780 hir::PatKind::TupleStruct(qpath, pats, ddpos)
2782 PatKind::Or(ref pats) => {
2783 hir::PatKind::Or(pats.iter().map(|x| self.lower_pat(x)).collect())
2785 PatKind::Path(ref qself, ref path) => {
2786 let qpath = self.lower_qpath(
2790 ParamMode::Optional,
2791 ImplTraitContext::disallowed(),
2793 hir::PatKind::Path(qpath)
2795 PatKind::Struct(ref path, ref fields, etc) => {
2796 let qpath = self.lower_qpath(
2800 ParamMode::Optional,
2801 ImplTraitContext::disallowed(),
2806 .map(|f| hir::FieldPat {
2807 hir_id: self.next_id(),
2809 pat: self.lower_pat(&f.pat),
2810 is_shorthand: f.is_shorthand,
2814 hir::PatKind::Struct(qpath, fs, etc)
2816 PatKind::Tuple(ref pats) => {
2817 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple");
2818 hir::PatKind::Tuple(pats, ddpos)
2820 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
2821 PatKind::Ref(ref inner, mutbl) => {
2822 hir::PatKind::Ref(self.lower_pat(inner), mutbl)
2824 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
2825 P(self.lower_expr(e1)),
2826 P(self.lower_expr(e2)),
2827 self.lower_range_end(end),
2829 PatKind::Slice(ref pats) => self.lower_pat_slice(pats),
2831 // If we reach here the `..` pattern is not semantically allowed.
2832 self.ban_illegal_rest_pat(p.span)
2834 PatKind::Paren(ref inner) => return self.lower_pat(inner),
2835 PatKind::Mac(_) => panic!("Shouldn't exist here"),
2838 self.pat_with_node_id_of(p, node)
2845 ) -> (HirVec<P<hir::Pat>>, Option<usize>) {
2846 let mut elems = Vec::with_capacity(pats.len());
2847 let mut rest = None;
2849 let mut iter = pats.iter().enumerate();
2850 for (idx, pat) in iter.by_ref() {
2851 // Interpret the first `..` pattern as a sub-tuple pattern.
2852 // Note that unlike for slice patterns,
2853 // where `xs @ ..` is a legal sub-slice pattern,
2854 // it is not a legal sub-tuple pattern.
2856 rest = Some((idx, pat.span));
2859 // It was not a sub-tuple pattern so lower it normally.
2860 elems.push(self.lower_pat(pat));
2863 for (_, pat) in iter {
2864 // There was a previous sub-tuple pattern; make sure we don't allow more...
2866 // ...but there was one again, so error.
2867 self.ban_extra_rest_pat(pat.span, rest.unwrap().1, ctx);
2869 elems.push(self.lower_pat(pat));
2873 (elems.into(), rest.map(|(ddpos, _)| ddpos))
2876 /// Lower a slice pattern of form `[pat_0, ..., pat_n]` into
2877 /// `hir::PatKind::Slice(before, slice, after)`.
2879 /// When encountering `($binding_mode $ident @)? ..` (`slice`),
2880 /// this is interpreted as a sub-slice pattern semantically.
2881 /// Patterns that follow, which are not like `slice` -- or an error occurs, are in `after`.
2882 fn lower_pat_slice(&mut self, pats: &[AstP<Pat>]) -> hir::PatKind {
2883 let mut before = Vec::new();
2884 let mut after = Vec::new();
2885 let mut slice = None;
2886 let mut prev_rest_span = None;
2888 let mut iter = pats.iter();
2889 // Lower all the patterns until the first occurence of a sub-slice pattern.
2890 for pat in iter.by_ref() {
2892 // Found a sub-slice pattern `..`. Record, lower it to `_`, and stop here.
2894 prev_rest_span = Some(pat.span);
2895 slice = Some(self.pat_wild_with_node_id_of(pat));
2898 // Found a sub-slice pattern `$binding_mode $ident @ ..`.
2899 // Record, lower it to `$binding_mode $ident @ _`, and stop here.
2900 PatKind::Ident(ref bm, ident, Some(ref sub)) if sub.is_rest() => {
2901 prev_rest_span = Some(sub.span);
2902 let lower_sub = |this: &mut Self| Some(this.pat_wild_with_node_id_of(sub));
2903 let node = self.lower_pat_ident(pat, bm, ident, lower_sub);
2904 slice = Some(self.pat_with_node_id_of(pat, node));
2907 // It was not a subslice pattern so lower it normally.
2908 _ => before.push(self.lower_pat(pat)),
2912 // Lower all the patterns after the first sub-slice pattern.
2914 // There was a previous subslice pattern; make sure we don't allow more.
2915 let rest_span = match pat.kind {
2916 PatKind::Rest => Some(pat.span),
2917 PatKind::Ident(.., Some(ref sub)) if sub.is_rest() => {
2918 // The `HirValidator` is merciless; add a `_` pattern to avoid ICEs.
2919 after.push(self.pat_wild_with_node_id_of(pat));
2924 if let Some(rest_span) = rest_span {
2925 // We have e.g., `[a, .., b, ..]`. That's no good, error!
2926 self.ban_extra_rest_pat(rest_span, prev_rest_span.unwrap(), "slice");
2928 // Lower the pattern normally.
2929 after.push(self.lower_pat(pat));
2933 hir::PatKind::Slice(before.into(), slice, after.into())
2939 binding_mode: &BindingMode,
2941 lower_sub: impl FnOnce(&mut Self) -> Option<P<hir::Pat>>,
2943 match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
2944 // `None` can occur in body-less function signatures
2945 res @ None | res @ Some(Res::Local(_)) => {
2946 let canonical_id = match res {
2947 Some(Res::Local(id)) => id,
2951 hir::PatKind::Binding(
2952 self.lower_binding_mode(binding_mode),
2953 self.lower_node_id(canonical_id),
2958 Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
2962 res: self.lower_res(res),
2963 segments: hir_vec![hir::PathSegment::from_ident(ident)],
2969 fn pat_wild_with_node_id_of(&mut self, p: &Pat) -> P<hir::Pat> {
2970 self.pat_with_node_id_of(p, hir::PatKind::Wild)
2973 /// Construct a `Pat` with the `HirId` of `p.id` lowered.
2974 fn pat_with_node_id_of(&mut self, p: &Pat, kind: hir::PatKind) -> P<hir::Pat> {
2976 hir_id: self.lower_node_id(p.id),
2982 /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern.
2983 fn ban_extra_rest_pat(&self, sp: Span, prev_sp: Span, ctx: &str) {
2985 .struct_span_err(sp, &format!("`..` can only be used once per {} pattern", ctx))
2986 .span_label(sp, &format!("can only be used once per {} pattern", ctx))
2987 .span_label(prev_sp, "previously used here")
2991 /// Used to ban the `..` pattern in places it shouldn't be semantically.
2992 fn ban_illegal_rest_pat(&self, sp: Span) -> hir::PatKind {
2994 .struct_span_err(sp, "`..` patterns are not allowed here")
2995 .note("only allowed in tuple, tuple struct, and slice patterns")
2998 // We're not in a list context so `..` can be reasonably treated
2999 // as `_` because it should always be valid and roughly matches the
3000 // intent of `..` (notice that the rest of a single slot is that slot).
3004 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3006 RangeEnd::Included(_) => hir::RangeEnd::Included,
3007 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3011 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3012 self.with_new_scopes(|this| {
3014 hir_id: this.lower_node_id(c.id),
3015 body: this.lower_const_body(c.value.span, Some(&c.value)),
3020 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
3021 let kind = match s.kind {
3022 StmtKind::Local(ref l) => {
3023 let (l, item_ids) = self.lower_local(l);
3024 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
3027 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
3028 self.stmt(s.span, hir::StmtKind::Item(item_id))
3033 hir_id: self.lower_node_id(s.id),
3034 kind: hir::StmtKind::Local(P(l)),
3040 StmtKind::Item(ref it) => {
3041 // Can only use the ID once.
3042 let mut id = Some(s.id);
3043 return self.lower_item_id(it)
3046 let hir_id = id.take()
3047 .map(|id| self.lower_node_id(id))
3048 .unwrap_or_else(|| self.next_id());
3052 kind: hir::StmtKind::Item(item_id),
3058 StmtKind::Expr(ref e) => hir::StmtKind::Expr(P(self.lower_expr(e))),
3059 StmtKind::Semi(ref e) => hir::StmtKind::Semi(P(self.lower_expr(e))),
3060 StmtKind::Mac(..) => panic!("shouldn't exist here"),
3062 smallvec![hir::Stmt {
3063 hir_id: self.lower_node_id(s.id),
3069 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3071 BlockCheckMode::Default => hir::DefaultBlock,
3072 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3076 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3078 BindingMode::ByValue(Mutability::Not) => hir::BindingAnnotation::Unannotated,
3079 BindingMode::ByRef(Mutability::Not) => hir::BindingAnnotation::Ref,
3080 BindingMode::ByValue(Mutability::Mut) => hir::BindingAnnotation::Mutable,
3081 BindingMode::ByRef(Mutability::Mut) => hir::BindingAnnotation::RefMut,
3085 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3087 CompilerGenerated => hir::CompilerGenerated,
3088 UserProvided => hir::UserProvided,
3092 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3094 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3095 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3099 // Helper methods for building HIR.
3101 fn stmt(&mut self, span: Span, kind: hir::StmtKind) -> hir::Stmt {
3102 hir::Stmt { span, kind, hir_id: self.next_id() }
3105 fn stmt_expr(&mut self, span: Span, expr: hir::Expr) -> hir::Stmt {
3106 self.stmt(span, hir::StmtKind::Expr(P(expr)))
3113 init: Option<P<hir::Expr>>,
3115 source: hir::LocalSource,
3117 let local = hir::Local {
3119 hir_id: self.next_id(),
3126 self.stmt(span, hir::StmtKind::Local(P(local)))
3129 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
3130 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
3136 stmts: hir::HirVec<hir::Stmt>,
3137 expr: Option<P<hir::Expr>>,
3142 hir_id: self.next_id(),
3143 rules: hir::DefaultBlock,
3145 targeted_by_break: false,
3149 /// Constructs a `true` or `false` literal pattern.
3150 fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
3151 let expr = self.expr_bool(span, val);
3152 self.pat(span, hir::PatKind::Lit(P(expr)))
3155 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3156 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
3159 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3160 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
3163 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3164 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
3167 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
3168 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
3174 components: &[Symbol],
3175 subpats: hir::HirVec<P<hir::Pat>>,
3177 let path = self.std_path(span, components, None, true);
3178 let qpath = hir::QPath::Resolved(None, P(path));
3179 let pt = if subpats.is_empty() {
3180 hir::PatKind::Path(qpath)
3182 hir::PatKind::TupleStruct(qpath, subpats, None)
3187 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
3188 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
3191 fn pat_ident_binding_mode(
3195 bm: hir::BindingAnnotation,
3196 ) -> (P<hir::Pat>, hir::HirId) {
3197 let hir_id = self.next_id();
3202 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
3209 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
3210 self.pat(span, hir::PatKind::Wild)
3213 fn pat(&mut self, span: Span, kind: hir::PatKind) -> P<hir::Pat> {
3215 hir_id: self.next_id(),
3221 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
3222 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
3223 /// The path is also resolved according to `is_value`.
3227 components: &[Symbol],
3228 params: Option<P<hir::GenericArgs>>,
3231 let ns = if is_value { Namespace::ValueNS } else { Namespace::TypeNS };
3232 let (path, res) = self.resolver.resolve_str_path(span, self.crate_root, components, ns);
3234 let mut segments: Vec<_> = path.segments.iter().map(|segment| {
3235 let res = self.expect_full_res(segment.id);
3237 ident: segment.ident,
3238 hir_id: Some(self.lower_node_id(segment.id)),
3239 res: Some(self.lower_res(res)),
3244 segments.last_mut().unwrap().args = params;
3248 res: res.map_id(|_| panic!("unexpected `NodeId`")),
3249 segments: segments.into(),
3253 fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
3254 let kind = match qpath {
3255 hir::QPath::Resolved(None, path) => {
3256 // Turn trait object paths into `TyKind::TraitObject` instead.
3258 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
3259 let principal = hir::PolyTraitRef {
3260 bound_generic_params: hir::HirVec::new(),
3261 trait_ref: hir::TraitRef {
3268 // The original ID is taken by the `PolyTraitRef`,
3269 // so the `Ty` itself needs a different one.
3270 hir_id = self.next_id();
3271 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
3273 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
3276 _ => hir::TyKind::Path(qpath),
3286 /// Invoked to create the lifetime argument for a type `&T`
3287 /// with no explicit lifetime.
3288 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
3289 match self.anonymous_lifetime_mode {
3290 // Intercept when we are in an impl header or async fn and introduce an in-band
3292 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
3294 AnonymousLifetimeMode::CreateParameter => {
3295 let fresh_name = self.collect_fresh_in_band_lifetime(span);
3297 hir_id: self.next_id(),
3299 name: hir::LifetimeName::Param(fresh_name),
3303 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
3305 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
3309 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
3310 /// return a "error lifetime".
3311 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
3312 let (id, msg, label) = match id {
3313 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
3316 self.resolver.next_node_id(),
3317 "`&` without an explicit lifetime name cannot be used here",
3318 "explicit lifetime name needed here",
3322 let mut err = struct_span_err!(
3329 err.span_label(span, label);
3332 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3335 /// Invoked to create the lifetime argument(s) for a path like
3336 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
3337 /// sorts of cases are deprecated. This may therefore report a warning or an
3338 /// error, depending on the mode.
3339 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
3341 .map(|_| self.elided_path_lifetime(span))
3345 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
3346 match self.anonymous_lifetime_mode {
3347 AnonymousLifetimeMode::CreateParameter => {
3348 // We should have emitted E0726 when processing this path above
3349 self.sess.delay_span_bug(
3351 "expected 'implicit elided lifetime not allowed' error",
3353 let id = self.resolver.next_node_id();
3354 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3356 // `PassThrough` is the normal case.
3357 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
3358 // is unsuitable here, as these can occur from missing lifetime parameters in a
3359 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
3360 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
3361 // later, at which point a suitable error will be emitted.
3362 | AnonymousLifetimeMode::PassThrough
3363 | AnonymousLifetimeMode::ReportError => self.new_implicit_lifetime(span),
3367 /// Invoked to create the lifetime argument(s) for an elided trait object
3368 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
3369 /// when the bound is written, even if it is written with `'_` like in
3370 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
3371 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
3372 match self.anonymous_lifetime_mode {
3373 // NB. We intentionally ignore the create-parameter mode here.
3374 // and instead "pass through" to resolve-lifetimes, which will apply
3375 // the object-lifetime-defaulting rules. Elided object lifetime defaults
3376 // do not act like other elided lifetimes. In other words, given this:
3378 // impl Foo for Box<dyn Debug>
3380 // we do not introduce a fresh `'_` to serve as the bound, but instead
3381 // ultimately translate to the equivalent of:
3383 // impl Foo for Box<dyn Debug + 'static>
3385 // `resolve_lifetime` has the code to make that happen.
3386 AnonymousLifetimeMode::CreateParameter => {}
3388 AnonymousLifetimeMode::ReportError => {
3389 // ReportError applies to explicit use of `'_`.
3392 // This is the normal case.
3393 AnonymousLifetimeMode::PassThrough => {}
3396 let r = hir::Lifetime {
3397 hir_id: self.next_id(),
3399 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
3401 debug!("elided_dyn_bound: r={:?}", r);
3405 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
3407 hir_id: self.next_id(),
3409 name: hir::LifetimeName::Implicit,
3413 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
3414 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
3415 // call site which do not have a macro backtrace. See #61963.
3416 let is_macro_callsite = self.sess.source_map()
3417 .span_to_snippet(span)
3418 .map(|snippet| snippet.starts_with("#["))
3420 if !is_macro_callsite {
3421 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
3422 builtin::BARE_TRAIT_OBJECTS,
3425 "trait objects without an explicit `dyn` are deprecated",
3426 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
3432 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
3433 // Sorting by span ensures that we get things in order within a
3434 // file, and also puts the files in a sensible order.
3435 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
3436 body_ids.sort_by_key(|b| bodies[b].value.span);
3440 /// Checks if the specified expression is a built-in range literal.
3441 /// (See: `LoweringContext::lower_expr()`).
3442 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
3443 use hir::{Path, QPath, ExprKind, TyKind};
3445 // Returns whether the given path represents a (desugared) range,
3446 // either in std or core, i.e. has either a `::std::ops::Range` or
3447 // `::core::ops::Range` prefix.
3448 fn is_range_path(path: &Path) -> bool {
3449 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
3450 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
3452 // "{{root}}" is the equivalent of `::` prefix in `Path`.
3453 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
3454 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
3460 // Check whether a span corresponding to a range expression is a
3461 // range literal, rather than an explicit struct or `new()` call.
3462 fn is_lit(sess: &Session, span: &Span) -> bool {
3463 let source_map = sess.source_map();
3464 let end_point = source_map.end_point(*span);
3466 if let Ok(end_string) = source_map.span_to_snippet(end_point) {
3467 !(end_string.ends_with("}") || end_string.ends_with(")"))
3474 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
3475 ExprKind::Struct(ref qpath, _, _) => {
3476 if let QPath::Resolved(None, ref path) = **qpath {
3477 return is_range_path(&path) && is_lit(sess, &expr.span);
3481 // `..` desugars to its struct path.
3482 ExprKind::Path(QPath::Resolved(None, ref path)) => {
3483 return is_range_path(&path) && is_lit(sess, &expr.span);
3486 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
3487 ExprKind::Call(ref func, _) => {
3488 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
3489 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
3490 let new_call = segment.ident.name == sym::new;
3491 return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;