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::dep_graph::DepGraph;
39 use crate::hir::{self, ParamName};
40 use crate::hir::HirVec;
41 use crate::hir::map::{DefKey, DefPathData, Definitions};
42 use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
43 use crate::hir::def::{Namespace, Res, DefKind, PartialRes, PerNS};
44 use crate::hir::{GenericArg, ConstArg};
45 use crate::hir::ptr::P;
47 use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
48 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::thin_vec::ThinVec;
58 use rustc_data_structures::sync::Lrc;
60 use std::collections::BTreeMap;
62 use smallvec::SmallVec;
65 use syntax::ptr::P as AstP;
68 use syntax::print::pprust;
69 use syntax::token::{self, Nonterminal, Token};
70 use syntax::tokenstream::{TokenStream, TokenTree};
71 use syntax::sess::ParseSess;
72 use syntax::source_map::{respan, ExpnData, ExpnKind, DesugaringKind, Spanned};
73 use syntax::symbol::{kw, sym, Symbol};
74 use syntax::visit::{self, Visitor};
75 use syntax_pos::hygiene::ExpnId;
78 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
80 pub struct LoweringContext<'a> {
81 crate_root: Option<Symbol>,
83 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
86 resolver: &'a mut dyn Resolver,
88 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
89 /// if we don't have this function pointer. To avoid that dependency so that
90 /// librustc is independent of the parser, we use dynamic dispatch here.
91 nt_to_tokenstream: NtToTokenstream,
93 /// The items being lowered are collected here.
94 items: BTreeMap<hir::HirId, hir::Item>,
96 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
97 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
98 bodies: BTreeMap<hir::BodyId, hir::Body>,
99 exported_macros: Vec<hir::MacroDef>,
100 non_exported_macro_attrs: Vec<ast::Attribute>,
102 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
104 modules: BTreeMap<hir::HirId, hir::ModuleItems>,
106 generator_kind: Option<hir::GeneratorKind>,
108 /// Used to get the current `fn`'s def span to point to when using `await`
109 /// outside of an `async fn`.
110 current_item: Option<Span>,
112 catch_scopes: Vec<NodeId>,
113 loop_scopes: Vec<NodeId>,
114 is_in_loop_condition: bool,
115 is_in_trait_impl: bool,
116 is_in_dyn_type: bool,
118 /// What to do when we encounter either an "anonymous lifetime
119 /// reference". The term "anonymous" is meant to encompass both
120 /// `'_` lifetimes as well as fully elided cases where nothing is
121 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
122 anonymous_lifetime_mode: AnonymousLifetimeMode,
124 /// Used to create lifetime definitions from in-band lifetime usages.
125 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
126 /// When a named lifetime is encountered in a function or impl header and
127 /// has not been defined
128 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
129 /// to this list. The results of this list are then added to the list of
130 /// lifetime definitions in the corresponding impl or function generics.
131 lifetimes_to_define: Vec<(Span, ParamName)>,
133 /// `true` if in-band lifetimes are being collected. This is used to
134 /// indicate whether or not we're in a place where new lifetimes will result
135 /// in in-band lifetime definitions, such a function or an impl header,
136 /// including implicit lifetimes from `impl_header_lifetime_elision`.
137 is_collecting_in_band_lifetimes: bool,
139 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
140 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
141 /// against this list to see if it is already in-scope, or if a definition
142 /// needs to be created for it.
144 /// We always store a `modern()` version of the param-name in this
146 in_scope_lifetimes: Vec<ParamName>,
148 current_module: hir::HirId,
150 type_def_lifetime_params: DefIdMap<usize>,
152 current_hir_id_owner: Vec<(DefIndex, u32)>,
153 item_local_id_counters: NodeMap<u32>,
154 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
156 allow_try_trait: Option<Lrc<[Symbol]>>,
157 allow_gen_future: Option<Lrc<[Symbol]>>,
161 fn cstore(&self) -> &dyn CrateStore;
163 /// Obtains resolution for a `NodeId` with a single resolution.
164 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
166 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
167 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
169 /// Obtains resolution for a label with the given `NodeId`.
170 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
172 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
173 /// This should only return `None` during testing.
174 fn definitions(&mut self) -> &mut Definitions;
176 /// Given suffix `["b", "c", "d"]`, creates an AST path for `[::crate_root]::b::c::d` and
177 /// resolves it based on `is_value`.
181 crate_root: Option<Symbol>,
182 components: &[Symbol],
184 ) -> (ast::Path, Res<NodeId>);
186 fn lint_buffer(&mut self) -> &mut lint::LintBuffer;
189 type NtToTokenstream = fn(&Nonterminal, &ParseSess, Span) -> TokenStream;
191 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
192 /// and if so, what meaning it has.
194 enum ImplTraitContext<'a> {
195 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
196 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
197 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
199 /// Newly generated parameters should be inserted into the given `Vec`.
200 Universal(&'a mut Vec<hir::GenericParam>),
202 /// Treat `impl Trait` as shorthand for a new opaque type.
203 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
204 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
206 /// We optionally store a `DefId` for the parent item here so we can look up necessary
207 /// information later. It is `None` when no information about the context should be stored
208 /// (e.g., for consts and statics).
209 OpaqueTy(Option<DefId> /* fn def-ID */),
211 /// `impl Trait` is not accepted in this position.
212 Disallowed(ImplTraitPosition),
215 /// Position in which `impl Trait` is disallowed.
216 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
217 enum ImplTraitPosition {
218 /// Disallowed in `let` / `const` / `static` bindings.
221 /// All other posiitons.
225 impl<'a> ImplTraitContext<'a> {
227 fn disallowed() -> Self {
228 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
231 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
232 use self::ImplTraitContext::*;
234 Universal(params) => Universal(params),
235 OpaqueTy(fn_def_id) => OpaqueTy(*fn_def_id),
236 Disallowed(pos) => Disallowed(*pos),
243 dep_graph: &DepGraph,
245 resolver: &mut dyn Resolver,
246 nt_to_tokenstream: NtToTokenstream,
248 // We're constructing the HIR here; we don't care what we will
249 // read, since we haven't even constructed the *input* to
251 dep_graph.assert_ignored();
253 let _prof_timer = sess.prof.generic_activity("hir_lowering");
256 crate_root: sess.parse_sess.injected_crate_name.try_get().copied(),
260 items: BTreeMap::new(),
261 trait_items: BTreeMap::new(),
262 impl_items: BTreeMap::new(),
263 bodies: BTreeMap::new(),
264 trait_impls: BTreeMap::new(),
265 modules: BTreeMap::new(),
266 exported_macros: Vec::new(),
267 non_exported_macro_attrs: Vec::new(),
268 catch_scopes: Vec::new(),
269 loop_scopes: Vec::new(),
270 is_in_loop_condition: false,
271 is_in_trait_impl: false,
272 is_in_dyn_type: false,
273 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
274 type_def_lifetime_params: Default::default(),
275 current_module: hir::CRATE_HIR_ID,
276 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
277 item_local_id_counters: Default::default(),
278 node_id_to_hir_id: IndexVec::new(),
279 generator_kind: None,
281 lifetimes_to_define: Vec::new(),
282 is_collecting_in_band_lifetimes: false,
283 in_scope_lifetimes: Vec::new(),
284 allow_try_trait: Some([sym::try_trait][..].into()),
285 allow_gen_future: Some([sym::gen_future][..].into()),
289 #[derive(Copy, Clone, PartialEq)]
291 /// Any path in a type context.
293 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
295 /// The `module::Type` in `module::Type::method` in an expression.
299 enum ParenthesizedGenericArgs {
305 /// What to do when we encounter an **anonymous** lifetime
306 /// reference. Anonymous lifetime references come in two flavors. You
307 /// have implicit, or fully elided, references to lifetimes, like the
308 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
309 /// or `Ref<'_, T>`. These often behave the same, but not always:
311 /// - certain usages of implicit references are deprecated, like
312 /// `Ref<T>`, and we sometimes just give hard errors in those cases
314 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
315 /// the same as `Box<dyn Foo + '_>`.
317 /// We describe the effects of the various modes in terms of three cases:
319 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
320 /// of a `&` (e.g., the missing lifetime in something like `&T`)
321 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
322 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
323 /// elided bounds follow special rules. Note that this only covers
324 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
325 /// '_>` is a case of "modern" elision.
326 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
327 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
328 /// non-deprecated equivalent.
330 /// Currently, the handling of lifetime elision is somewhat spread out
331 /// between HIR lowering and -- as described below -- the
332 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
333 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
334 /// everything into HIR lowering.
335 #[derive(Copy, Clone, Debug)]
336 enum AnonymousLifetimeMode {
337 /// For **Modern** cases, create a new anonymous region parameter
338 /// and reference that.
340 /// For **Dyn Bound** cases, pass responsibility to
341 /// `resolve_lifetime` code.
343 /// For **Deprecated** cases, report an error.
346 /// Give a hard error when either `&` or `'_` is written. Used to
347 /// rule out things like `where T: Foo<'_>`. Does not imply an
348 /// error on default object bounds (e.g., `Box<dyn Foo>`).
351 /// Pass responsibility to `resolve_lifetime` code for all cases.
355 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
357 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
358 fn visit_ty(&mut self, ty: &'a Ty) {
364 TyKind::ImplTrait(id, _) => self.ids.push(id),
367 visit::walk_ty(self, ty);
370 fn visit_path_segment(
373 path_segment: &'v PathSegment,
375 if let Some(ref p) = path_segment.args {
376 if let GenericArgs::Parenthesized(_) = **p {
380 visit::walk_path_segment(self, path_span, path_segment)
384 impl<'a> LoweringContext<'a> {
385 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
386 /// Full-crate AST visitor that inserts into a fresh
387 /// `LoweringContext` any information that may be
388 /// needed from arbitrary locations in the crate,
389 /// e.g., the number of lifetime generic parameters
390 /// declared for every type and trait definition.
391 struct MiscCollector<'tcx, 'interner> {
392 lctx: &'tcx mut LoweringContext<'interner>,
393 hir_id_owner: Option<NodeId>,
396 impl MiscCollector<'_, '_> {
397 fn allocate_use_tree_hir_id_counters(
403 UseTreeKind::Simple(_, id1, id2) => {
404 for &id in &[id1, id2] {
405 self.lctx.resolver.definitions().create_def_with_parent(
412 self.lctx.allocate_hir_id_counter(id);
415 UseTreeKind::Glob => (),
416 UseTreeKind::Nested(ref trees) => {
417 for &(ref use_tree, id) in trees {
418 let hir_id = self.lctx.allocate_hir_id_counter(id);
419 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
425 fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
427 F: FnOnce(&mut Self) -> T,
429 let old = mem::replace(&mut self.hir_id_owner, owner);
431 self.hir_id_owner = old;
436 impl<'tcx, 'interner> Visitor<'tcx> for MiscCollector<'tcx, 'interner> {
437 fn visit_pat(&mut self, p: &'tcx Pat) {
438 if let PatKind::Paren(..) | PatKind::Rest = p.kind {
439 // Doesn't generate a HIR node
440 } else if let Some(owner) = self.hir_id_owner {
441 self.lctx.lower_node_id_with_owner(p.id, owner);
444 visit::walk_pat(self, p)
447 fn visit_item(&mut self, item: &'tcx Item) {
448 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
451 ItemKind::Struct(_, ref generics)
452 | ItemKind::Union(_, ref generics)
453 | ItemKind::Enum(_, ref generics)
454 | ItemKind::TyAlias(_, ref generics)
455 | ItemKind::OpaqueTy(_, ref generics)
456 | ItemKind::Trait(_, _, ref generics, ..) => {
457 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
461 .filter(|param| match param.kind {
462 ast::GenericParamKind::Lifetime { .. } => true,
466 self.lctx.type_def_lifetime_params.insert(def_id, count);
468 ItemKind::Use(ref use_tree) => {
469 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
474 self.with_hir_id_owner(Some(item.id), |this| {
475 visit::walk_item(this, item);
479 fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
480 self.lctx.allocate_hir_id_counter(item.id);
483 TraitItemKind::Method(_, None) => {
484 // Ignore patterns in trait methods without bodies
485 self.with_hir_id_owner(None, |this| {
486 visit::walk_trait_item(this, item)
489 _ => self.with_hir_id_owner(Some(item.id), |this| {
490 visit::walk_trait_item(this, item);
495 fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
496 self.lctx.allocate_hir_id_counter(item.id);
497 self.with_hir_id_owner(Some(item.id), |this| {
498 visit::walk_impl_item(this, item);
502 fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) {
503 // Ignore patterns in foreign items
504 self.with_hir_id_owner(None, |this| {
505 visit::walk_foreign_item(this, i)
509 fn visit_ty(&mut self, t: &'tcx Ty) {
511 // Mirrors the case in visit::walk_ty
512 TyKind::BareFn(ref f) => {
518 // Mirrors visit::walk_fn_decl
519 for parameter in &f.decl.inputs {
520 // We don't lower the ids of argument patterns
521 self.with_hir_id_owner(None, |this| {
522 this.visit_pat(¶meter.pat);
524 self.visit_ty(¶meter.ty)
526 self.visit_fn_ret_ty(&f.decl.output)
528 _ => visit::walk_ty(self, t),
533 self.lower_node_id(CRATE_NODE_ID);
534 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
536 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
537 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
539 let module = self.lower_mod(&c.module);
540 let attrs = self.lower_attrs(&c.attrs);
541 let body_ids = body_ids(&self.bodies);
545 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
551 exported_macros: hir::HirVec::from(self.exported_macros),
552 non_exported_macro_attrs: hir::HirVec::from(self.non_exported_macro_attrs),
554 trait_items: self.trait_items,
555 impl_items: self.impl_items,
558 trait_impls: self.trait_impls,
559 modules: self.modules,
563 fn insert_item(&mut self, item: hir::Item) {
564 let id = item.hir_id;
565 // FIXME: Use `debug_asset-rt`.
566 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
567 self.items.insert(id, item);
568 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
571 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
572 // Set up the counter if needed.
573 self.item_local_id_counters.entry(owner).or_insert(0);
574 // Always allocate the first `HirId` for the owner itself.
575 let lowered = self.lower_node_id_with_owner(owner, owner);
576 debug_assert_eq!(lowered.local_id.as_u32(), 0);
580 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> hir::HirId
582 F: FnOnce(&mut Self) -> hir::HirId,
584 if ast_node_id == DUMMY_NODE_ID {
585 return hir::DUMMY_HIR_ID;
588 let min_size = ast_node_id.as_usize() + 1;
590 if min_size > self.node_id_to_hir_id.len() {
591 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
594 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
596 if existing_hir_id == hir::DUMMY_HIR_ID {
597 // Generate a new `HirId`.
598 let hir_id = alloc_hir_id(self);
599 self.node_id_to_hir_id[ast_node_id] = hir_id;
607 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
609 F: FnOnce(&mut Self) -> T,
611 let counter = self.item_local_id_counters
612 .insert(owner, HIR_ID_COUNTER_LOCKED)
613 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
614 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
615 self.current_hir_id_owner.push((def_index, counter));
617 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
619 debug_assert!(def_index == new_def_index);
620 debug_assert!(new_counter >= counter);
622 let prev = self.item_local_id_counters
623 .insert(owner, new_counter)
625 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
629 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
630 /// the `LoweringContext`'s `NodeId => HirId` map.
631 /// Take care not to call this method if the resulting `HirId` is then not
632 /// actually used in the HIR, as that would trigger an assertion in the
633 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
634 /// properly. Calling the method twice with the same `NodeId` is fine though.
635 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
636 self.lower_node_id_generic(ast_node_id, |this| {
637 let &mut (def_index, ref mut local_id_counter) =
638 this.current_hir_id_owner.last_mut().unwrap();
639 let local_id = *local_id_counter;
640 *local_id_counter += 1;
643 local_id: hir::ItemLocalId::from_u32(local_id),
648 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
649 self.lower_node_id_generic(ast_node_id, |this| {
650 let local_id_counter = this
651 .item_local_id_counters
653 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
654 let local_id = *local_id_counter;
656 // We want to be sure not to modify the counter in the map while it
657 // is also on the stack. Otherwise we'll get lost updates when writing
658 // back from the stack to the map.
659 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
661 *local_id_counter += 1;
665 .opt_def_index(owner)
666 .expect("you forgot to call `create_def_with_parent` or are lowering node-IDs \
667 that do not belong to the current owner");
671 local_id: hir::ItemLocalId::from_u32(local_id),
676 fn next_id(&mut self) -> hir::HirId {
677 self.lower_node_id(self.sess.next_node_id())
680 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
682 self.lower_node_id_generic(id, |_| {
683 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
688 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
689 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
690 if pr.unresolved_segments() != 0 {
691 bug!("path not fully resolved: {:?}", pr);
697 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
698 self.resolver.get_import_res(id).present_items()
701 fn diagnostic(&self) -> &errors::Handler {
702 self.sess.diagnostic()
705 /// Reuses the span but adds information like the kind of the desugaring and features that are
706 /// allowed inside this span.
707 fn mark_span_with_reason(
709 reason: DesugaringKind,
711 allow_internal_unstable: Option<Lrc<[Symbol]>>,
713 span.fresh_expansion(ExpnData {
714 allow_internal_unstable,
715 ..ExpnData::default(ExpnKind::Desugaring(reason), span, self.sess.edition())
719 fn with_anonymous_lifetime_mode<R>(
721 anonymous_lifetime_mode: AnonymousLifetimeMode,
722 op: impl FnOnce(&mut Self) -> R,
725 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
726 anonymous_lifetime_mode,
728 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
729 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
730 let result = op(self);
731 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
732 debug!("with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
733 old_anonymous_lifetime_mode);
737 /// Creates a new `hir::GenericParam` for every new lifetime and
738 /// type parameter encountered while evaluating `f`. Definitions
739 /// are created with the parent provided. If no `parent_id` is
740 /// provided, no definitions will be returned.
742 /// Presuming that in-band lifetimes are enabled, then
743 /// `self.anonymous_lifetime_mode` will be updated to match the
744 /// parameter while `f` is running (and restored afterwards).
745 fn collect_in_band_defs<T, F>(
748 anonymous_lifetime_mode: AnonymousLifetimeMode,
750 ) -> (Vec<hir::GenericParam>, T)
752 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
754 assert!(!self.is_collecting_in_band_lifetimes);
755 assert!(self.lifetimes_to_define.is_empty());
756 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
758 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
759 self.is_collecting_in_band_lifetimes = true;
761 let (in_band_ty_params, res) = f(self);
763 self.is_collecting_in_band_lifetimes = false;
764 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
766 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
768 let params = lifetimes_to_define
770 .map(|(span, hir_name)| self.lifetime_to_generic_param(
771 span, hir_name, parent_id.index,
773 .chain(in_band_ty_params.into_iter())
779 /// Converts a lifetime into a new generic parameter.
780 fn lifetime_to_generic_param(
784 parent_index: DefIndex,
785 ) -> hir::GenericParam {
786 let node_id = self.sess.next_node_id();
788 // Get the name we'll use to make the def-path. Note
789 // that collisions are ok here and this shouldn't
790 // really show up for end-user.
791 let (str_name, kind) = match hir_name {
792 ParamName::Plain(ident) => (
794 hir::LifetimeParamKind::InBand,
796 ParamName::Fresh(_) => (
797 kw::UnderscoreLifetime,
798 hir::LifetimeParamKind::Elided,
800 ParamName::Error => (
801 kw::UnderscoreLifetime,
802 hir::LifetimeParamKind::Error,
806 // Add a definition for the in-band lifetime def.
807 self.resolver.definitions().create_def_with_parent(
810 DefPathData::LifetimeNs(str_name),
816 hir_id: self.lower_node_id(node_id),
821 pure_wrt_drop: false,
822 kind: hir::GenericParamKind::Lifetime { kind }
826 /// When there is a reference to some lifetime `'a`, and in-band
827 /// lifetimes are enabled, then we want to push that lifetime into
828 /// the vector of names to define later. In that case, it will get
829 /// added to the appropriate generics.
830 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
831 if !self.is_collecting_in_band_lifetimes {
835 if !self.sess.features_untracked().in_band_lifetimes {
839 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.modern())) {
843 let hir_name = ParamName::Plain(ident);
845 if self.lifetimes_to_define.iter()
846 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
850 self.lifetimes_to_define.push((ident.span, hir_name));
853 /// When we have either an elided or `'_` lifetime in an impl
854 /// header, we convert it to an in-band lifetime.
855 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
856 assert!(self.is_collecting_in_band_lifetimes);
857 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
858 let hir_name = ParamName::Fresh(index);
859 self.lifetimes_to_define.push((span, hir_name));
863 // Evaluates `f` with the lifetimes in `params` in-scope.
864 // This is used to track which lifetimes have already been defined, and
865 // which are new in-band lifetimes that need to have a definition created
867 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
869 F: FnOnce(&mut LoweringContext<'_>) -> T,
871 let old_len = self.in_scope_lifetimes.len();
872 let lt_def_names = params.iter().filter_map(|param| match param.kind {
873 GenericParamKind::Lifetime { .. } => Some(ParamName::Plain(param.ident.modern())),
876 self.in_scope_lifetimes.extend(lt_def_names);
880 self.in_scope_lifetimes.truncate(old_len);
884 /// Appends in-band lifetime defs and argument-position `impl
885 /// Trait` defs to the existing set of generics.
887 /// Presuming that in-band lifetimes are enabled, then
888 /// `self.anonymous_lifetime_mode` will be updated to match the
889 /// parameter while `f` is running (and restored afterwards).
890 fn add_in_band_defs<F, T>(
894 anonymous_lifetime_mode: AnonymousLifetimeMode,
896 ) -> (hir::Generics, T)
898 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
900 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
903 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
904 let mut params = Vec::new();
905 // Note: it is necessary to lower generics *before* calling `f`.
906 // When lowering `async fn`, there's a final step when lowering
907 // the return type that assumes that all in-scope lifetimes have
908 // already been added to either `in_scope_lifetimes` or
909 // `lifetimes_to_define`. If we swapped the order of these two,
910 // in-band-lifetimes introduced by generics or where-clauses
911 // wouldn't have been added yet.
912 let generics = this.lower_generics(
914 ImplTraitContext::Universal(&mut params),
916 let res = f(this, &mut params);
917 (params, (generics, res))
922 let mut lowered_params: Vec<_> = lowered_generics
928 // FIXME(const_generics): the compiler doesn't always cope with
929 // unsorted generic parameters at the moment, so we make sure
930 // that they're ordered correctly here for now. (When we chain
931 // the `in_band_defs`, we might make the order unsorted.)
932 lowered_params.sort_by_key(|param| {
934 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
935 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
936 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
940 lowered_generics.params = lowered_params.into();
942 (lowered_generics, res)
945 fn with_dyn_type_scope<T, F>(&mut self, in_scope: bool, f: F) -> T
947 F: FnOnce(&mut LoweringContext<'_>) -> T,
949 let was_in_dyn_type = self.is_in_dyn_type;
950 self.is_in_dyn_type = in_scope;
952 let result = f(self);
954 self.is_in_dyn_type = was_in_dyn_type;
959 fn with_new_scopes<T, F>(&mut self, f: F) -> T
961 F: FnOnce(&mut LoweringContext<'_>) -> T,
963 let was_in_loop_condition = self.is_in_loop_condition;
964 self.is_in_loop_condition = false;
966 let catch_scopes = mem::take(&mut self.catch_scopes);
967 let loop_scopes = mem::take(&mut self.loop_scopes);
969 self.catch_scopes = catch_scopes;
970 self.loop_scopes = loop_scopes;
972 self.is_in_loop_condition = was_in_loop_condition;
977 fn def_key(&mut self, id: DefId) -> DefKey {
979 self.resolver.definitions().def_key(id.index)
981 self.resolver.cstore().def_key(id)
985 fn lower_attrs_extendable(&mut self, attrs: &[Attribute]) -> Vec<Attribute> {
988 .map(|a| self.lower_attr(a))
992 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
993 self.lower_attrs_extendable(attrs).into()
996 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
997 // Note that we explicitly do not walk the path. Since we don't really
998 // lower attributes (we use the AST version) there is nowhere to keep
999 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1000 let kind = match attr.kind {
1001 AttrKind::Normal(ref item) => {
1002 AttrKind::Normal(AttrItem {
1003 path: item.path.clone(),
1004 tokens: self.lower_token_stream(item.tokens.clone()),
1007 AttrKind::DocComment(comment) => AttrKind::DocComment(comment)
1018 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1021 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1025 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1027 TokenTree::Token(token) => self.lower_token(token),
1028 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1031 self.lower_token_stream(tts),
1036 fn lower_token(&mut self, token: Token) -> TokenStream {
1038 token::Interpolated(nt) => {
1039 let tts = (self.nt_to_tokenstream)(&nt, &self.sess.parse_sess, token.span);
1040 self.lower_token_stream(tts)
1042 _ => TokenTree::Token(token).into(),
1046 /// Given an associated type constraint like one of these:
1049 /// T: Iterator<Item: Debug>
1051 /// T: Iterator<Item = Debug>
1055 /// returns a `hir::TypeBinding` representing `Item`.
1056 fn lower_assoc_ty_constraint(
1058 constraint: &AssocTyConstraint,
1059 itctx: ImplTraitContext<'_>,
1060 ) -> hir::TypeBinding {
1061 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1063 let kind = match constraint.kind {
1064 AssocTyConstraintKind::Equality { ref ty } => hir::TypeBindingKind::Equality {
1065 ty: self.lower_ty(ty, itctx)
1067 AssocTyConstraintKind::Bound { ref bounds } => {
1068 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1069 let (desugar_to_impl_trait, itctx) = match itctx {
1070 // We are in the return position:
1072 // fn foo() -> impl Iterator<Item: Debug>
1076 // fn foo() -> impl Iterator<Item = impl Debug>
1077 ImplTraitContext::OpaqueTy(_) => (true, itctx),
1079 // We are in the argument position, but within a dyn type:
1081 // fn foo(x: dyn Iterator<Item: Debug>)
1085 // fn foo(x: dyn Iterator<Item = impl Debug>)
1086 ImplTraitContext::Universal(_) if self.is_in_dyn_type => (true, itctx),
1088 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1089 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1090 // "impl trait context" to permit `impl Debug` in this position (it desugars
1091 // then to an opaque type).
1093 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1094 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type =>
1095 (true, ImplTraitContext::OpaqueTy(None)),
1097 // We are in the parameter position, but not within a dyn type:
1099 // fn foo(x: impl Iterator<Item: Debug>)
1101 // so we leave it as is and this gets expanded in astconv to a bound like
1102 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1104 _ => (false, itctx),
1107 if desugar_to_impl_trait {
1108 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1109 // constructing the HIR for `impl bounds...` and then lowering that.
1111 let impl_trait_node_id = self.sess.next_node_id();
1112 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1113 self.resolver.definitions().create_def_with_parent(
1116 DefPathData::ImplTrait,
1121 self.with_dyn_type_scope(false, |this| {
1122 let ty = this.lower_ty(
1124 id: this.sess.next_node_id(),
1125 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1126 span: constraint.span,
1131 hir::TypeBindingKind::Equality {
1136 // Desugar `AssocTy: Bounds` into a type binding where the
1137 // later desugars into a trait predicate.
1138 let bounds = self.lower_param_bounds(bounds, itctx);
1140 hir::TypeBindingKind::Constraint {
1148 hir_id: self.lower_node_id(constraint.id),
1149 ident: constraint.ident,
1151 span: constraint.span,
1155 fn lower_generic_arg(&mut self,
1156 arg: &ast::GenericArg,
1157 itctx: ImplTraitContext<'_>)
1158 -> hir::GenericArg {
1160 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1161 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1162 ast::GenericArg::Const(ct) => {
1163 GenericArg::Const(ConstArg {
1164 value: self.lower_anon_const(&ct),
1165 span: ct.value.span,
1171 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1172 P(self.lower_ty_direct(t, itctx))
1178 qself: &Option<QSelf>,
1180 param_mode: ParamMode,
1181 itctx: ImplTraitContext<'_>
1183 let id = self.lower_node_id(t.id);
1184 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1185 let ty = self.ty_path(id, t.span, qpath);
1186 if let hir::TyKind::TraitObject(..) = ty.kind {
1187 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1192 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1193 let kind = match t.kind {
1194 TyKind::Infer => hir::TyKind::Infer,
1195 TyKind::Err => hir::TyKind::Err,
1196 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1197 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1198 TyKind::Rptr(ref region, ref mt) => {
1199 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1200 let lifetime = match *region {
1201 Some(ref lt) => self.lower_lifetime(lt),
1202 None => self.elided_ref_lifetime(span),
1204 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1206 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1209 this.with_anonymous_lifetime_mode(
1210 AnonymousLifetimeMode::PassThrough,
1212 hir::TyKind::BareFn(P(hir::BareFnTy {
1213 generic_params: this.lower_generic_params(
1215 &NodeMap::default(),
1216 ImplTraitContext::disallowed(),
1218 unsafety: this.lower_unsafety(f.unsafety),
1219 abi: this.lower_abi(f.abi),
1220 decl: this.lower_fn_decl(&f.decl, None, false, None),
1221 param_names: this.lower_fn_params_to_names(&f.decl),
1227 TyKind::Never => hir::TyKind::Never,
1228 TyKind::Tup(ref tys) => {
1229 hir::TyKind::Tup(tys.iter().map(|ty| {
1230 self.lower_ty_direct(ty, itctx.reborrow())
1233 TyKind::Paren(ref ty) => {
1234 return self.lower_ty_direct(ty, itctx);
1236 TyKind::Path(ref qself, ref path) => {
1237 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1239 TyKind::ImplicitSelf => {
1240 let res = self.expect_full_res(t.id);
1241 let res = self.lower_res(res);
1242 hir::TyKind::Path(hir::QPath::Resolved(
1246 segments: hir_vec![hir::PathSegment::from_ident(
1247 Ident::with_dummy_span(kw::SelfUpper)
1253 TyKind::Array(ref ty, ref length) => {
1254 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1256 TyKind::Typeof(ref expr) => {
1257 hir::TyKind::Typeof(self.lower_anon_const(expr))
1259 TyKind::TraitObject(ref bounds, kind) => {
1260 let mut lifetime_bound = None;
1261 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1264 .filter_map(|bound| match *bound {
1265 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1266 Some(this.lower_poly_trait_ref(ty, itctx.reborrow()))
1268 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1269 GenericBound::Outlives(ref lifetime) => {
1270 if lifetime_bound.is_none() {
1271 lifetime_bound = Some(this.lower_lifetime(lifetime));
1277 let lifetime_bound =
1278 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1279 (bounds, lifetime_bound)
1281 if kind != TraitObjectSyntax::Dyn {
1282 self.maybe_lint_bare_trait(t.span, t.id, false);
1284 hir::TyKind::TraitObject(bounds, lifetime_bound)
1286 TyKind::ImplTrait(def_node_id, ref bounds) => {
1289 ImplTraitContext::OpaqueTy(fn_def_id) => {
1290 self.lower_opaque_impl_trait(
1291 span, fn_def_id, def_node_id,
1292 |this| this.lower_param_bounds(bounds, itctx),
1295 ImplTraitContext::Universal(in_band_ty_params) => {
1296 // Add a definition for the in-band `Param`.
1297 let def_index = self
1300 .opt_def_index(def_node_id)
1303 let hir_bounds = self.lower_param_bounds(
1305 ImplTraitContext::Universal(in_band_ty_params),
1307 // Set the name to `impl Bound1 + Bound2`.
1308 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1309 in_band_ty_params.push(hir::GenericParam {
1310 hir_id: self.lower_node_id(def_node_id),
1311 name: ParamName::Plain(ident),
1312 pure_wrt_drop: false,
1316 kind: hir::GenericParamKind::Type {
1318 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1322 hir::TyKind::Path(hir::QPath::Resolved(
1326 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1327 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1331 ImplTraitContext::Disallowed(pos) => {
1332 let allowed_in = if self.sess.features_untracked()
1333 .impl_trait_in_bindings {
1334 "bindings or function and inherent method return types"
1336 "function and inherent method return types"
1338 let mut err = struct_span_err!(
1342 "`impl Trait` not allowed outside of {}",
1345 if pos == ImplTraitPosition::Binding &&
1346 nightly_options::is_nightly_build() {
1348 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1349 attributes to enable");
1356 TyKind::Mac(_) => bug!("`TyKind::Mac` should have been expanded by now"),
1357 TyKind::CVarArgs => bug!("`TyKind::CVarArgs` should have been handled elsewhere"),
1363 hir_id: self.lower_node_id(t.id),
1367 fn lower_opaque_impl_trait(
1370 fn_def_id: Option<DefId>,
1371 opaque_ty_node_id: NodeId,
1372 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1375 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1381 // Make sure we know that some funky desugaring has been going on here.
1382 // This is a first: there is code in other places like for loop
1383 // desugaring that explicitly states that we don't want to track that.
1384 // Not tracking it makes lints in rustc and clippy very fragile, as
1385 // frequently opened issues show.
1386 let opaque_ty_span = self.mark_span_with_reason(
1387 DesugaringKind::OpaqueTy,
1392 let opaque_ty_def_index = self
1395 .opt_def_index(opaque_ty_node_id)
1398 self.allocate_hir_id_counter(opaque_ty_node_id);
1400 let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
1402 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1404 opaque_ty_def_index,
1409 "lower_opaque_impl_trait: lifetimes={:#?}", lifetimes,
1413 "lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs,
1416 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1417 let opaque_ty_item = hir::OpaqueTy {
1418 generics: hir::Generics {
1419 params: lifetime_defs,
1420 where_clause: hir::WhereClause {
1421 predicates: hir_vec![],
1427 impl_trait_fn: fn_def_id,
1428 origin: hir::OpaqueTyOrigin::FnReturn,
1431 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_index);
1432 let opaque_ty_id = lctx.generate_opaque_type(
1439 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1440 hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, lifetimes)
1444 /// Registers a new opaque type with the proper `NodeId`s and
1445 /// returns the lowered node-ID for the opaque type.
1446 fn generate_opaque_type(
1448 opaque_ty_node_id: NodeId,
1449 opaque_ty_item: hir::OpaqueTy,
1451 opaque_ty_span: Span,
1453 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1454 let opaque_ty_id = self.lower_node_id(opaque_ty_node_id);
1455 // Generate an `type Foo = impl Trait;` declaration.
1456 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1457 let opaque_ty_item = hir::Item {
1458 hir_id: opaque_ty_id,
1459 ident: Ident::invalid(),
1460 attrs: Default::default(),
1461 kind: opaque_ty_item_kind,
1462 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1463 span: opaque_ty_span,
1466 // Insert the item into the global item list. This usually happens
1467 // automatically for all AST items. But this opaque type item
1468 // does not actually exist in the AST.
1469 self.insert_item(opaque_ty_item);
1473 fn lifetimes_from_impl_trait_bounds(
1475 opaque_ty_id: NodeId,
1476 parent_index: DefIndex,
1477 bounds: &hir::GenericBounds,
1478 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1480 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
1481 parent_index={:?}, \
1483 opaque_ty_id, parent_index, bounds,
1486 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1487 // appear in the bounds, excluding lifetimes that are created within the bounds.
1488 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1489 struct ImplTraitLifetimeCollector<'r, 'a> {
1490 context: &'r mut LoweringContext<'a>,
1492 opaque_ty_id: NodeId,
1493 collect_elided_lifetimes: bool,
1494 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1495 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1496 output_lifetimes: Vec<hir::GenericArg>,
1497 output_lifetime_params: Vec<hir::GenericParam>,
1500 impl<'r, 'a, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1501 fn nested_visit_map<'this>(
1503 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1504 hir::intravisit::NestedVisitorMap::None
1507 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1508 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1509 if parameters.parenthesized {
1510 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1511 self.collect_elided_lifetimes = false;
1512 hir::intravisit::walk_generic_args(self, span, parameters);
1513 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1515 hir::intravisit::walk_generic_args(self, span, parameters);
1519 fn visit_ty(&mut self, t: &'v hir::Ty) {
1520 // Don't collect elided lifetimes used inside of `fn()` syntax.
1521 if let hir::TyKind::BareFn(_) = t.kind {
1522 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1523 self.collect_elided_lifetimes = false;
1525 // Record the "stack height" of `for<'a>` lifetime bindings
1526 // to be able to later fully undo their introduction.
1527 let old_len = self.currently_bound_lifetimes.len();
1528 hir::intravisit::walk_ty(self, t);
1529 self.currently_bound_lifetimes.truncate(old_len);
1531 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1533 hir::intravisit::walk_ty(self, t)
1537 fn visit_poly_trait_ref(
1539 trait_ref: &'v hir::PolyTraitRef,
1540 modifier: hir::TraitBoundModifier,
1542 // Record the "stack height" of `for<'a>` lifetime bindings
1543 // to be able to later fully undo their introduction.
1544 let old_len = self.currently_bound_lifetimes.len();
1545 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1546 self.currently_bound_lifetimes.truncate(old_len);
1549 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1550 // Record the introduction of 'a in `for<'a> ...`.
1551 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1552 // Introduce lifetimes one at a time so that we can handle
1553 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1554 let lt_name = hir::LifetimeName::Param(param.name);
1555 self.currently_bound_lifetimes.push(lt_name);
1558 hir::intravisit::walk_generic_param(self, param);
1561 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1562 let name = match lifetime.name {
1563 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1564 if self.collect_elided_lifetimes {
1565 // Use `'_` for both implicit and underscore lifetimes in
1566 // `type Foo<'_> = impl SomeTrait<'_>;`.
1567 hir::LifetimeName::Underscore
1572 hir::LifetimeName::Param(_) => lifetime.name,
1574 // Refers to some other lifetime that is "in
1575 // scope" within the type.
1576 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1578 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1581 if !self.currently_bound_lifetimes.contains(&name)
1582 && !self.already_defined_lifetimes.contains(&name) {
1583 self.already_defined_lifetimes.insert(name);
1585 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1586 hir_id: self.context.next_id(),
1587 span: lifetime.span,
1591 let def_node_id = self.context.sess.next_node_id();
1593 self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1594 self.context.resolver.definitions().create_def_with_parent(
1597 DefPathData::LifetimeNs(name.ident().name),
1601 let (name, kind) = match name {
1602 hir::LifetimeName::Underscore => (
1603 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1604 hir::LifetimeParamKind::Elided,
1606 hir::LifetimeName::Param(param_name) => (
1608 hir::LifetimeParamKind::Explicit,
1610 _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1613 self.output_lifetime_params.push(hir::GenericParam {
1616 span: lifetime.span,
1617 pure_wrt_drop: false,
1620 kind: hir::GenericParamKind::Lifetime { kind }
1626 let mut lifetime_collector = ImplTraitLifetimeCollector {
1628 parent: parent_index,
1630 collect_elided_lifetimes: true,
1631 currently_bound_lifetimes: Vec::new(),
1632 already_defined_lifetimes: FxHashSet::default(),
1633 output_lifetimes: Vec::new(),
1634 output_lifetime_params: Vec::new(),
1637 for bound in bounds {
1638 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1642 lifetime_collector.output_lifetimes.into(),
1643 lifetime_collector.output_lifetime_params.into(),
1650 qself: &Option<QSelf>,
1652 param_mode: ParamMode,
1653 mut itctx: ImplTraitContext<'_>,
1655 let qself_position = qself.as_ref().map(|q| q.position);
1656 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1658 let partial_res = self.resolver
1659 .get_partial_res(id)
1660 .unwrap_or_else(|| PartialRes::new(Res::Err));
1662 let proj_start = p.segments.len() - partial_res.unresolved_segments();
1663 let path = P(hir::Path {
1664 res: self.lower_res(partial_res.base_res()),
1665 segments: p.segments[..proj_start]
1668 .map(|(i, segment)| {
1669 let param_mode = match (qself_position, param_mode) {
1670 (Some(j), ParamMode::Optional) if i < j => {
1671 // This segment is part of the trait path in a
1672 // qualified path - one of `a`, `b` or `Trait`
1673 // in `<X as a::b::Trait>::T::U::method`.
1679 // Figure out if this is a type/trait segment,
1680 // which may need lifetime elision performed.
1681 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1682 krate: def_id.krate,
1683 index: this.def_key(def_id).parent.expect("missing parent"),
1685 let type_def_id = match partial_res.base_res() {
1686 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1687 Some(parent_def_id(self, def_id))
1689 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1690 Some(parent_def_id(self, def_id))
1692 Res::Def(DefKind::Struct, def_id)
1693 | Res::Def(DefKind::Union, def_id)
1694 | Res::Def(DefKind::Enum, def_id)
1695 | Res::Def(DefKind::TyAlias, def_id)
1696 | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
1702 let parenthesized_generic_args = match partial_res.base_res() {
1703 // `a::b::Trait(Args)`
1704 Res::Def(DefKind::Trait, _)
1705 if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1706 // `a::b::Trait(Args)::TraitItem`
1707 Res::Def(DefKind::Method, _)
1708 | Res::Def(DefKind::AssocConst, _)
1709 | Res::Def(DefKind::AssocTy, _)
1710 if i + 2 == proj_start =>
1712 ParenthesizedGenericArgs::Ok
1714 // Avoid duplicated errors.
1715 Res::Err => ParenthesizedGenericArgs::Ok,
1717 Res::Def(DefKind::Struct, _)
1718 | Res::Def(DefKind::Enum, _)
1719 | Res::Def(DefKind::Union, _)
1720 | Res::Def(DefKind::TyAlias, _)
1721 | Res::Def(DefKind::Variant, _) if i + 1 == proj_start =>
1723 ParenthesizedGenericArgs::Err
1725 // A warning for now, for compatibility reasons.
1726 _ => ParenthesizedGenericArgs::Warn,
1729 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1730 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1733 assert!(!def_id.is_local());
1734 let item_generics = self.resolver.cstore()
1735 .item_generics_cloned_untracked(def_id, self.sess);
1736 let n = item_generics.own_counts().lifetimes;
1737 self.type_def_lifetime_params.insert(def_id, n);
1740 self.lower_path_segment(
1745 parenthesized_generic_args,
1754 // Simple case, either no projections, or only fully-qualified.
1755 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1756 if partial_res.unresolved_segments() == 0 {
1757 return hir::QPath::Resolved(qself, path);
1760 // Create the innermost type that we're projecting from.
1761 let mut ty = if path.segments.is_empty() {
1762 // If the base path is empty that means there exists a
1763 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1764 qself.expect("missing QSelf for <T>::...")
1766 // Otherwise, the base path is an implicit `Self` type path,
1767 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1768 // `<I as Iterator>::Item::default`.
1769 let new_id = self.next_id();
1770 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1773 // Anything after the base path are associated "extensions",
1774 // out of which all but the last one are associated types,
1775 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1776 // * base path is `std::vec::Vec<T>`
1777 // * "extensions" are `IntoIter`, `Item` and `clone`
1778 // * type nodes are:
1779 // 1. `std::vec::Vec<T>` (created above)
1780 // 2. `<std::vec::Vec<T>>::IntoIter`
1781 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1782 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1783 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1784 let segment = P(self.lower_path_segment(
1789 ParenthesizedGenericArgs::Warn,
1793 let qpath = hir::QPath::TypeRelative(ty, segment);
1795 // It's finished, return the extension of the right node type.
1796 if i == p.segments.len() - 1 {
1800 // Wrap the associated extension in another type node.
1801 let new_id = self.next_id();
1802 ty = P(self.ty_path(new_id, p.span, qpath));
1805 // We should've returned in the for loop above.
1808 "lower_qpath: no final extension segment in {}..{}",
1814 fn lower_path_extra(
1818 param_mode: ParamMode,
1819 explicit_owner: Option<NodeId>,
1823 segments: p.segments
1826 self.lower_path_segment(
1831 ParenthesizedGenericArgs::Err,
1832 ImplTraitContext::disallowed(),
1841 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1842 let res = self.expect_full_res(id);
1843 let res = self.lower_res(res);
1844 self.lower_path_extra(res, p, param_mode, None)
1847 fn lower_path_segment(
1850 segment: &PathSegment,
1851 param_mode: ParamMode,
1852 expected_lifetimes: usize,
1853 parenthesized_generic_args: ParenthesizedGenericArgs,
1854 itctx: ImplTraitContext<'_>,
1855 explicit_owner: Option<NodeId>,
1856 ) -> hir::PathSegment {
1857 let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
1858 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
1859 match **generic_args {
1860 GenericArgs::AngleBracketed(ref data) => {
1861 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1863 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1864 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1865 ParenthesizedGenericArgs::Warn => {
1866 self.resolver.lint_buffer().buffer_lint(
1867 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1872 (hir::GenericArgs::none(), true)
1874 ParenthesizedGenericArgs::Err => {
1875 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
1876 err.span_label(data.span, "only `Fn` traits may use parentheses");
1877 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
1878 // Do not suggest going from `Trait()` to `Trait<>`
1879 if data.inputs.len() > 0 {
1880 let split = snippet.find('(').unwrap();
1881 let trait_name = &snippet[0..split];
1882 let args = &snippet[split + 1 .. snippet.len() - 1];
1883 err.span_suggestion(
1885 "use angle brackets instead",
1886 format!("{}<{}>", trait_name, args),
1887 Applicability::MaybeIncorrect,
1893 self.lower_angle_bracketed_parameter_data(
1894 &data.as_angle_bracketed_args(),
1904 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1907 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1908 GenericArg::Lifetime(_) => true,
1911 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1912 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1913 if !generic_args.parenthesized && !has_lifetimes {
1915 self.elided_path_lifetimes(path_span, expected_lifetimes)
1917 .map(|lt| GenericArg::Lifetime(lt))
1918 .chain(generic_args.args.into_iter())
1920 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1921 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1922 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
1923 let no_bindings = generic_args.bindings.is_empty();
1924 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
1925 // If there are no (non-implicit) generic args or associated type
1926 // bindings, our suggestion includes the angle brackets.
1927 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1929 // Otherwise (sorry, this is kind of gross) we need to infer the
1930 // place to splice in the `'_, ` from the generics that do exist.
1931 let first_generic_span = first_generic_span
1932 .expect("already checked that non-lifetime args or bindings exist");
1933 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1935 match self.anonymous_lifetime_mode {
1936 // In create-parameter mode we error here because we don't want to support
1937 // deprecated impl elision in new features like impl elision and `async fn`,
1938 // both of which work using the `CreateParameter` mode:
1940 // impl Foo for std::cell::Ref<u32> // note lack of '_
1941 // async fn foo(_: std::cell::Ref<u32>) { ... }
1942 AnonymousLifetimeMode::CreateParameter => {
1943 let mut err = struct_span_err!(
1947 "implicit elided lifetime not allowed here"
1949 crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
1960 AnonymousLifetimeMode::PassThrough |
1961 AnonymousLifetimeMode::ReportError => {
1962 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
1963 ELIDED_LIFETIMES_IN_PATHS,
1966 "hidden lifetime parameters in types are deprecated",
1967 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1980 let res = self.expect_full_res(segment.id);
1981 let id = if let Some(owner) = explicit_owner {
1982 self.lower_node_id_with_owner(segment.id, owner)
1984 self.lower_node_id(segment.id)
1987 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
1988 segment.ident, segment.id, id,
1991 hir::PathSegment::new(
1994 Some(self.lower_res(res)),
2000 fn lower_angle_bracketed_parameter_data(
2002 data: &AngleBracketedArgs,
2003 param_mode: ParamMode,
2004 mut itctx: ImplTraitContext<'_>,
2005 ) -> (hir::GenericArgs, bool) {
2006 let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
2007 let has_non_lt_args = args.iter().any(|arg| match arg {
2008 ast::GenericArg::Lifetime(_) => false,
2009 ast::GenericArg::Type(_) => true,
2010 ast::GenericArg::Const(_) => true,
2014 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2015 bindings: constraints.iter()
2016 .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow()))
2018 parenthesized: false,
2020 !has_non_lt_args && param_mode == ParamMode::Optional
2024 fn lower_parenthesized_parameter_data(
2026 data: &ParenthesizedArgs,
2027 ) -> (hir::GenericArgs, bool) {
2028 // Switch to `PassThrough` mode for anonymous lifetimes; this
2029 // means that we permit things like `&Ref<T>`, where `Ref` has
2030 // a hidden lifetime parameter. This is needed for backwards
2031 // compatibility, even in contexts like an impl header where
2032 // we generally don't permit such things (see #51008).
2033 self.with_anonymous_lifetime_mode(
2034 AnonymousLifetimeMode::PassThrough,
2036 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2039 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2041 let mk_tup = |this: &mut Self, tys, span| {
2042 hir::Ty { kind: hir::TyKind::Tup(tys), hir_id: this.next_id(), span }
2046 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2049 hir_id: this.next_id(),
2050 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2051 kind: hir::TypeBindingKind::Equality {
2054 .map(|ty| this.lower_ty(
2056 ImplTraitContext::disallowed()
2059 P(mk_tup(this, hir::HirVec::new(), span))
2062 span: output.as_ref().map_or(span, |ty| ty.span),
2065 parenthesized: true,
2073 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2074 let mut ids = SmallVec::<[NodeId; 1]>::new();
2075 if self.sess.features_untracked().impl_trait_in_bindings {
2076 if let Some(ref ty) = l.ty {
2077 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2078 visitor.visit_ty(ty);
2081 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2083 hir_id: self.lower_node_id(l.id),
2086 .map(|t| self.lower_ty(t,
2087 if self.sess.features_untracked().impl_trait_in_bindings {
2088 ImplTraitContext::OpaqueTy(Some(parent_def_id))
2090 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2093 pat: self.lower_pat(&l.pat),
2094 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2096 attrs: l.attrs.clone(),
2097 source: hir::LocalSource::Normal,
2101 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2103 Mutability::Mutable => hir::MutMutable,
2104 Mutability::Immutable => hir::MutImmutable,
2108 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2109 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2110 // as they are not explicit in HIR/Ty function signatures.
2111 // (instead, the `c_variadic` flag is set to `true`)
2112 let mut inputs = &decl.inputs[..];
2113 if decl.c_variadic() {
2114 inputs = &inputs[..inputs.len() - 1];
2118 .map(|param| match param.pat.kind {
2119 PatKind::Ident(_, ident, _) => ident,
2120 _ => Ident::new(kw::Invalid, param.pat.span),
2125 // Lowers a function declaration.
2127 // `decl`: the unlowered (AST) function declaration.
2128 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2129 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2130 // `make_ret_async` is also `Some`.
2131 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2132 // This guards against trait declarations and implementations where `impl Trait` is
2134 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2135 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2136 // return type `impl Trait` item.
2140 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2141 impl_trait_return_allow: bool,
2142 make_ret_async: Option<NodeId>,
2143 ) -> P<hir::FnDecl> {
2144 let lt_mode = if make_ret_async.is_some() {
2145 // In `async fn`, argument-position elided lifetimes
2146 // must be transformed into fresh generic parameters so that
2147 // they can be applied to the opaque `impl Trait` return type.
2148 AnonymousLifetimeMode::CreateParameter
2150 self.anonymous_lifetime_mode
2153 let c_variadic = decl.c_variadic();
2155 // Remember how many lifetimes were already around so that we can
2156 // only look at the lifetime parameters introduced by the arguments.
2157 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2158 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2159 // as they are not explicit in HIR/Ty function signatures.
2160 // (instead, the `c_variadic` flag is set to `true`)
2161 let mut inputs = &decl.inputs[..];
2163 inputs = &inputs[..inputs.len() - 1];
2168 if let Some((_, ibty)) = &mut in_band_ty_params {
2169 this.lower_ty_direct(¶m.ty, ImplTraitContext::Universal(ibty))
2171 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
2174 .collect::<HirVec<_>>()
2177 let output = if let Some(ret_id) = make_ret_async {
2178 self.lower_async_fn_ret_ty(
2180 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2185 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2186 Some((def_id, _)) if impl_trait_return_allow => {
2187 hir::Return(self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(def_id))))
2190 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2193 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2201 implicit_self: decl.inputs.get(0).map_or(
2202 hir::ImplicitSelfKind::None,
2204 let is_mutable_pat = match arg.pat.kind {
2205 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2206 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2207 mt == Mutability::Mutable,
2212 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2213 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2214 // Given we are only considering `ImplicitSelf` types, we needn't consider
2215 // the case where we have a mutable pattern to a reference as that would
2216 // no longer be an `ImplicitSelf`.
2217 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() &&
2218 mt.mutbl == ast::Mutability::Mutable =>
2219 hir::ImplicitSelfKind::MutRef,
2220 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() =>
2221 hir::ImplicitSelfKind::ImmRef,
2222 _ => hir::ImplicitSelfKind::None,
2229 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
2230 // combined with the following definition of `OpaqueTy`:
2232 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
2234 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
2235 // `output`: unlowered output type (`T` in `-> T`)
2236 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2237 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
2238 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2239 fn lower_async_fn_ret_ty(
2241 output: &FunctionRetTy,
2243 opaque_ty_node_id: NodeId,
2244 ) -> hir::FunctionRetTy {
2246 "lower_async_fn_ret_ty(\
2249 opaque_ty_node_id={:?})",
2250 output, fn_def_id, opaque_ty_node_id,
2253 let span = output.span();
2255 let opaque_ty_span = self.mark_span_with_reason(
2256 DesugaringKind::Async,
2261 let opaque_ty_def_index = self
2264 .opt_def_index(opaque_ty_node_id)
2267 self.allocate_hir_id_counter(opaque_ty_node_id);
2269 // When we create the opaque type for this async fn, it is going to have
2270 // to capture all the lifetimes involved in the signature (including in the
2271 // return type). This is done by introducing lifetime parameters for:
2273 // - all the explicitly declared lifetimes from the impl and function itself;
2274 // - all the elided lifetimes in the fn arguments;
2275 // - all the elided lifetimes in the return type.
2277 // So for example in this snippet:
2280 // impl<'a> Foo<'a> {
2281 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
2282 // // ^ '0 ^ '1 ^ '2
2283 // // elided lifetimes used below
2288 // we would create an opaque type like:
2291 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
2294 // and we would then desugar `bar` to the equivalent of:
2297 // impl<'a> Foo<'a> {
2298 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
2302 // Note that the final parameter to `Bar` is `'_`, not `'2` --
2303 // this is because the elided lifetimes from the return type
2304 // should be figured out using the ordinary elision rules, and
2305 // this desugaring achieves that.
2307 // The variable `input_lifetimes_count` tracks the number of
2308 // lifetime parameters to the opaque type *not counting* those
2309 // lifetimes elided in the return type. This includes those
2310 // that are explicitly declared (`in_scope_lifetimes`) and
2311 // those elided lifetimes we found in the arguments (current
2312 // content of `lifetimes_to_define`). Next, we will process
2313 // the return type, which will cause `lifetimes_to_define` to
2315 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
2317 let (opaque_ty_id, lifetime_params) = self.with_hir_id_owner(opaque_ty_node_id, |this| {
2318 // We have to be careful to get elision right here. The
2319 // idea is that we create a lifetime parameter for each
2320 // lifetime in the return type. So, given a return type
2321 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
2322 // Future<Output = &'1 [ &'2 u32 ]>`.
2324 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
2325 // hence the elision takes place at the fn site.
2326 let future_bound = this.with_anonymous_lifetime_mode(
2327 AnonymousLifetimeMode::CreateParameter,
2328 |this| this.lower_async_fn_output_type_to_future_bound(
2335 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
2337 // Calculate all the lifetimes that should be captured
2338 // by the opaque type. This should include all in-scope
2339 // lifetime parameters, including those defined in-band.
2341 // Note: this must be done after lowering the output type,
2342 // as the output type may introduce new in-band lifetimes.
2343 let lifetime_params: Vec<(Span, ParamName)> =
2344 this.in_scope_lifetimes
2346 .map(|name| (name.ident().span, name))
2347 .chain(this.lifetimes_to_define.iter().cloned())
2350 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
2351 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
2352 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
2354 let generic_params =
2357 .map(|(span, hir_name)| {
2358 this.lifetime_to_generic_param(span, hir_name, opaque_ty_def_index)
2362 let opaque_ty_item = hir::OpaqueTy {
2363 generics: hir::Generics {
2364 params: generic_params,
2365 where_clause: hir::WhereClause {
2366 predicates: hir_vec![],
2371 bounds: hir_vec![future_bound],
2372 impl_trait_fn: Some(fn_def_id),
2373 origin: hir::OpaqueTyOrigin::AsyncFn,
2376 trace!("exist ty from async fn def index: {:#?}", opaque_ty_def_index);
2377 let opaque_ty_id = this.generate_opaque_type(
2384 (opaque_ty_id, lifetime_params)
2387 // As documented above on the variable
2388 // `input_lifetimes_count`, we need to create the lifetime
2389 // arguments to our opaque type. Continuing with our example,
2390 // we're creating the type arguments for the return type:
2393 // Bar<'a, 'b, '0, '1, '_>
2396 // For the "input" lifetime parameters, we wish to create
2397 // references to the parameters themselves, including the
2398 // "implicit" ones created from parameter types (`'a`, `'b`,
2401 // For the "output" lifetime parameters, we just want to
2403 let mut generic_args: Vec<_> =
2404 lifetime_params[..input_lifetimes_count]
2406 .map(|&(span, hir_name)| {
2407 // Input lifetime like `'a` or `'1`:
2408 GenericArg::Lifetime(hir::Lifetime {
2409 hir_id: self.next_id(),
2411 name: hir::LifetimeName::Param(hir_name),
2415 generic_args.extend(
2416 lifetime_params[input_lifetimes_count..]
2419 // Output lifetime like `'_`.
2420 GenericArg::Lifetime(hir::Lifetime {
2421 hir_id: self.next_id(),
2423 name: hir::LifetimeName::Implicit,
2428 // Create the `Foo<...>` refernece itself. Note that the `type
2429 // Foo = impl Trait` is, internally, created as a child of the
2430 // async fn, so the *type parameters* are inherited. It's
2431 // only the lifetime parameters that we must supply.
2432 let opaque_ty_ref = hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, generic_args.into());
2434 hir::FunctionRetTy::Return(P(hir::Ty {
2435 kind: opaque_ty_ref,
2437 hir_id: self.next_id(),
2441 /// Transforms `-> T` into `Future<Output = T>`
2442 fn lower_async_fn_output_type_to_future_bound(
2444 output: &FunctionRetTy,
2447 ) -> hir::GenericBound {
2448 // Compute the `T` in `Future<Output = T>` from the return type.
2449 let output_ty = match output {
2450 FunctionRetTy::Ty(ty) => {
2451 self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(fn_def_id)))
2453 FunctionRetTy::Default(ret_ty_span) => {
2455 hir_id: self.next_id(),
2456 kind: hir::TyKind::Tup(hir_vec![]),
2463 let future_params = P(hir::GenericArgs {
2465 bindings: hir_vec![hir::TypeBinding {
2466 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2467 kind: hir::TypeBindingKind::Equality {
2470 hir_id: self.next_id(),
2473 parenthesized: false,
2476 // ::std::future::Future<future_params>
2478 P(self.std_path(span, &[sym::future, sym::Future], Some(future_params), false));
2480 hir::GenericBound::Trait(
2482 trait_ref: hir::TraitRef {
2484 hir_ref_id: self.next_id(),
2486 bound_generic_params: hir_vec![],
2489 hir::TraitBoundModifier::None,
2493 fn lower_param_bound(
2496 itctx: ImplTraitContext<'_>,
2497 ) -> hir::GenericBound {
2499 GenericBound::Trait(ref ty, modifier) => {
2500 hir::GenericBound::Trait(
2501 self.lower_poly_trait_ref(ty, itctx),
2502 self.lower_trait_bound_modifier(modifier),
2505 GenericBound::Outlives(ref lifetime) => {
2506 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2511 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2512 let span = l.ident.span;
2514 ident if ident.name == kw::StaticLifetime =>
2515 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2516 ident if ident.name == kw::UnderscoreLifetime =>
2517 match self.anonymous_lifetime_mode {
2518 AnonymousLifetimeMode::CreateParameter => {
2519 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2520 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2523 AnonymousLifetimeMode::PassThrough => {
2524 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2527 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2530 self.maybe_collect_in_band_lifetime(ident);
2531 let param_name = ParamName::Plain(ident);
2532 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2537 fn new_named_lifetime(
2541 name: hir::LifetimeName,
2542 ) -> hir::Lifetime {
2544 hir_id: self.lower_node_id(id),
2550 fn lower_generic_params(
2552 params: &[GenericParam],
2553 add_bounds: &NodeMap<Vec<GenericBound>>,
2554 mut itctx: ImplTraitContext<'_>,
2555 ) -> hir::HirVec<hir::GenericParam> {
2556 params.iter().map(|param| {
2557 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2561 fn lower_generic_param(&mut self,
2562 param: &GenericParam,
2563 add_bounds: &NodeMap<Vec<GenericBound>>,
2564 mut itctx: ImplTraitContext<'_>)
2565 -> hir::GenericParam {
2566 let mut bounds = self.with_anonymous_lifetime_mode(
2567 AnonymousLifetimeMode::ReportError,
2568 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2571 let (name, kind) = match param.kind {
2572 GenericParamKind::Lifetime => {
2573 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2574 self.is_collecting_in_band_lifetimes = false;
2576 let lt = self.with_anonymous_lifetime_mode(
2577 AnonymousLifetimeMode::ReportError,
2578 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2580 let param_name = match lt.name {
2581 hir::LifetimeName::Param(param_name) => param_name,
2582 hir::LifetimeName::Implicit
2583 | hir::LifetimeName::Underscore
2584 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2585 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2588 "object-lifetime-default should not occur here",
2591 hir::LifetimeName::Error => ParamName::Error,
2594 let kind = hir::GenericParamKind::Lifetime {
2595 kind: hir::LifetimeParamKind::Explicit
2598 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2602 GenericParamKind::Type { ref default, .. } => {
2603 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2604 if !add_bounds.is_empty() {
2605 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2606 bounds = bounds.into_iter()
2611 let kind = hir::GenericParamKind::Type {
2612 default: default.as_ref().map(|x| {
2613 self.lower_ty(x, ImplTraitContext::OpaqueTy(None))
2615 synthetic: param.attrs.iter()
2616 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2617 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2621 (hir::ParamName::Plain(param.ident), kind)
2623 GenericParamKind::Const { ref ty } => {
2624 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2625 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2631 hir_id: self.lower_node_id(param.id),
2633 span: param.ident.span,
2634 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2635 attrs: self.lower_attrs(¶m.attrs),
2641 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2642 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2643 hir::QPath::Resolved(None, path) => path,
2644 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2648 hir_ref_id: self.lower_node_id(p.ref_id),
2652 fn lower_poly_trait_ref(
2655 mut itctx: ImplTraitContext<'_>,
2656 ) -> hir::PolyTraitRef {
2657 let bound_generic_params = self.lower_generic_params(
2658 &p.bound_generic_params,
2659 &NodeMap::default(),
2662 let trait_ref = self.with_in_scope_lifetime_defs(
2663 &p.bound_generic_params,
2664 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2668 bound_generic_params,
2674 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2676 ty: self.lower_ty(&mt.ty, itctx),
2677 mutbl: self.lower_mutability(mt.mutbl),
2681 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2682 -> hir::GenericBounds {
2683 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2686 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2687 let mut stmts = vec![];
2688 let mut expr = None;
2690 for (index, stmt) in b.stmts.iter().enumerate() {
2691 if index == b.stmts.len() - 1 {
2692 if let StmtKind::Expr(ref e) = stmt.kind {
2693 expr = Some(P(self.lower_expr(e)));
2695 stmts.extend(self.lower_stmt(stmt));
2698 stmts.extend(self.lower_stmt(stmt));
2703 hir_id: self.lower_node_id(b.id),
2704 stmts: stmts.into(),
2706 rules: self.lower_block_check_mode(&b.rules),
2712 /// Lowers a block directly to an expression, presuming that it
2713 /// has no attributes and is not targeted by a `break`.
2714 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr {
2715 let block = self.lower_block(b, false);
2716 self.expr_block(block, ThinVec::new())
2719 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2720 let node = match p.kind {
2721 PatKind::Wild => hir::PatKind::Wild,
2722 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2723 let lower_sub = |this: &mut Self| sub.as_ref().map(|x| this.lower_pat(x));
2724 self.lower_pat_ident(p, binding_mode, ident, lower_sub)
2726 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
2727 PatKind::TupleStruct(ref path, ref pats) => {
2728 let qpath = self.lower_qpath(
2732 ParamMode::Optional,
2733 ImplTraitContext::disallowed(),
2735 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple struct");
2736 hir::PatKind::TupleStruct(qpath, pats, ddpos)
2738 PatKind::Or(ref pats) => {
2739 hir::PatKind::Or(pats.iter().map(|x| self.lower_pat(x)).collect())
2741 PatKind::Path(ref qself, ref path) => {
2742 let qpath = self.lower_qpath(
2746 ParamMode::Optional,
2747 ImplTraitContext::disallowed(),
2749 hir::PatKind::Path(qpath)
2751 PatKind::Struct(ref path, ref fields, etc) => {
2752 let qpath = self.lower_qpath(
2756 ParamMode::Optional,
2757 ImplTraitContext::disallowed(),
2762 .map(|f| hir::FieldPat {
2763 hir_id: self.next_id(),
2765 pat: self.lower_pat(&f.pat),
2766 is_shorthand: f.is_shorthand,
2770 hir::PatKind::Struct(qpath, fs, etc)
2772 PatKind::Tuple(ref pats) => {
2773 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple");
2774 hir::PatKind::Tuple(pats, ddpos)
2776 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
2777 PatKind::Ref(ref inner, mutbl) => {
2778 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
2780 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
2781 P(self.lower_expr(e1)),
2782 P(self.lower_expr(e2)),
2783 self.lower_range_end(end),
2785 PatKind::Slice(ref pats) => self.lower_pat_slice(pats),
2787 // If we reach here the `..` pattern is not semantically allowed.
2788 self.ban_illegal_rest_pat(p.span)
2790 PatKind::Paren(ref inner) => return self.lower_pat(inner),
2791 PatKind::Mac(_) => panic!("Shouldn't exist here"),
2794 self.pat_with_node_id_of(p, node)
2801 ) -> (HirVec<P<hir::Pat>>, Option<usize>) {
2802 let mut elems = Vec::with_capacity(pats.len());
2803 let mut rest = None;
2805 let mut iter = pats.iter().enumerate();
2806 while let Some((idx, pat)) = iter.next() {
2807 // Interpret the first `..` pattern as a subtuple pattern.
2809 rest = Some((idx, pat.span));
2812 // It was not a subslice pattern so lower it normally.
2813 elems.push(self.lower_pat(pat));
2816 while let Some((_, pat)) = iter.next() {
2817 // There was a previous subtuple pattern; make sure we don't allow more.
2819 self.ban_extra_rest_pat(pat.span, rest.unwrap().1, ctx);
2821 elems.push(self.lower_pat(pat));
2825 (elems.into(), rest.map(|(ddpos, _)| ddpos))
2828 fn lower_pat_slice(&mut self, pats: &[AstP<Pat>]) -> hir::PatKind {
2829 let mut before = Vec::new();
2830 let mut after = Vec::new();
2831 let mut slice = None;
2832 let mut prev_rest_span = None;
2834 let mut iter = pats.iter();
2835 while let Some(pat) = iter.next() {
2836 // Interpret the first `((ref mut?)? x @)? ..` pattern as a subslice pattern.
2839 prev_rest_span = Some(pat.span);
2840 slice = Some(self.pat_wild_with_node_id_of(pat));
2843 PatKind::Ident(ref bm, ident, Some(ref sub)) if sub.is_rest() => {
2844 prev_rest_span = Some(sub.span);
2845 let lower_sub = |this: &mut Self| Some(this.pat_wild_with_node_id_of(sub));
2846 let node = self.lower_pat_ident(pat, bm, ident, lower_sub);
2847 slice = Some(self.pat_with_node_id_of(pat, node));
2853 // It was not a subslice pattern so lower it normally.
2854 before.push(self.lower_pat(pat));
2857 while let Some(pat) = iter.next() {
2858 // There was a previous subslice pattern; make sure we don't allow more.
2859 let rest_span = match pat.kind {
2860 PatKind::Rest => Some(pat.span),
2861 PatKind::Ident(.., Some(ref sub)) if sub.is_rest() => {
2862 // The `HirValidator` is merciless; add a `_` pattern to avoid ICEs.
2863 after.push(self.pat_wild_with_node_id_of(pat));
2868 if let Some(rest_span) = rest_span {
2869 self.ban_extra_rest_pat(rest_span, prev_rest_span.unwrap(), "slice");
2871 after.push(self.lower_pat(pat));
2875 hir::PatKind::Slice(before.into(), slice, after.into())
2881 binding_mode: &BindingMode,
2883 lower_sub: impl FnOnce(&mut Self) -> Option<P<hir::Pat>>,
2885 match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
2886 // `None` can occur in body-less function signatures
2887 res @ None | res @ Some(Res::Local(_)) => {
2888 let canonical_id = match res {
2889 Some(Res::Local(id)) => id,
2893 hir::PatKind::Binding(
2894 self.lower_binding_mode(binding_mode),
2895 self.lower_node_id(canonical_id),
2900 Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
2904 res: self.lower_res(res),
2905 segments: hir_vec![hir::PathSegment::from_ident(ident)],
2911 fn pat_wild_with_node_id_of(&mut self, p: &Pat) -> P<hir::Pat> {
2912 self.pat_with_node_id_of(p, hir::PatKind::Wild)
2915 /// Construct a `Pat` with the `HirId` of `p.id` lowered.
2916 fn pat_with_node_id_of(&mut self, p: &Pat, kind: hir::PatKind) -> P<hir::Pat> {
2918 hir_id: self.lower_node_id(p.id),
2924 /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern.
2925 fn ban_extra_rest_pat(&self, sp: Span, prev_sp: Span, ctx: &str) {
2927 .struct_span_err(sp, &format!("`..` can only be used once per {} pattern", ctx))
2928 .span_label(sp, &format!("can only be used once per {} pattern", ctx))
2929 .span_label(prev_sp, "previously used here")
2933 /// Used to ban the `..` pattern in places it shouldn't be semantically.
2934 fn ban_illegal_rest_pat(&self, sp: Span) -> hir::PatKind {
2936 .struct_span_err(sp, "`..` patterns are not allowed here")
2937 .note("only allowed in tuple, tuple struct, and slice patterns")
2940 // We're not in a list context so `..` can be reasonably treated
2941 // as `_` because it should always be valid and roughly matches the
2942 // intent of `..` (notice that the rest of a single slot is that slot).
2946 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
2948 RangeEnd::Included(_) => hir::RangeEnd::Included,
2949 RangeEnd::Excluded => hir::RangeEnd::Excluded,
2953 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2954 self.with_new_scopes(|this| {
2956 hir_id: this.lower_node_id(c.id),
2957 body: this.lower_const_body(&c.value),
2962 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
2963 let kind = match s.kind {
2964 StmtKind::Local(ref l) => {
2965 let (l, item_ids) = self.lower_local(l);
2966 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
2969 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
2970 self.stmt(s.span, hir::StmtKind::Item(item_id))
2975 hir_id: self.lower_node_id(s.id),
2976 kind: hir::StmtKind::Local(P(l)),
2982 StmtKind::Item(ref it) => {
2983 // Can only use the ID once.
2984 let mut id = Some(s.id);
2985 return self.lower_item_id(it)
2988 let hir_id = id.take()
2989 .map(|id| self.lower_node_id(id))
2990 .unwrap_or_else(|| self.next_id());
2994 kind: hir::StmtKind::Item(item_id),
3000 StmtKind::Expr(ref e) => hir::StmtKind::Expr(P(self.lower_expr(e))),
3001 StmtKind::Semi(ref e) => hir::StmtKind::Semi(P(self.lower_expr(e))),
3002 StmtKind::Mac(..) => panic!("shouldn't exist here"),
3004 smallvec![hir::Stmt {
3005 hir_id: self.lower_node_id(s.id),
3011 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3013 BlockCheckMode::Default => hir::DefaultBlock,
3014 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3018 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3020 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3021 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3022 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3023 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3027 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3029 CompilerGenerated => hir::CompilerGenerated,
3030 UserProvided => hir::UserProvided,
3034 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3036 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3037 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3041 // Helper methods for building HIR.
3043 fn stmt(&mut self, span: Span, kind: hir::StmtKind) -> hir::Stmt {
3044 hir::Stmt { span, kind, hir_id: self.next_id() }
3047 fn stmt_expr(&mut self, span: Span, expr: hir::Expr) -> hir::Stmt {
3048 self.stmt(span, hir::StmtKind::Expr(P(expr)))
3053 attrs: ThinVec<Attribute>,
3055 init: Option<P<hir::Expr>>,
3057 source: hir::LocalSource,
3059 let local = hir::Local {
3061 hir_id: self.next_id(),
3068 self.stmt(span, hir::StmtKind::Local(P(local)))
3071 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
3072 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
3078 stmts: hir::HirVec<hir::Stmt>,
3079 expr: Option<P<hir::Expr>>,
3084 hir_id: self.next_id(),
3085 rules: hir::DefaultBlock,
3087 targeted_by_break: false,
3091 /// Constructs a `true` or `false` literal pattern.
3092 fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
3093 let expr = self.expr_bool(span, val);
3094 self.pat(span, hir::PatKind::Lit(P(expr)))
3097 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3098 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
3101 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3102 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
3105 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3106 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
3109 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
3110 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
3116 components: &[Symbol],
3117 subpats: hir::HirVec<P<hir::Pat>>,
3119 let path = self.std_path(span, components, None, true);
3120 let qpath = hir::QPath::Resolved(None, P(path));
3121 let pt = if subpats.is_empty() {
3122 hir::PatKind::Path(qpath)
3124 hir::PatKind::TupleStruct(qpath, subpats, None)
3129 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
3130 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
3133 fn pat_ident_binding_mode(
3137 bm: hir::BindingAnnotation,
3138 ) -> (P<hir::Pat>, hir::HirId) {
3139 let hir_id = self.next_id();
3144 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
3151 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
3152 self.pat(span, hir::PatKind::Wild)
3155 fn pat(&mut self, span: Span, kind: hir::PatKind) -> P<hir::Pat> {
3157 hir_id: self.next_id(),
3163 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
3164 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
3165 /// The path is also resolved according to `is_value`.
3169 components: &[Symbol],
3170 params: Option<P<hir::GenericArgs>>,
3173 let ns = if is_value { Namespace::ValueNS } else { Namespace::TypeNS };
3174 let (path, res) = self.resolver.resolve_str_path(span, self.crate_root, components, ns);
3176 let mut segments: Vec<_> = path.segments.iter().map(|segment| {
3177 let res = self.expect_full_res(segment.id);
3179 ident: segment.ident,
3180 hir_id: Some(self.lower_node_id(segment.id)),
3181 res: Some(self.lower_res(res)),
3186 segments.last_mut().unwrap().args = params;
3190 res: res.map_id(|_| panic!("unexpected `NodeId`")),
3191 segments: segments.into(),
3195 fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
3196 let kind = match qpath {
3197 hir::QPath::Resolved(None, path) => {
3198 // Turn trait object paths into `TyKind::TraitObject` instead.
3200 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
3201 let principal = hir::PolyTraitRef {
3202 bound_generic_params: hir::HirVec::new(),
3203 trait_ref: hir::TraitRef {
3210 // The original ID is taken by the `PolyTraitRef`,
3211 // so the `Ty` itself needs a different one.
3212 hir_id = self.next_id();
3213 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
3215 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
3218 _ => hir::TyKind::Path(qpath),
3228 /// Invoked to create the lifetime argument for a type `&T`
3229 /// with no explicit lifetime.
3230 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
3231 match self.anonymous_lifetime_mode {
3232 // Intercept when we are in an impl header or async fn and introduce an in-band
3234 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
3236 AnonymousLifetimeMode::CreateParameter => {
3237 let fresh_name = self.collect_fresh_in_band_lifetime(span);
3239 hir_id: self.next_id(),
3241 name: hir::LifetimeName::Param(fresh_name),
3245 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
3247 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
3251 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
3252 /// return a "error lifetime".
3253 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
3254 let (id, msg, label) = match id {
3255 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
3258 self.sess.next_node_id(),
3259 "`&` without an explicit lifetime name cannot be used here",
3260 "explicit lifetime name needed here",
3264 let mut err = struct_span_err!(
3271 err.span_label(span, label);
3274 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3277 /// Invoked to create the lifetime argument(s) for a path like
3278 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
3279 /// sorts of cases are deprecated. This may therefore report a warning or an
3280 /// error, depending on the mode.
3281 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
3283 .map(|_| self.elided_path_lifetime(span))
3287 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
3288 match self.anonymous_lifetime_mode {
3289 AnonymousLifetimeMode::CreateParameter => {
3290 // We should have emitted E0726 when processing this path above
3291 self.sess.delay_span_bug(
3293 "expected 'implicit elided lifetime not allowed' error",
3295 let id = self.sess.next_node_id();
3296 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3298 // `PassThrough` is the normal case.
3299 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
3300 // is unsuitable here, as these can occur from missing lifetime parameters in a
3301 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
3302 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
3303 // later, at which point a suitable error will be emitted.
3304 | AnonymousLifetimeMode::PassThrough
3305 | AnonymousLifetimeMode::ReportError => self.new_implicit_lifetime(span),
3309 /// Invoked to create the lifetime argument(s) for an elided trait object
3310 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
3311 /// when the bound is written, even if it is written with `'_` like in
3312 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
3313 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
3314 match self.anonymous_lifetime_mode {
3315 // NB. We intentionally ignore the create-parameter mode here.
3316 // and instead "pass through" to resolve-lifetimes, which will apply
3317 // the object-lifetime-defaulting rules. Elided object lifetime defaults
3318 // do not act like other elided lifetimes. In other words, given this:
3320 // impl Foo for Box<dyn Debug>
3322 // we do not introduce a fresh `'_` to serve as the bound, but instead
3323 // ultimately translate to the equivalent of:
3325 // impl Foo for Box<dyn Debug + 'static>
3327 // `resolve_lifetime` has the code to make that happen.
3328 AnonymousLifetimeMode::CreateParameter => {}
3330 AnonymousLifetimeMode::ReportError => {
3331 // ReportError applies to explicit use of `'_`.
3334 // This is the normal case.
3335 AnonymousLifetimeMode::PassThrough => {}
3338 let r = hir::Lifetime {
3339 hir_id: self.next_id(),
3341 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
3343 debug!("elided_dyn_bound: r={:?}", r);
3347 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
3349 hir_id: self.next_id(),
3351 name: hir::LifetimeName::Implicit,
3355 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
3356 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
3357 // call site which do not have a macro backtrace. See #61963.
3358 let is_macro_callsite = self.sess.source_map()
3359 .span_to_snippet(span)
3360 .map(|snippet| snippet.starts_with("#["))
3362 if !is_macro_callsite {
3363 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
3364 builtin::BARE_TRAIT_OBJECTS,
3367 "trait objects without an explicit `dyn` are deprecated",
3368 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
3374 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
3375 // Sorting by span ensures that we get things in order within a
3376 // file, and also puts the files in a sensible order.
3377 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
3378 body_ids.sort_by_key(|b| bodies[b].value.span);
3382 /// Checks if the specified expression is a built-in range literal.
3383 /// (See: `LoweringContext::lower_expr()`).
3384 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
3385 use hir::{Path, QPath, ExprKind, TyKind};
3387 // Returns whether the given path represents a (desugared) range,
3388 // either in std or core, i.e. has either a `::std::ops::Range` or
3389 // `::core::ops::Range` prefix.
3390 fn is_range_path(path: &Path) -> bool {
3391 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
3392 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
3394 // "{{root}}" is the equivalent of `::` prefix in `Path`.
3395 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
3396 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
3402 // Check whether a span corresponding to a range expression is a
3403 // range literal, rather than an explicit struct or `new()` call.
3404 fn is_lit(sess: &Session, span: &Span) -> bool {
3405 let source_map = sess.source_map();
3406 let end_point = source_map.end_point(*span);
3408 if let Ok(end_string) = source_map.span_to_snippet(end_point) {
3409 !(end_string.ends_with("}") || end_string.ends_with(")"))
3416 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
3417 ExprKind::Struct(ref qpath, _, _) => {
3418 if let QPath::Resolved(None, ref path) = **qpath {
3419 return is_range_path(&path) && is_lit(sess, &expr.span);
3423 // `..` desugars to its struct path.
3424 ExprKind::Path(QPath::Resolved(None, ref path)) => {
3425 return is_range_path(&path) && is_lit(sess, &expr.span);
3428 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
3429 ExprKind::Call(ref func, _) => {
3430 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
3431 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
3432 let new_call = segment.ident.name == sym::new;
3433 return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;