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;
46 use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
47 ELIDED_LIFETIMES_IN_PATHS};
48 use crate::middle::cstore::CrateStore;
49 use crate::session::Session;
50 use crate::session::config::nightly_options;
51 use crate::util::common::FN_OUTPUT_NAME;
52 use crate::util::nodemap::{DefIdMap, NodeMap};
53 use errors::Applicability;
54 use rustc_data_structures::fx::FxHashSet;
55 use rustc_data_structures::indexed_vec::IndexVec;
56 use rustc_data_structures::thin_vec::ThinVec;
57 use rustc_data_structures::sync::Lrc;
59 use std::collections::BTreeMap;
61 use smallvec::SmallVec;
64 use syntax::ptr::P as AstP;
67 use syntax::ext::base::SpecialDerives;
68 use syntax::ext::hygiene::ExpnId;
69 use syntax::print::pprust;
70 use syntax::source_map::{respan, ExpnData, ExpnKind, DesugaringKind, Spanned};
71 use syntax::symbol::{kw, sym, Symbol};
72 use syntax::tokenstream::{TokenStream, TokenTree};
73 use syntax::parse::token::{self, Token};
74 use syntax::visit::{self, Visitor};
77 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
79 pub struct LoweringContext<'a> {
80 crate_root: Option<Symbol>,
82 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
85 cstore: &'a dyn CrateStore,
87 resolver: &'a mut dyn Resolver,
89 /// The items being lowered are collected here.
90 items: BTreeMap<hir::HirId, hir::Item>,
92 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
93 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
94 bodies: BTreeMap<hir::BodyId, hir::Body>,
95 exported_macros: Vec<hir::MacroDef>,
96 non_exported_macro_attrs: Vec<ast::Attribute>,
98 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
100 modules: BTreeMap<NodeId, hir::ModuleItems>,
102 generator_kind: Option<hir::GeneratorKind>,
104 /// Used to get the current `fn`'s def span to point to when using `await`
105 /// outside of an `async fn`.
106 current_item: Option<Span>,
108 catch_scopes: Vec<NodeId>,
109 loop_scopes: Vec<NodeId>,
110 is_in_loop_condition: bool,
111 is_in_trait_impl: bool,
112 is_in_dyn_type: bool,
114 /// What to do when we encounter either an "anonymous lifetime
115 /// reference". The term "anonymous" is meant to encompass both
116 /// `'_` lifetimes as well as fully elided cases where nothing is
117 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
118 anonymous_lifetime_mode: AnonymousLifetimeMode,
120 /// Used to create lifetime definitions from in-band lifetime usages.
121 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
122 /// When a named lifetime is encountered in a function or impl header and
123 /// has not been defined
124 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
125 /// to this list. The results of this list are then added to the list of
126 /// lifetime definitions in the corresponding impl or function generics.
127 lifetimes_to_define: Vec<(Span, ParamName)>,
129 /// `true` if in-band lifetimes are being collected. This is used to
130 /// indicate whether or not we're in a place where new lifetimes will result
131 /// in in-band lifetime definitions, such a function or an impl header,
132 /// including implicit lifetimes from `impl_header_lifetime_elision`.
133 is_collecting_in_band_lifetimes: bool,
135 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
136 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
137 /// against this list to see if it is already in-scope, or if a definition
138 /// needs to be created for it.
140 /// We always store a `modern()` version of the param-name in this
142 in_scope_lifetimes: Vec<ParamName>,
144 current_module: NodeId,
146 type_def_lifetime_params: DefIdMap<usize>,
148 current_hir_id_owner: Vec<(DefIndex, u32)>,
149 item_local_id_counters: NodeMap<u32>,
150 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
152 allow_try_trait: Option<Lrc<[Symbol]>>,
153 allow_gen_future: Option<Lrc<[Symbol]>>,
157 /// Obtains resolution for a `NodeId` with a single resolution.
158 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
160 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
161 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
163 /// Obtains resolution for a label with the given `NodeId`.
164 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
166 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
167 /// This should only return `None` during testing.
168 fn definitions(&mut self) -> &mut Definitions;
170 /// Given suffix `["b", "c", "d"]`, creates an AST path for `[::crate_root]::b::c::d` and
171 /// resolves it based on `is_value`.
175 crate_root: Option<Symbol>,
176 components: &[Symbol],
178 ) -> (ast::Path, Res<NodeId>);
180 fn has_derives(&self, node_id: NodeId, derives: SpecialDerives) -> bool;
183 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
184 /// and if so, what meaning it has.
186 enum ImplTraitContext<'a> {
187 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
188 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
189 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
191 /// Newly generated parameters should be inserted into the given `Vec`.
192 Universal(&'a mut Vec<hir::GenericParam>),
194 /// Treat `impl Trait` as shorthand for a new opaque type.
195 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
196 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
198 /// We optionally store a `DefId` for the parent item here so we can look up necessary
199 /// information later. It is `None` when no information about the context should be stored
200 /// (e.g., for consts and statics).
201 OpaqueTy(Option<DefId> /* fn def-ID */),
203 /// `impl Trait` is not accepted in this position.
204 Disallowed(ImplTraitPosition),
207 /// Position in which `impl Trait` is disallowed.
208 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
209 enum ImplTraitPosition {
210 /// Disallowed in `let` / `const` / `static` bindings.
213 /// All other posiitons.
217 impl<'a> ImplTraitContext<'a> {
219 fn disallowed() -> Self {
220 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
223 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
224 use self::ImplTraitContext::*;
226 Universal(params) => Universal(params),
227 OpaqueTy(fn_def_id) => OpaqueTy(*fn_def_id),
228 Disallowed(pos) => Disallowed(*pos),
235 cstore: &dyn CrateStore,
236 dep_graph: &DepGraph,
238 resolver: &mut dyn Resolver,
240 // We're constructing the HIR here; we don't care what we will
241 // read, since we haven't even constructed the *input* to
243 dep_graph.assert_ignored();
246 crate_root: sess.parse_sess.injected_crate_name.try_get().copied(),
250 items: BTreeMap::new(),
251 trait_items: BTreeMap::new(),
252 impl_items: BTreeMap::new(),
253 bodies: BTreeMap::new(),
254 trait_impls: BTreeMap::new(),
255 modules: BTreeMap::new(),
256 exported_macros: Vec::new(),
257 non_exported_macro_attrs: Vec::new(),
258 catch_scopes: Vec::new(),
259 loop_scopes: Vec::new(),
260 is_in_loop_condition: false,
261 is_in_trait_impl: false,
262 is_in_dyn_type: false,
263 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
264 type_def_lifetime_params: Default::default(),
265 current_module: CRATE_NODE_ID,
266 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
267 item_local_id_counters: Default::default(),
268 node_id_to_hir_id: IndexVec::new(),
269 generator_kind: None,
271 lifetimes_to_define: Vec::new(),
272 is_collecting_in_band_lifetimes: false,
273 in_scope_lifetimes: Vec::new(),
274 allow_try_trait: Some([sym::try_trait][..].into()),
275 allow_gen_future: Some([sym::gen_future][..].into()),
279 #[derive(Copy, Clone, PartialEq)]
281 /// Any path in a type context.
283 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
285 /// The `module::Type` in `module::Type::method` in an expression.
289 enum ParenthesizedGenericArgs {
295 /// What to do when we encounter an **anonymous** lifetime
296 /// reference. Anonymous lifetime references come in two flavors. You
297 /// have implicit, or fully elided, references to lifetimes, like the
298 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
299 /// or `Ref<'_, T>`. These often behave the same, but not always:
301 /// - certain usages of implicit references are deprecated, like
302 /// `Ref<T>`, and we sometimes just give hard errors in those cases
304 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
305 /// the same as `Box<dyn Foo + '_>`.
307 /// We describe the effects of the various modes in terms of three cases:
309 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
310 /// of a `&` (e.g., the missing lifetime in something like `&T`)
311 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
312 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
313 /// elided bounds follow special rules. Note that this only covers
314 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
315 /// '_>` is a case of "modern" elision.
316 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
317 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
318 /// non-deprecated equivalent.
320 /// Currently, the handling of lifetime elision is somewhat spread out
321 /// between HIR lowering and -- as described below -- the
322 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
323 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
324 /// everything into HIR lowering.
325 #[derive(Copy, Clone, Debug)]
326 enum AnonymousLifetimeMode {
327 /// For **Modern** cases, create a new anonymous region parameter
328 /// and reference that.
330 /// For **Dyn Bound** cases, pass responsibility to
331 /// `resolve_lifetime` code.
333 /// For **Deprecated** cases, report an error.
336 /// Give a hard error when either `&` or `'_` is written. Used to
337 /// rule out things like `where T: Foo<'_>`. Does not imply an
338 /// error on default object bounds (e.g., `Box<dyn Foo>`).
341 /// Pass responsibility to `resolve_lifetime` code for all cases.
345 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
347 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
348 fn visit_ty(&mut self, ty: &'a Ty) {
354 TyKind::ImplTrait(id, _) => self.ids.push(id),
357 visit::walk_ty(self, ty);
360 fn visit_path_segment(
363 path_segment: &'v PathSegment,
365 if let Some(ref p) = path_segment.args {
366 if let GenericArgs::Parenthesized(_) = **p {
370 visit::walk_path_segment(self, path_span, path_segment)
374 impl<'a> LoweringContext<'a> {
375 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
376 /// Full-crate AST visitor that inserts into a fresh
377 /// `LoweringContext` any information that may be
378 /// needed from arbitrary locations in the crate,
379 /// e.g., the number of lifetime generic parameters
380 /// declared for every type and trait definition.
381 struct MiscCollector<'tcx, 'interner> {
382 lctx: &'tcx mut LoweringContext<'interner>,
383 hir_id_owner: Option<NodeId>,
386 impl MiscCollector<'_, '_> {
387 fn allocate_use_tree_hir_id_counters(
393 UseTreeKind::Simple(_, id1, id2) => {
394 for &id in &[id1, id2] {
395 self.lctx.resolver.definitions().create_def_with_parent(
402 self.lctx.allocate_hir_id_counter(id);
405 UseTreeKind::Glob => (),
406 UseTreeKind::Nested(ref trees) => {
407 for &(ref use_tree, id) in trees {
408 let hir_id = self.lctx.allocate_hir_id_counter(id);
409 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
415 fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
417 F: FnOnce(&mut Self) -> T,
419 let old = mem::replace(&mut self.hir_id_owner, owner);
421 self.hir_id_owner = old;
426 impl<'tcx, 'interner> Visitor<'tcx> for MiscCollector<'tcx, 'interner> {
427 fn visit_pat(&mut self, p: &'tcx Pat) {
428 if let PatKind::Paren(..) | PatKind::Rest = p.node {
429 // Doesn't generate a HIR node
430 } else if let Some(owner) = self.hir_id_owner {
431 self.lctx.lower_node_id_with_owner(p.id, owner);
434 visit::walk_pat(self, p)
437 // HACK(or_patterns; Centril | dlrobertson): Avoid creating
438 // HIR nodes for `PatKind::Or` for the top level of a `ast::Arm`.
439 // This is a temporary hack that should go away once we push down
440 // `arm.pats: HirVec<P<Pat>>` -> `arm.pat: P<Pat>` to HIR. // Centril
441 fn visit_arm(&mut self, arm: &'tcx Arm) {
442 match &arm.pat.node {
443 PatKind::Or(pats) => pats.iter().for_each(|p| self.visit_pat(p)),
444 _ => self.visit_pat(&arm.pat),
446 walk_list!(self, visit_expr, &arm.guard);
447 self.visit_expr(&arm.body);
448 walk_list!(self, visit_attribute, &arm.attrs);
451 // HACK(or_patterns; Centril | dlrobertson): Same as above. // Centril
452 fn visit_expr(&mut self, e: &'tcx Expr) {
453 if let ExprKind::Let(pat, scrutinee) = &e.node {
454 walk_list!(self, visit_attribute, e.attrs.iter());
456 PatKind::Or(pats) => pats.iter().for_each(|p| self.visit_pat(p)),
457 _ => self.visit_pat(&pat),
459 self.visit_expr(scrutinee);
460 self.visit_expr_post(e);
463 visit::walk_expr(self, e)
466 fn visit_item(&mut self, item: &'tcx Item) {
467 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
470 ItemKind::Struct(_, ref generics)
471 | ItemKind::Union(_, ref generics)
472 | ItemKind::Enum(_, ref generics)
473 | ItemKind::TyAlias(_, ref generics)
474 | ItemKind::OpaqueTy(_, ref generics)
475 | ItemKind::Trait(_, _, ref generics, ..) => {
476 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
480 .filter(|param| match param.kind {
481 ast::GenericParamKind::Lifetime { .. } => true,
485 self.lctx.type_def_lifetime_params.insert(def_id, count);
487 ItemKind::Use(ref use_tree) => {
488 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
493 self.with_hir_id_owner(Some(item.id), |this| {
494 visit::walk_item(this, item);
498 fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
499 self.lctx.allocate_hir_id_counter(item.id);
502 TraitItemKind::Method(_, None) => {
503 // Ignore patterns in trait methods without bodies
504 self.with_hir_id_owner(None, |this| {
505 visit::walk_trait_item(this, item)
508 _ => self.with_hir_id_owner(Some(item.id), |this| {
509 visit::walk_trait_item(this, item);
514 fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
515 self.lctx.allocate_hir_id_counter(item.id);
516 self.with_hir_id_owner(Some(item.id), |this| {
517 visit::walk_impl_item(this, item);
521 fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) {
522 // Ignore patterns in foreign items
523 self.with_hir_id_owner(None, |this| {
524 visit::walk_foreign_item(this, i)
528 fn visit_ty(&mut self, t: &'tcx Ty) {
530 // Mirrors the case in visit::walk_ty
531 TyKind::BareFn(ref f) => {
537 // Mirrors visit::walk_fn_decl
538 for parameter in &f.decl.inputs {
539 // We don't lower the ids of argument patterns
540 self.with_hir_id_owner(None, |this| {
541 this.visit_pat(¶meter.pat);
543 self.visit_ty(¶meter.ty)
545 self.visit_fn_ret_ty(&f.decl.output)
547 _ => visit::walk_ty(self, t),
552 self.lower_node_id(CRATE_NODE_ID);
553 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
555 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
556 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
558 let module = self.lower_mod(&c.module);
559 let attrs = self.lower_attrs(&c.attrs);
560 let body_ids = body_ids(&self.bodies);
564 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
570 exported_macros: hir::HirVec::from(self.exported_macros),
571 non_exported_macro_attrs: hir::HirVec::from(self.non_exported_macro_attrs),
573 trait_items: self.trait_items,
574 impl_items: self.impl_items,
577 trait_impls: self.trait_impls,
578 modules: self.modules,
582 fn insert_item(&mut self, item: hir::Item) {
583 let id = item.hir_id;
584 // FIXME: Use `debug_asset-rt`.
585 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
586 self.items.insert(id, item);
587 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
590 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
591 // Set up the counter if needed.
592 self.item_local_id_counters.entry(owner).or_insert(0);
593 // Always allocate the first `HirId` for the owner itself.
594 let lowered = self.lower_node_id_with_owner(owner, owner);
595 debug_assert_eq!(lowered.local_id.as_u32(), 0);
599 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> hir::HirId
601 F: FnOnce(&mut Self) -> hir::HirId,
603 if ast_node_id == DUMMY_NODE_ID {
604 return hir::DUMMY_HIR_ID;
607 let min_size = ast_node_id.as_usize() + 1;
609 if min_size > self.node_id_to_hir_id.len() {
610 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
613 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
615 if existing_hir_id == hir::DUMMY_HIR_ID {
616 // Generate a new `HirId`.
617 let hir_id = alloc_hir_id(self);
618 self.node_id_to_hir_id[ast_node_id] = hir_id;
626 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
628 F: FnOnce(&mut Self) -> T,
630 let counter = self.item_local_id_counters
631 .insert(owner, HIR_ID_COUNTER_LOCKED)
632 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
633 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
634 self.current_hir_id_owner.push((def_index, counter));
636 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
638 debug_assert!(def_index == new_def_index);
639 debug_assert!(new_counter >= counter);
641 let prev = self.item_local_id_counters
642 .insert(owner, new_counter)
644 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
648 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
649 /// the `LoweringContext`'s `NodeId => HirId` map.
650 /// Take care not to call this method if the resulting `HirId` is then not
651 /// actually used in the HIR, as that would trigger an assertion in the
652 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
653 /// properly. Calling the method twice with the same `NodeId` is fine though.
654 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
655 self.lower_node_id_generic(ast_node_id, |this| {
656 let &mut (def_index, ref mut local_id_counter) =
657 this.current_hir_id_owner.last_mut().unwrap();
658 let local_id = *local_id_counter;
659 *local_id_counter += 1;
662 local_id: hir::ItemLocalId::from_u32(local_id),
667 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
668 self.lower_node_id_generic(ast_node_id, |this| {
669 let local_id_counter = this
670 .item_local_id_counters
672 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
673 let local_id = *local_id_counter;
675 // We want to be sure not to modify the counter in the map while it
676 // is also on the stack. Otherwise we'll get lost updates when writing
677 // back from the stack to the map.
678 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
680 *local_id_counter += 1;
684 .opt_def_index(owner)
685 .expect("you forgot to call `create_def_with_parent` or are lowering node-IDs \
686 that do not belong to the current owner");
690 local_id: hir::ItemLocalId::from_u32(local_id),
695 fn next_id(&mut self) -> hir::HirId {
696 self.lower_node_id(self.sess.next_node_id())
699 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
701 self.lower_node_id_generic(id, |_| {
702 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
707 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
708 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
709 if pr.unresolved_segments() != 0 {
710 bug!("path not fully resolved: {:?}", pr);
716 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
717 self.resolver.get_import_res(id).present_items()
720 fn diagnostic(&self) -> &errors::Handler {
721 self.sess.diagnostic()
724 /// Reuses the span but adds information like the kind of the desugaring and features that are
725 /// allowed inside this span.
726 fn mark_span_with_reason(
728 reason: DesugaringKind,
730 allow_internal_unstable: Option<Lrc<[Symbol]>>,
732 span.fresh_expansion(ExpnData {
733 allow_internal_unstable,
734 ..ExpnData::default(ExpnKind::Desugaring(reason), span, self.sess.edition())
738 fn with_anonymous_lifetime_mode<R>(
740 anonymous_lifetime_mode: AnonymousLifetimeMode,
741 op: impl FnOnce(&mut Self) -> R,
744 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
745 anonymous_lifetime_mode,
747 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
748 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
749 let result = op(self);
750 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
751 debug!("with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
752 old_anonymous_lifetime_mode);
756 /// Creates a new `hir::GenericParam` for every new lifetime and
757 /// type parameter encountered while evaluating `f`. Definitions
758 /// are created with the parent provided. If no `parent_id` is
759 /// provided, no definitions will be returned.
761 /// Presuming that in-band lifetimes are enabled, then
762 /// `self.anonymous_lifetime_mode` will be updated to match the
763 /// parameter while `f` is running (and restored afterwards).
764 fn collect_in_band_defs<T, F>(
767 anonymous_lifetime_mode: AnonymousLifetimeMode,
769 ) -> (Vec<hir::GenericParam>, T)
771 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
773 assert!(!self.is_collecting_in_band_lifetimes);
774 assert!(self.lifetimes_to_define.is_empty());
775 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
777 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
778 self.is_collecting_in_band_lifetimes = true;
780 let (in_band_ty_params, res) = f(self);
782 self.is_collecting_in_band_lifetimes = false;
783 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
785 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
787 let params = lifetimes_to_define
789 .map(|(span, hir_name)| self.lifetime_to_generic_param(
790 span, hir_name, parent_id.index,
792 .chain(in_band_ty_params.into_iter())
798 /// Converts a lifetime into a new generic parameter.
799 fn lifetime_to_generic_param(
803 parent_index: DefIndex,
804 ) -> hir::GenericParam {
805 let node_id = self.sess.next_node_id();
807 // Get the name we'll use to make the def-path. Note
808 // that collisions are ok here and this shouldn't
809 // really show up for end-user.
810 let (str_name, kind) = match hir_name {
811 ParamName::Plain(ident) => (
812 ident.as_interned_str(),
813 hir::LifetimeParamKind::InBand,
815 ParamName::Fresh(_) => (
816 kw::UnderscoreLifetime.as_interned_str(),
817 hir::LifetimeParamKind::Elided,
819 ParamName::Error => (
820 kw::UnderscoreLifetime.as_interned_str(),
821 hir::LifetimeParamKind::Error,
825 // Add a definition for the in-band lifetime def.
826 self.resolver.definitions().create_def_with_parent(
829 DefPathData::LifetimeNs(str_name),
835 hir_id: self.lower_node_id(node_id),
840 pure_wrt_drop: false,
841 kind: hir::GenericParamKind::Lifetime { kind }
845 /// When there is a reference to some lifetime `'a`, and in-band
846 /// lifetimes are enabled, then we want to push that lifetime into
847 /// the vector of names to define later. In that case, it will get
848 /// added to the appropriate generics.
849 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
850 if !self.is_collecting_in_band_lifetimes {
854 if !self.sess.features_untracked().in_band_lifetimes {
858 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.modern())) {
862 let hir_name = ParamName::Plain(ident);
864 if self.lifetimes_to_define.iter()
865 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
869 self.lifetimes_to_define.push((ident.span, hir_name));
872 /// When we have either an elided or `'_` lifetime in an impl
873 /// header, we convert it to an in-band lifetime.
874 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
875 assert!(self.is_collecting_in_band_lifetimes);
876 let index = self.lifetimes_to_define.len();
877 let hir_name = ParamName::Fresh(index);
878 self.lifetimes_to_define.push((span, hir_name));
882 // Evaluates `f` with the lifetimes in `params` in-scope.
883 // This is used to track which lifetimes have already been defined, and
884 // which are new in-band lifetimes that need to have a definition created
886 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
888 F: FnOnce(&mut LoweringContext<'_>) -> T,
890 let old_len = self.in_scope_lifetimes.len();
891 let lt_def_names = params.iter().filter_map(|param| match param.kind {
892 GenericParamKind::Lifetime { .. } => Some(ParamName::Plain(param.ident.modern())),
895 self.in_scope_lifetimes.extend(lt_def_names);
899 self.in_scope_lifetimes.truncate(old_len);
903 /// Appends in-band lifetime defs and argument-position `impl
904 /// Trait` defs to the existing set of generics.
906 /// Presuming that in-band lifetimes are enabled, then
907 /// `self.anonymous_lifetime_mode` will be updated to match the
908 /// parameter while `f` is running (and restored afterwards).
909 fn add_in_band_defs<F, T>(
913 anonymous_lifetime_mode: AnonymousLifetimeMode,
915 ) -> (hir::Generics, T)
917 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
919 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
922 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
923 let mut params = Vec::new();
924 // Note: it is necessary to lower generics *before* calling `f`.
925 // When lowering `async fn`, there's a final step when lowering
926 // the return type that assumes that all in-scope lifetimes have
927 // already been added to either `in_scope_lifetimes` or
928 // `lifetimes_to_define`. If we swapped the order of these two,
929 // in-band-lifetimes introduced by generics or where-clauses
930 // wouldn't have been added yet.
931 let generics = this.lower_generics(
933 ImplTraitContext::Universal(&mut params),
935 let res = f(this, &mut params);
936 (params, (generics, res))
941 let mut lowered_params: Vec<_> = lowered_generics
947 // FIXME(const_generics): the compiler doesn't always cope with
948 // unsorted generic parameters at the moment, so we make sure
949 // that they're ordered correctly here for now. (When we chain
950 // the `in_band_defs`, we might make the order unsorted.)
951 lowered_params.sort_by_key(|param| {
953 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
954 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
955 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
959 lowered_generics.params = lowered_params.into();
961 (lowered_generics, res)
964 fn with_dyn_type_scope<T, F>(&mut self, in_scope: bool, f: F) -> T
966 F: FnOnce(&mut LoweringContext<'_>) -> T,
968 let was_in_dyn_type = self.is_in_dyn_type;
969 self.is_in_dyn_type = in_scope;
971 let result = f(self);
973 self.is_in_dyn_type = was_in_dyn_type;
978 fn with_new_scopes<T, F>(&mut self, f: F) -> T
980 F: FnOnce(&mut LoweringContext<'_>) -> T,
982 let was_in_loop_condition = self.is_in_loop_condition;
983 self.is_in_loop_condition = false;
985 let catch_scopes = mem::take(&mut self.catch_scopes);
986 let loop_scopes = mem::take(&mut self.loop_scopes);
988 self.catch_scopes = catch_scopes;
989 self.loop_scopes = loop_scopes;
991 self.is_in_loop_condition = was_in_loop_condition;
996 fn def_key(&mut self, id: DefId) -> DefKey {
998 self.resolver.definitions().def_key(id.index)
1000 self.cstore.def_key(id)
1004 fn lower_attrs_extendable(&mut self, attrs: &[Attribute]) -> Vec<Attribute> {
1007 .map(|a| self.lower_attr(a))
1011 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1012 self.lower_attrs_extendable(attrs).into()
1015 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1016 // Note that we explicitly do not walk the path. Since we don't really
1017 // lower attributes (we use the AST version) there is nowhere to keep
1018 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1022 path: attr.path.clone(),
1023 tokens: self.lower_token_stream(attr.tokens.clone()),
1024 is_sugared_doc: attr.is_sugared_doc,
1029 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1032 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1036 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1038 TokenTree::Token(token) => self.lower_token(token),
1039 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1042 self.lower_token_stream(tts),
1047 fn lower_token(&mut self, token: Token) -> TokenStream {
1049 token::Interpolated(nt) => {
1050 let tts = nt.to_tokenstream(&self.sess.parse_sess, token.span);
1051 self.lower_token_stream(tts)
1053 _ => TokenTree::Token(token).into(),
1057 /// Given an associated type constraint like one of these:
1060 /// T: Iterator<Item: Debug>
1062 /// T: Iterator<Item = Debug>
1066 /// returns a `hir::TypeBinding` representing `Item`.
1067 fn lower_assoc_ty_constraint(
1069 constraint: &AssocTyConstraint,
1070 itctx: ImplTraitContext<'_>,
1071 ) -> hir::TypeBinding {
1072 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1074 let kind = match constraint.kind {
1075 AssocTyConstraintKind::Equality { ref ty } => hir::TypeBindingKind::Equality {
1076 ty: self.lower_ty(ty, itctx)
1078 AssocTyConstraintKind::Bound { ref bounds } => {
1079 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1080 let (desugar_to_impl_trait, itctx) = match itctx {
1081 // We are in the return position:
1083 // fn foo() -> impl Iterator<Item: Debug>
1087 // fn foo() -> impl Iterator<Item = impl Debug>
1088 ImplTraitContext::OpaqueTy(_) => (true, itctx),
1090 // We are in the argument position, but within a dyn type:
1092 // fn foo(x: dyn Iterator<Item: Debug>)
1096 // fn foo(x: dyn Iterator<Item = impl Debug>)
1097 ImplTraitContext::Universal(_) if self.is_in_dyn_type => (true, itctx),
1099 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1100 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1101 // "impl trait context" to permit `impl Debug` in this position (it desugars
1102 // then to an opaque type).
1104 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1105 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type =>
1106 (true, ImplTraitContext::OpaqueTy(None)),
1108 // We are in the parameter position, but not within a dyn type:
1110 // fn foo(x: impl Iterator<Item: Debug>)
1112 // so we leave it as is and this gets expanded in astconv to a bound like
1113 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1115 _ => (false, itctx),
1118 if desugar_to_impl_trait {
1119 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1120 // constructing the HIR for `impl bounds...` and then lowering that.
1122 let impl_trait_node_id = self.sess.next_node_id();
1123 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1124 self.resolver.definitions().create_def_with_parent(
1127 DefPathData::ImplTrait,
1132 self.with_dyn_type_scope(false, |this| {
1133 let ty = this.lower_ty(
1135 id: this.sess.next_node_id(),
1136 node: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1137 span: constraint.span,
1142 hir::TypeBindingKind::Equality {
1147 // Desugar `AssocTy: Bounds` into a type binding where the
1148 // later desugars into a trait predicate.
1149 let bounds = self.lower_param_bounds(bounds, itctx);
1151 hir::TypeBindingKind::Constraint {
1159 hir_id: self.lower_node_id(constraint.id),
1160 ident: constraint.ident,
1162 span: constraint.span,
1166 fn lower_generic_arg(&mut self,
1167 arg: &ast::GenericArg,
1168 itctx: ImplTraitContext<'_>)
1169 -> hir::GenericArg {
1171 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1172 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1173 ast::GenericArg::Const(ct) => {
1174 GenericArg::Const(ConstArg {
1175 value: self.lower_anon_const(&ct),
1176 span: ct.value.span,
1182 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1183 P(self.lower_ty_direct(t, itctx))
1189 qself: &Option<QSelf>,
1191 param_mode: ParamMode,
1192 itctx: ImplTraitContext<'_>
1194 let id = self.lower_node_id(t.id);
1195 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1196 let ty = self.ty_path(id, t.span, qpath);
1197 if let hir::TyKind::TraitObject(..) = ty.node {
1198 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1203 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1204 let kind = match t.node {
1205 TyKind::Infer => hir::TyKind::Infer,
1206 TyKind::Err => hir::TyKind::Err,
1207 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1208 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1209 TyKind::Rptr(ref region, ref mt) => {
1210 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1211 let lifetime = match *region {
1212 Some(ref lt) => self.lower_lifetime(lt),
1213 None => self.elided_ref_lifetime(span),
1215 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1217 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1220 this.with_anonymous_lifetime_mode(
1221 AnonymousLifetimeMode::PassThrough,
1223 hir::TyKind::BareFn(P(hir::BareFnTy {
1224 generic_params: this.lower_generic_params(
1226 &NodeMap::default(),
1227 ImplTraitContext::disallowed(),
1229 unsafety: this.lower_unsafety(f.unsafety),
1231 decl: this.lower_fn_decl(&f.decl, None, false, None),
1232 param_names: this.lower_fn_params_to_names(&f.decl),
1238 TyKind::Never => hir::TyKind::Never,
1239 TyKind::Tup(ref tys) => {
1240 hir::TyKind::Tup(tys.iter().map(|ty| {
1241 self.lower_ty_direct(ty, itctx.reborrow())
1244 TyKind::Paren(ref ty) => {
1245 return self.lower_ty_direct(ty, itctx);
1247 TyKind::Path(ref qself, ref path) => {
1248 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1250 TyKind::ImplicitSelf => {
1251 let res = self.expect_full_res(t.id);
1252 let res = self.lower_res(res);
1253 hir::TyKind::Path(hir::QPath::Resolved(
1257 segments: hir_vec![hir::PathSegment::from_ident(
1258 Ident::with_dummy_span(kw::SelfUpper)
1264 TyKind::Array(ref ty, ref length) => {
1265 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1267 TyKind::Typeof(ref expr) => {
1268 hir::TyKind::Typeof(self.lower_anon_const(expr))
1270 TyKind::TraitObject(ref bounds, kind) => {
1271 let mut lifetime_bound = None;
1272 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1275 .filter_map(|bound| match *bound {
1276 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1277 Some(this.lower_poly_trait_ref(ty, itctx.reborrow()))
1279 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1280 GenericBound::Outlives(ref lifetime) => {
1281 if lifetime_bound.is_none() {
1282 lifetime_bound = Some(this.lower_lifetime(lifetime));
1288 let lifetime_bound =
1289 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1290 (bounds, lifetime_bound)
1292 if kind != TraitObjectSyntax::Dyn {
1293 self.maybe_lint_bare_trait(t.span, t.id, false);
1295 hir::TyKind::TraitObject(bounds, lifetime_bound)
1297 TyKind::ImplTrait(def_node_id, ref bounds) => {
1300 ImplTraitContext::OpaqueTy(fn_def_id) => {
1301 self.lower_opaque_impl_trait(
1302 span, fn_def_id, def_node_id,
1303 |this| this.lower_param_bounds(bounds, itctx),
1306 ImplTraitContext::Universal(in_band_ty_params) => {
1307 // Add a definition for the in-band `Param`.
1308 let def_index = self
1311 .opt_def_index(def_node_id)
1314 let hir_bounds = self.lower_param_bounds(
1316 ImplTraitContext::Universal(in_band_ty_params),
1318 // Set the name to `impl Bound1 + Bound2`.
1319 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1320 in_band_ty_params.push(hir::GenericParam {
1321 hir_id: self.lower_node_id(def_node_id),
1322 name: ParamName::Plain(ident),
1323 pure_wrt_drop: false,
1327 kind: hir::GenericParamKind::Type {
1329 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1333 hir::TyKind::Path(hir::QPath::Resolved(
1337 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1338 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1342 ImplTraitContext::Disallowed(pos) => {
1343 let allowed_in = if self.sess.features_untracked()
1344 .impl_trait_in_bindings {
1345 "bindings or function and inherent method return types"
1347 "function and inherent method return types"
1349 let mut err = struct_span_err!(
1353 "`impl Trait` not allowed outside of {}",
1356 if pos == ImplTraitPosition::Binding &&
1357 nightly_options::is_nightly_build() {
1359 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1360 attributes to enable");
1367 TyKind::Mac(_) => bug!("`TyMac` should have been expanded by now"),
1368 TyKind::CVarArgs => {
1369 // Create the implicit lifetime of the "spoofed" `VaListImpl`.
1370 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1371 let lt = self.new_implicit_lifetime(span);
1372 hir::TyKind::CVarArgs(lt)
1379 hir_id: self.lower_node_id(t.id),
1383 fn lower_opaque_impl_trait(
1386 fn_def_id: Option<DefId>,
1387 opaque_ty_node_id: NodeId,
1388 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1391 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1397 // Make sure we know that some funky desugaring has been going on here.
1398 // This is a first: there is code in other places like for loop
1399 // desugaring that explicitly states that we don't want to track that.
1400 // Not tracking it makes lints in rustc and clippy very fragile, as
1401 // frequently opened issues show.
1402 let opaque_ty_span = self.mark_span_with_reason(
1403 DesugaringKind::OpaqueTy,
1408 let opaque_ty_def_index = self
1411 .opt_def_index(opaque_ty_node_id)
1414 self.allocate_hir_id_counter(opaque_ty_node_id);
1416 let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
1418 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1420 opaque_ty_def_index,
1425 "lower_opaque_impl_trait: lifetimes={:#?}", lifetimes,
1429 "lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs,
1432 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1433 let opaque_ty_item = hir::OpaqueTy {
1434 generics: hir::Generics {
1435 params: lifetime_defs,
1436 where_clause: hir::WhereClause {
1437 predicates: hir_vec![],
1443 impl_trait_fn: fn_def_id,
1444 origin: hir::OpaqueTyOrigin::FnReturn,
1447 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_index);
1448 let opaque_ty_id = lctx.generate_opaque_type(
1455 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1456 hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, lifetimes)
1460 /// Registers a new opaque type with the proper `NodeId`s and
1461 /// returns the lowered node-ID for the opaque type.
1462 fn generate_opaque_type(
1464 opaque_ty_node_id: NodeId,
1465 opaque_ty_item: hir::OpaqueTy,
1467 opaque_ty_span: Span,
1469 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1470 let opaque_ty_id = self.lower_node_id(opaque_ty_node_id);
1471 // Generate an `type Foo = impl Trait;` declaration.
1472 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1473 let opaque_ty_item = hir::Item {
1474 hir_id: opaque_ty_id,
1475 ident: Ident::invalid(),
1476 attrs: Default::default(),
1477 node: opaque_ty_item_kind,
1478 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1479 span: opaque_ty_span,
1482 // Insert the item into the global item list. This usually happens
1483 // automatically for all AST items. But this opaque type item
1484 // does not actually exist in the AST.
1485 self.insert_item(opaque_ty_item);
1489 fn lifetimes_from_impl_trait_bounds(
1491 opaque_ty_id: NodeId,
1492 parent_index: DefIndex,
1493 bounds: &hir::GenericBounds,
1494 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1496 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
1497 parent_index={:?}, \
1499 opaque_ty_id, parent_index, bounds,
1502 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1503 // appear in the bounds, excluding lifetimes that are created within the bounds.
1504 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1505 struct ImplTraitLifetimeCollector<'r, 'a> {
1506 context: &'r mut LoweringContext<'a>,
1508 opaque_ty_id: NodeId,
1509 collect_elided_lifetimes: bool,
1510 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1511 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1512 output_lifetimes: Vec<hir::GenericArg>,
1513 output_lifetime_params: Vec<hir::GenericParam>,
1516 impl<'r, 'a, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1517 fn nested_visit_map<'this>(
1519 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1520 hir::intravisit::NestedVisitorMap::None
1523 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1524 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1525 if parameters.parenthesized {
1526 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1527 self.collect_elided_lifetimes = false;
1528 hir::intravisit::walk_generic_args(self, span, parameters);
1529 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1531 hir::intravisit::walk_generic_args(self, span, parameters);
1535 fn visit_ty(&mut self, t: &'v hir::Ty) {
1536 // Don't collect elided lifetimes used inside of `fn()` syntax.
1537 if let hir::TyKind::BareFn(_) = t.node {
1538 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1539 self.collect_elided_lifetimes = false;
1541 // Record the "stack height" of `for<'a>` lifetime bindings
1542 // to be able to later fully undo their introduction.
1543 let old_len = self.currently_bound_lifetimes.len();
1544 hir::intravisit::walk_ty(self, t);
1545 self.currently_bound_lifetimes.truncate(old_len);
1547 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1549 hir::intravisit::walk_ty(self, t)
1553 fn visit_poly_trait_ref(
1555 trait_ref: &'v hir::PolyTraitRef,
1556 modifier: hir::TraitBoundModifier,
1558 // Record the "stack height" of `for<'a>` lifetime bindings
1559 // to be able to later fully undo their introduction.
1560 let old_len = self.currently_bound_lifetimes.len();
1561 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1562 self.currently_bound_lifetimes.truncate(old_len);
1565 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1566 // Record the introduction of 'a in `for<'a> ...`.
1567 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1568 // Introduce lifetimes one at a time so that we can handle
1569 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1570 let lt_name = hir::LifetimeName::Param(param.name);
1571 self.currently_bound_lifetimes.push(lt_name);
1574 hir::intravisit::walk_generic_param(self, param);
1577 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1578 let name = match lifetime.name {
1579 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1580 if self.collect_elided_lifetimes {
1581 // Use `'_` for both implicit and underscore lifetimes in
1582 // `type Foo<'_> = impl SomeTrait<'_>;`.
1583 hir::LifetimeName::Underscore
1588 hir::LifetimeName::Param(_) => lifetime.name,
1590 // Refers to some other lifetime that is "in
1591 // scope" within the type.
1592 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1594 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1597 if !self.currently_bound_lifetimes.contains(&name)
1598 && !self.already_defined_lifetimes.contains(&name) {
1599 self.already_defined_lifetimes.insert(name);
1601 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1602 hir_id: self.context.next_id(),
1603 span: lifetime.span,
1607 let def_node_id = self.context.sess.next_node_id();
1609 self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1610 self.context.resolver.definitions().create_def_with_parent(
1613 DefPathData::LifetimeNs(name.ident().as_interned_str()),
1617 let (name, kind) = match name {
1618 hir::LifetimeName::Underscore => (
1619 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1620 hir::LifetimeParamKind::Elided,
1622 hir::LifetimeName::Param(param_name) => (
1624 hir::LifetimeParamKind::Explicit,
1626 _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1629 self.output_lifetime_params.push(hir::GenericParam {
1632 span: lifetime.span,
1633 pure_wrt_drop: false,
1636 kind: hir::GenericParamKind::Lifetime { kind }
1642 let mut lifetime_collector = ImplTraitLifetimeCollector {
1644 parent: parent_index,
1646 collect_elided_lifetimes: true,
1647 currently_bound_lifetimes: Vec::new(),
1648 already_defined_lifetimes: FxHashSet::default(),
1649 output_lifetimes: Vec::new(),
1650 output_lifetime_params: Vec::new(),
1653 for bound in bounds {
1654 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1658 lifetime_collector.output_lifetimes.into(),
1659 lifetime_collector.output_lifetime_params.into(),
1666 qself: &Option<QSelf>,
1668 param_mode: ParamMode,
1669 mut itctx: ImplTraitContext<'_>,
1671 let qself_position = qself.as_ref().map(|q| q.position);
1672 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1674 let partial_res = self.resolver
1675 .get_partial_res(id)
1676 .unwrap_or_else(|| PartialRes::new(Res::Err));
1678 let proj_start = p.segments.len() - partial_res.unresolved_segments();
1679 let path = P(hir::Path {
1680 res: self.lower_res(partial_res.base_res()),
1681 segments: p.segments[..proj_start]
1684 .map(|(i, segment)| {
1685 let param_mode = match (qself_position, param_mode) {
1686 (Some(j), ParamMode::Optional) if i < j => {
1687 // This segment is part of the trait path in a
1688 // qualified path - one of `a`, `b` or `Trait`
1689 // in `<X as a::b::Trait>::T::U::method`.
1695 // Figure out if this is a type/trait segment,
1696 // which may need lifetime elision performed.
1697 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1698 krate: def_id.krate,
1699 index: this.def_key(def_id).parent.expect("missing parent"),
1701 let type_def_id = match partial_res.base_res() {
1702 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1703 Some(parent_def_id(self, def_id))
1705 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1706 Some(parent_def_id(self, def_id))
1708 Res::Def(DefKind::Struct, def_id)
1709 | Res::Def(DefKind::Union, def_id)
1710 | Res::Def(DefKind::Enum, def_id)
1711 | Res::Def(DefKind::TyAlias, def_id)
1712 | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
1718 let parenthesized_generic_args = match partial_res.base_res() {
1719 // `a::b::Trait(Args)`
1720 Res::Def(DefKind::Trait, _)
1721 if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1722 // `a::b::Trait(Args)::TraitItem`
1723 Res::Def(DefKind::Method, _)
1724 | Res::Def(DefKind::AssocConst, _)
1725 | Res::Def(DefKind::AssocTy, _)
1726 if i + 2 == proj_start =>
1728 ParenthesizedGenericArgs::Ok
1730 // Avoid duplicated errors.
1731 Res::Err => ParenthesizedGenericArgs::Ok,
1733 Res::Def(DefKind::Struct, _)
1734 | Res::Def(DefKind::Enum, _)
1735 | Res::Def(DefKind::Union, _)
1736 | Res::Def(DefKind::TyAlias, _)
1737 | Res::Def(DefKind::Variant, _) if i + 1 == proj_start =>
1739 ParenthesizedGenericArgs::Err
1741 // A warning for now, for compatibility reasons.
1742 _ => ParenthesizedGenericArgs::Warn,
1745 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1746 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1749 assert!(!def_id.is_local());
1751 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1752 let n = item_generics.own_counts().lifetimes;
1753 self.type_def_lifetime_params.insert(def_id, n);
1756 self.lower_path_segment(
1761 parenthesized_generic_args,
1770 // Simple case, either no projections, or only fully-qualified.
1771 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1772 if partial_res.unresolved_segments() == 0 {
1773 return hir::QPath::Resolved(qself, path);
1776 // Create the innermost type that we're projecting from.
1777 let mut ty = if path.segments.is_empty() {
1778 // If the base path is empty that means there exists a
1779 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1780 qself.expect("missing QSelf for <T>::...")
1782 // Otherwise, the base path is an implicit `Self` type path,
1783 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1784 // `<I as Iterator>::Item::default`.
1785 let new_id = self.next_id();
1786 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1789 // Anything after the base path are associated "extensions",
1790 // out of which all but the last one are associated types,
1791 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1792 // * base path is `std::vec::Vec<T>`
1793 // * "extensions" are `IntoIter`, `Item` and `clone`
1794 // * type nodes are:
1795 // 1. `std::vec::Vec<T>` (created above)
1796 // 2. `<std::vec::Vec<T>>::IntoIter`
1797 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1798 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1799 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1800 let segment = P(self.lower_path_segment(
1805 ParenthesizedGenericArgs::Warn,
1809 let qpath = hir::QPath::TypeRelative(ty, segment);
1811 // It's finished, return the extension of the right node type.
1812 if i == p.segments.len() - 1 {
1816 // Wrap the associated extension in another type node.
1817 let new_id = self.next_id();
1818 ty = P(self.ty_path(new_id, p.span, qpath));
1821 // We should've returned in the for loop above.
1824 "lower_qpath: no final extension segment in {}..{}",
1830 fn lower_path_extra(
1834 param_mode: ParamMode,
1835 explicit_owner: Option<NodeId>,
1839 segments: p.segments
1842 self.lower_path_segment(
1847 ParenthesizedGenericArgs::Err,
1848 ImplTraitContext::disallowed(),
1857 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1858 let res = self.expect_full_res(id);
1859 let res = self.lower_res(res);
1860 self.lower_path_extra(res, p, param_mode, None)
1863 fn lower_path_segment(
1866 segment: &PathSegment,
1867 param_mode: ParamMode,
1868 expected_lifetimes: usize,
1869 parenthesized_generic_args: ParenthesizedGenericArgs,
1870 itctx: ImplTraitContext<'_>,
1871 explicit_owner: Option<NodeId>,
1872 ) -> hir::PathSegment {
1873 let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
1874 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
1875 match **generic_args {
1876 GenericArgs::AngleBracketed(ref data) => {
1877 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1879 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1880 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1881 ParenthesizedGenericArgs::Warn => {
1882 self.sess.buffer_lint(
1883 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1888 (hir::GenericArgs::none(), true)
1890 ParenthesizedGenericArgs::Err => {
1891 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
1892 err.span_label(data.span, "only `Fn` traits may use parentheses");
1893 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
1894 // Do not suggest going from `Trait()` to `Trait<>`
1895 if data.inputs.len() > 0 {
1896 err.span_suggestion(
1898 "use angle brackets instead",
1899 format!("<{}>", &snippet[1..snippet.len() - 1]),
1900 Applicability::MaybeIncorrect,
1906 self.lower_angle_bracketed_parameter_data(
1907 &data.as_angle_bracketed_args(),
1917 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1920 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1921 GenericArg::Lifetime(_) => true,
1924 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1925 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1926 if !generic_args.parenthesized && !has_lifetimes {
1928 self.elided_path_lifetimes(path_span, expected_lifetimes)
1930 .map(|lt| GenericArg::Lifetime(lt))
1931 .chain(generic_args.args.into_iter())
1933 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1934 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1935 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
1936 let no_bindings = generic_args.bindings.is_empty();
1937 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
1938 // If there are no (non-implicit) generic args or associated type
1939 // bindings, our suggestion includes the angle brackets.
1940 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1942 // Otherwise (sorry, this is kind of gross) we need to infer the
1943 // place to splice in the `'_, ` from the generics that do exist.
1944 let first_generic_span = first_generic_span
1945 .expect("already checked that non-lifetime args or bindings exist");
1946 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1948 match self.anonymous_lifetime_mode {
1949 // In create-parameter mode we error here because we don't want to support
1950 // deprecated impl elision in new features like impl elision and `async fn`,
1951 // both of which work using the `CreateParameter` mode:
1953 // impl Foo for std::cell::Ref<u32> // note lack of '_
1954 // async fn foo(_: std::cell::Ref<u32>) { ... }
1955 AnonymousLifetimeMode::CreateParameter => {
1956 let mut err = struct_span_err!(
1960 "implicit elided lifetime not allowed here"
1962 crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
1973 AnonymousLifetimeMode::PassThrough |
1974 AnonymousLifetimeMode::ReportError => {
1975 self.sess.buffer_lint_with_diagnostic(
1976 ELIDED_LIFETIMES_IN_PATHS,
1979 "hidden lifetime parameters in types are deprecated",
1980 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1993 let res = self.expect_full_res(segment.id);
1994 let id = if let Some(owner) = explicit_owner {
1995 self.lower_node_id_with_owner(segment.id, owner)
1997 self.lower_node_id(segment.id)
2000 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2001 segment.ident, segment.id, id,
2004 hir::PathSegment::new(
2007 Some(self.lower_res(res)),
2013 fn lower_angle_bracketed_parameter_data(
2015 data: &AngleBracketedArgs,
2016 param_mode: ParamMode,
2017 mut itctx: ImplTraitContext<'_>,
2018 ) -> (hir::GenericArgs, bool) {
2019 let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
2020 let has_non_lt_args = args.iter().any(|arg| match arg {
2021 ast::GenericArg::Lifetime(_) => false,
2022 ast::GenericArg::Type(_) => true,
2023 ast::GenericArg::Const(_) => true,
2027 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2028 bindings: constraints.iter()
2029 .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow()))
2031 parenthesized: false,
2033 !has_non_lt_args && param_mode == ParamMode::Optional
2037 fn lower_parenthesized_parameter_data(
2039 data: &ParenthesizedArgs,
2040 ) -> (hir::GenericArgs, bool) {
2041 // Switch to `PassThrough` mode for anonymous lifetimes; this
2042 // means that we permit things like `&Ref<T>`, where `Ref` has
2043 // a hidden lifetime parameter. This is needed for backwards
2044 // compatibility, even in contexts like an impl header where
2045 // we generally don't permit such things (see #51008).
2046 self.with_anonymous_lifetime_mode(
2047 AnonymousLifetimeMode::PassThrough,
2049 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2052 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2054 let mk_tup = |this: &mut Self, tys, span| {
2055 hir::Ty { node: hir::TyKind::Tup(tys), hir_id: this.next_id(), span }
2059 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2062 hir_id: this.next_id(),
2063 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2064 kind: hir::TypeBindingKind::Equality {
2067 .map(|ty| this.lower_ty(
2069 ImplTraitContext::disallowed()
2072 P(mk_tup(this, hir::HirVec::new(), span))
2075 span: output.as_ref().map_or(span, |ty| ty.span),
2078 parenthesized: true,
2086 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2087 let mut ids = SmallVec::<[NodeId; 1]>::new();
2088 if self.sess.features_untracked().impl_trait_in_bindings {
2089 if let Some(ref ty) = l.ty {
2090 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2091 visitor.visit_ty(ty);
2094 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2096 hir_id: self.lower_node_id(l.id),
2099 .map(|t| self.lower_ty(t,
2100 if self.sess.features_untracked().impl_trait_in_bindings {
2101 ImplTraitContext::OpaqueTy(Some(parent_def_id))
2103 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2106 pat: self.lower_pat(&l.pat),
2107 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2109 attrs: l.attrs.clone(),
2110 source: hir::LocalSource::Normal,
2114 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2116 Mutability::Mutable => hir::MutMutable,
2117 Mutability::Immutable => hir::MutImmutable,
2121 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2124 .map(|param| match param.pat.node {
2125 PatKind::Ident(_, ident, _) => ident,
2126 _ => Ident::new(kw::Invalid, param.pat.span),
2131 // Lowers a function declaration.
2133 // `decl`: the unlowered (AST) function declaration.
2134 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2135 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2136 // `make_ret_async` is also `Some`.
2137 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2138 // This guards against trait declarations and implementations where `impl Trait` is
2140 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2141 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2142 // return type `impl Trait` item.
2146 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2147 impl_trait_return_allow: bool,
2148 make_ret_async: Option<NodeId>,
2149 ) -> P<hir::FnDecl> {
2150 let lt_mode = if make_ret_async.is_some() {
2151 // In `async fn`, argument-position elided lifetimes
2152 // must be transformed into fresh generic parameters so that
2153 // they can be applied to the opaque `impl Trait` return type.
2154 AnonymousLifetimeMode::CreateParameter
2156 self.anonymous_lifetime_mode
2159 // Remember how many lifetimes were already around so that we can
2160 // only look at the lifetime parameters introduced by the arguments.
2161 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2165 if let Some((_, ibty)) = &mut in_band_ty_params {
2166 this.lower_ty_direct(¶m.ty, ImplTraitContext::Universal(ibty))
2168 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
2171 .collect::<HirVec<_>>()
2174 let output = if let Some(ret_id) = make_ret_async {
2175 self.lower_async_fn_ret_ty(
2177 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2182 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2183 Some((def_id, _)) if impl_trait_return_allow => {
2184 hir::Return(self.lower_ty(ty,
2185 ImplTraitContext::OpaqueTy(Some(def_id))
2189 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2192 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2199 c_variadic: decl.c_variadic,
2200 implicit_self: decl.inputs.get(0).map_or(
2201 hir::ImplicitSelfKind::None,
2203 let is_mutable_pat = match arg.pat.node {
2204 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2205 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2206 mt == Mutability::Mutable,
2211 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2212 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2213 // Given we are only considering `ImplicitSelf` types, we needn't consider
2214 // the case where we have a mutable pattern to a reference as that would
2215 // no longer be an `ImplicitSelf`.
2216 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2217 mt.mutbl == ast::Mutability::Mutable =>
2218 hir::ImplicitSelfKind::MutRef,
2219 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2220 hir::ImplicitSelfKind::ImmRef,
2221 _ => hir::ImplicitSelfKind::None,
2228 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
2229 // combined with the following definition of `OpaqueTy`:
2231 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
2233 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
2234 // `output`: unlowered output type (`T` in `-> T`)
2235 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2236 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
2237 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2238 fn lower_async_fn_ret_ty(
2240 output: &FunctionRetTy,
2242 opaque_ty_node_id: NodeId,
2243 ) -> hir::FunctionRetTy {
2245 "lower_async_fn_ret_ty(\
2248 opaque_ty_node_id={:?})",
2249 output, fn_def_id, opaque_ty_node_id,
2252 let span = output.span();
2254 let opaque_ty_span = self.mark_span_with_reason(
2255 DesugaringKind::Async,
2260 let opaque_ty_def_index = self
2263 .opt_def_index(opaque_ty_node_id)
2266 self.allocate_hir_id_counter(opaque_ty_node_id);
2268 // When we create the opaque type for this async fn, it is going to have
2269 // to capture all the lifetimes involved in the signature (including in the
2270 // return type). This is done by introducing lifetime parameters for:
2272 // - all the explicitly declared lifetimes from the impl and function itself;
2273 // - all the elided lifetimes in the fn arguments;
2274 // - all the elided lifetimes in the return type.
2276 // So for example in this snippet:
2279 // impl<'a> Foo<'a> {
2280 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
2281 // // ^ '0 ^ '1 ^ '2
2282 // // elided lifetimes used below
2287 // we would create an opaque type like:
2290 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
2293 // and we would then desugar `bar` to the equivalent of:
2296 // impl<'a> Foo<'a> {
2297 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
2301 // Note that the final parameter to `Bar` is `'_`, not `'2` --
2302 // this is because the elided lifetimes from the return type
2303 // should be figured out using the ordinary elision rules, and
2304 // this desugaring achieves that.
2306 // The variable `input_lifetimes_count` tracks the number of
2307 // lifetime parameters to the opaque type *not counting* those
2308 // lifetimes elided in the return type. This includes those
2309 // that are explicitly declared (`in_scope_lifetimes`) and
2310 // those elided lifetimes we found in the arguments (current
2311 // content of `lifetimes_to_define`). Next, we will process
2312 // the return type, which will cause `lifetimes_to_define` to
2314 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
2316 let (opaque_ty_id, lifetime_params) = self.with_hir_id_owner(opaque_ty_node_id, |this| {
2317 // We have to be careful to get elision right here. The
2318 // idea is that we create a lifetime parameter for each
2319 // lifetime in the return type. So, given a return type
2320 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
2321 // Future<Output = &'1 [ &'2 u32 ]>`.
2323 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
2324 // hence the elision takes place at the fn site.
2325 let future_bound = this.with_anonymous_lifetime_mode(
2326 AnonymousLifetimeMode::CreateParameter,
2327 |this| this.lower_async_fn_output_type_to_future_bound(
2334 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
2336 // Calculate all the lifetimes that should be captured
2337 // by the opaque type. This should include all in-scope
2338 // lifetime parameters, including those defined in-band.
2340 // Note: this must be done after lowering the output type,
2341 // as the output type may introduce new in-band lifetimes.
2342 let lifetime_params: Vec<(Span, ParamName)> =
2343 this.in_scope_lifetimes
2345 .map(|name| (name.ident().span, name))
2346 .chain(this.lifetimes_to_define.iter().cloned())
2349 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
2350 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
2351 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
2353 let generic_params =
2356 .map(|(span, hir_name)| {
2357 this.lifetime_to_generic_param(span, hir_name, opaque_ty_def_index)
2361 let opaque_ty_item = hir::OpaqueTy {
2362 generics: hir::Generics {
2363 params: generic_params,
2364 where_clause: hir::WhereClause {
2365 predicates: hir_vec![],
2370 bounds: hir_vec![future_bound],
2371 impl_trait_fn: Some(fn_def_id),
2372 origin: hir::OpaqueTyOrigin::AsyncFn,
2375 trace!("exist ty from async fn def index: {:#?}", opaque_ty_def_index);
2376 let opaque_ty_id = this.generate_opaque_type(
2383 (opaque_ty_id, lifetime_params)
2386 // As documented above on the variable
2387 // `input_lifetimes_count`, we need to create the lifetime
2388 // arguments to our opaque type. Continuing with our example,
2389 // we're creating the type arguments for the return type:
2392 // Bar<'a, 'b, '0, '1, '_>
2395 // For the "input" lifetime parameters, we wish to create
2396 // references to the parameters themselves, including the
2397 // "implicit" ones created from parameter types (`'a`, `'b`,
2400 // For the "output" lifetime parameters, we just want to
2402 let mut generic_args: Vec<_> =
2403 lifetime_params[..input_lifetimes_count]
2405 .map(|&(span, hir_name)| {
2406 // Input lifetime like `'a` or `'1`:
2407 GenericArg::Lifetime(hir::Lifetime {
2408 hir_id: self.next_id(),
2410 name: hir::LifetimeName::Param(hir_name),
2414 generic_args.extend(
2415 lifetime_params[input_lifetimes_count..]
2418 // Output lifetime like `'_`.
2419 GenericArg::Lifetime(hir::Lifetime {
2420 hir_id: self.next_id(),
2422 name: hir::LifetimeName::Implicit,
2427 // Create the `Foo<...>` refernece itself. Note that the `type
2428 // Foo = impl Trait` is, internally, created as a child of the
2429 // async fn, so the *type parameters* are inherited. It's
2430 // only the lifetime parameters that we must supply.
2431 let opaque_ty_ref = hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, generic_args.into());
2433 hir::FunctionRetTy::Return(P(hir::Ty {
2434 node: opaque_ty_ref,
2436 hir_id: self.next_id(),
2440 /// Transforms `-> T` into `Future<Output = T>`
2441 fn lower_async_fn_output_type_to_future_bound(
2443 output: &FunctionRetTy,
2446 ) -> hir::GenericBound {
2447 // Compute the `T` in `Future<Output = T>` from the return type.
2448 let output_ty = match output {
2449 FunctionRetTy::Ty(ty) => {
2450 self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(fn_def_id)))
2452 FunctionRetTy::Default(ret_ty_span) => {
2454 hir_id: self.next_id(),
2455 node: hir::TyKind::Tup(hir_vec![]),
2462 let future_params = P(hir::GenericArgs {
2464 bindings: hir_vec![hir::TypeBinding {
2465 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2466 kind: hir::TypeBindingKind::Equality {
2469 hir_id: self.next_id(),
2472 parenthesized: false,
2475 // ::std::future::Future<future_params>
2477 P(self.std_path(span, &[sym::future, sym::Future], Some(future_params), false));
2479 hir::GenericBound::Trait(
2481 trait_ref: hir::TraitRef {
2483 hir_ref_id: self.next_id(),
2485 bound_generic_params: hir_vec![],
2488 hir::TraitBoundModifier::None,
2492 fn lower_param_bound(
2495 itctx: ImplTraitContext<'_>,
2496 ) -> hir::GenericBound {
2498 GenericBound::Trait(ref ty, modifier) => {
2499 hir::GenericBound::Trait(
2500 self.lower_poly_trait_ref(ty, itctx),
2501 self.lower_trait_bound_modifier(modifier),
2504 GenericBound::Outlives(ref lifetime) => {
2505 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2510 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2511 let span = l.ident.span;
2513 ident if ident.name == kw::StaticLifetime =>
2514 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2515 ident if ident.name == kw::UnderscoreLifetime =>
2516 match self.anonymous_lifetime_mode {
2517 AnonymousLifetimeMode::CreateParameter => {
2518 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2519 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2522 AnonymousLifetimeMode::PassThrough => {
2523 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2526 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2529 self.maybe_collect_in_band_lifetime(ident);
2530 let param_name = ParamName::Plain(ident);
2531 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2536 fn new_named_lifetime(
2540 name: hir::LifetimeName,
2541 ) -> hir::Lifetime {
2543 hir_id: self.lower_node_id(id),
2549 fn lower_generic_params(
2551 params: &[GenericParam],
2552 add_bounds: &NodeMap<Vec<GenericBound>>,
2553 mut itctx: ImplTraitContext<'_>,
2554 ) -> hir::HirVec<hir::GenericParam> {
2555 params.iter().map(|param| {
2556 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2560 fn lower_generic_param(&mut self,
2561 param: &GenericParam,
2562 add_bounds: &NodeMap<Vec<GenericBound>>,
2563 mut itctx: ImplTraitContext<'_>)
2564 -> hir::GenericParam {
2565 let mut bounds = self.with_anonymous_lifetime_mode(
2566 AnonymousLifetimeMode::ReportError,
2567 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2570 let (name, kind) = match param.kind {
2571 GenericParamKind::Lifetime => {
2572 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2573 self.is_collecting_in_band_lifetimes = false;
2575 let lt = self.with_anonymous_lifetime_mode(
2576 AnonymousLifetimeMode::ReportError,
2577 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2579 let param_name = match lt.name {
2580 hir::LifetimeName::Param(param_name) => param_name,
2581 hir::LifetimeName::Implicit
2582 | hir::LifetimeName::Underscore
2583 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2584 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2587 "object-lifetime-default should not occur here",
2590 hir::LifetimeName::Error => ParamName::Error,
2593 let kind = hir::GenericParamKind::Lifetime {
2594 kind: hir::LifetimeParamKind::Explicit
2597 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2601 GenericParamKind::Type { ref default, .. } => {
2602 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2603 if !add_bounds.is_empty() {
2604 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2605 bounds = bounds.into_iter()
2610 let kind = hir::GenericParamKind::Type {
2611 default: default.as_ref().map(|x| {
2612 self.lower_ty(x, ImplTraitContext::OpaqueTy(None))
2614 synthetic: param.attrs.iter()
2615 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2616 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2620 (hir::ParamName::Plain(param.ident), kind)
2622 GenericParamKind::Const { ref ty } => {
2623 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2624 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2630 hir_id: self.lower_node_id(param.id),
2632 span: param.ident.span,
2633 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2634 attrs: self.lower_attrs(¶m.attrs),
2640 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2641 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2642 hir::QPath::Resolved(None, path) => path,
2643 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2647 hir_ref_id: self.lower_node_id(p.ref_id),
2651 fn lower_poly_trait_ref(
2654 mut itctx: ImplTraitContext<'_>,
2655 ) -> hir::PolyTraitRef {
2656 let bound_generic_params = self.lower_generic_params(
2657 &p.bound_generic_params,
2658 &NodeMap::default(),
2661 let trait_ref = self.with_in_scope_lifetime_defs(
2662 &p.bound_generic_params,
2663 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2667 bound_generic_params,
2673 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2675 ty: self.lower_ty(&mt.ty, itctx),
2676 mutbl: self.lower_mutability(mt.mutbl),
2680 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2681 -> hir::GenericBounds {
2682 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2685 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2686 let mut stmts = vec![];
2687 let mut expr = None;
2689 for (index, stmt) in b.stmts.iter().enumerate() {
2690 if index == b.stmts.len() - 1 {
2691 if let StmtKind::Expr(ref e) = stmt.node {
2692 expr = Some(P(self.lower_expr(e)));
2694 stmts.extend(self.lower_stmt(stmt));
2697 stmts.extend(self.lower_stmt(stmt));
2702 hir_id: self.lower_node_id(b.id),
2703 stmts: stmts.into(),
2705 rules: self.lower_block_check_mode(&b.rules),
2711 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2712 let node = match p.node {
2713 PatKind::Wild => hir::PatKind::Wild,
2714 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2715 let lower_sub = |this: &mut Self| sub.as_ref().map(|x| this.lower_pat(x));
2716 self.lower_pat_ident(p, binding_mode, ident, lower_sub)
2718 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
2719 PatKind::TupleStruct(ref path, ref pats) => {
2720 let qpath = self.lower_qpath(
2724 ParamMode::Optional,
2725 ImplTraitContext::disallowed(),
2727 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple struct");
2728 hir::PatKind::TupleStruct(qpath, pats, ddpos)
2730 PatKind::Or(ref pats) => {
2731 hir::PatKind::Or(pats.iter().map(|x| self.lower_pat(x)).collect())
2733 PatKind::Path(ref qself, ref path) => {
2734 let qpath = self.lower_qpath(
2738 ParamMode::Optional,
2739 ImplTraitContext::disallowed(),
2741 hir::PatKind::Path(qpath)
2743 PatKind::Struct(ref path, ref fields, etc) => {
2744 let qpath = self.lower_qpath(
2748 ParamMode::Optional,
2749 ImplTraitContext::disallowed(),
2754 .map(|f| hir::FieldPat {
2755 hir_id: self.next_id(),
2757 pat: self.lower_pat(&f.pat),
2758 is_shorthand: f.is_shorthand,
2762 hir::PatKind::Struct(qpath, fs, etc)
2764 PatKind::Tuple(ref pats) => {
2765 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple");
2766 hir::PatKind::Tuple(pats, ddpos)
2768 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
2769 PatKind::Ref(ref inner, mutbl) => {
2770 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
2772 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
2773 P(self.lower_expr(e1)),
2774 P(self.lower_expr(e2)),
2775 self.lower_range_end(end),
2777 PatKind::Slice(ref pats) => self.lower_pat_slice(pats),
2779 // If we reach here the `..` pattern is not semantically allowed.
2780 self.ban_illegal_rest_pat(p.span)
2782 PatKind::Paren(ref inner) => return self.lower_pat(inner),
2783 PatKind::Mac(_) => panic!("Shouldn't exist here"),
2786 self.pat_with_node_id_of(p, node)
2793 ) -> (HirVec<P<hir::Pat>>, Option<usize>) {
2794 let mut elems = Vec::with_capacity(pats.len());
2795 let mut rest = None;
2797 let mut iter = pats.iter().enumerate();
2798 while let Some((idx, pat)) = iter.next() {
2799 // Interpret the first `..` pattern as a subtuple pattern.
2801 rest = Some((idx, pat.span));
2804 // It was not a subslice pattern so lower it normally.
2805 elems.push(self.lower_pat(pat));
2808 while let Some((_, pat)) = iter.next() {
2809 // There was a previous subtuple pattern; make sure we don't allow more.
2811 self.ban_extra_rest_pat(pat.span, rest.unwrap().1, ctx);
2813 elems.push(self.lower_pat(pat));
2817 (elems.into(), rest.map(|(ddpos, _)| ddpos))
2820 fn lower_pat_slice(&mut self, pats: &[AstP<Pat>]) -> hir::PatKind {
2821 let mut before = Vec::new();
2822 let mut after = Vec::new();
2823 let mut slice = None;
2824 let mut prev_rest_span = None;
2826 let mut iter = pats.iter();
2827 while let Some(pat) = iter.next() {
2828 // Interpret the first `((ref mut?)? x @)? ..` pattern as a subslice pattern.
2831 prev_rest_span = Some(pat.span);
2832 slice = Some(self.pat_wild_with_node_id_of(pat));
2835 PatKind::Ident(ref bm, ident, Some(ref sub)) if sub.is_rest() => {
2836 prev_rest_span = Some(sub.span);
2837 let lower_sub = |this: &mut Self| Some(this.pat_wild_with_node_id_of(sub));
2838 let node = self.lower_pat_ident(pat, bm, ident, lower_sub);
2839 slice = Some(self.pat_with_node_id_of(pat, node));
2845 // It was not a subslice pattern so lower it normally.
2846 before.push(self.lower_pat(pat));
2849 while let Some(pat) = iter.next() {
2850 // There was a previous subslice pattern; make sure we don't allow more.
2851 let rest_span = match pat.node {
2852 PatKind::Rest => Some(pat.span),
2853 PatKind::Ident(.., Some(ref sub)) if sub.is_rest() => {
2854 // The `HirValidator` is merciless; add a `_` pattern to avoid ICEs.
2855 after.push(self.pat_wild_with_node_id_of(pat));
2860 if let Some(rest_span) = rest_span {
2861 self.ban_extra_rest_pat(rest_span, prev_rest_span.unwrap(), "slice");
2863 after.push(self.lower_pat(pat));
2867 hir::PatKind::Slice(before.into(), slice, after.into())
2873 binding_mode: &BindingMode,
2875 lower_sub: impl FnOnce(&mut Self) -> Option<P<hir::Pat>>,
2877 match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
2878 // `None` can occur in body-less function signatures
2879 res @ None | res @ Some(Res::Local(_)) => {
2880 let canonical_id = match res {
2881 Some(Res::Local(id)) => id,
2885 hir::PatKind::Binding(
2886 self.lower_binding_mode(binding_mode),
2887 self.lower_node_id(canonical_id),
2892 Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
2896 res: self.lower_res(res),
2897 segments: hir_vec![hir::PathSegment::from_ident(ident)],
2903 fn pat_wild_with_node_id_of(&mut self, p: &Pat) -> P<hir::Pat> {
2904 self.pat_with_node_id_of(p, hir::PatKind::Wild)
2907 /// Construct a `Pat` with the `HirId` of `p.id` lowered.
2908 fn pat_with_node_id_of(&mut self, p: &Pat, node: hir::PatKind) -> P<hir::Pat> {
2910 hir_id: self.lower_node_id(p.id),
2916 /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern.
2917 fn ban_extra_rest_pat(&self, sp: Span, prev_sp: Span, ctx: &str) {
2919 .struct_span_err(sp, &format!("`..` can only be used once per {} pattern", ctx))
2920 .span_label(sp, &format!("can only be used once per {} pattern", ctx))
2921 .span_label(prev_sp, "previously used here")
2925 /// Used to ban the `..` pattern in places it shouldn't be semantically.
2926 fn ban_illegal_rest_pat(&self, sp: Span) -> hir::PatKind {
2928 .struct_span_err(sp, "`..` patterns are not allowed here")
2929 .note("only allowed in tuple, tuple struct, and slice patterns")
2932 // We're not in a list context so `..` can be reasonably treated
2933 // as `_` because it should always be valid and roughly matches the
2934 // intent of `..` (notice that the rest of a single slot is that slot).
2938 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
2940 RangeEnd::Included(_) => hir::RangeEnd::Included,
2941 RangeEnd::Excluded => hir::RangeEnd::Excluded,
2945 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2946 self.with_new_scopes(|this| {
2948 hir_id: this.lower_node_id(c.id),
2949 body: this.lower_const_body(&c.value),
2954 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
2955 let node = match s.node {
2956 StmtKind::Local(ref l) => {
2957 let (l, item_ids) = self.lower_local(l);
2958 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
2961 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
2962 self.stmt(s.span, hir::StmtKind::Item(item_id))
2967 hir_id: self.lower_node_id(s.id),
2968 node: hir::StmtKind::Local(P(l)),
2974 StmtKind::Item(ref it) => {
2975 // Can only use the ID once.
2976 let mut id = Some(s.id);
2977 return self.lower_item_id(it)
2980 let hir_id = id.take()
2981 .map(|id| self.lower_node_id(id))
2982 .unwrap_or_else(|| self.next_id());
2986 node: hir::StmtKind::Item(item_id),
2992 StmtKind::Expr(ref e) => hir::StmtKind::Expr(P(self.lower_expr(e))),
2993 StmtKind::Semi(ref e) => hir::StmtKind::Semi(P(self.lower_expr(e))),
2994 StmtKind::Mac(..) => panic!("shouldn't exist here"),
2996 smallvec![hir::Stmt {
2997 hir_id: self.lower_node_id(s.id),
3003 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3005 BlockCheckMode::Default => hir::DefaultBlock,
3006 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3010 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3012 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3013 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3014 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3015 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3019 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3021 CompilerGenerated => hir::CompilerGenerated,
3022 UserProvided => hir::UserProvided,
3026 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3028 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3029 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3033 // Helper methods for building HIR.
3035 fn stmt(&mut self, span: Span, node: hir::StmtKind) -> hir::Stmt {
3036 hir::Stmt { span, node, hir_id: self.next_id() }
3039 fn stmt_expr(&mut self, span: Span, expr: hir::Expr) -> hir::Stmt {
3040 self.stmt(span, hir::StmtKind::Expr(P(expr)))
3045 attrs: ThinVec<Attribute>,
3047 init: Option<P<hir::Expr>>,
3049 source: hir::LocalSource,
3051 let local = hir::Local {
3053 hir_id: self.next_id(),
3060 self.stmt(span, hir::StmtKind::Local(P(local)))
3063 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
3064 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
3070 stmts: hir::HirVec<hir::Stmt>,
3071 expr: Option<P<hir::Expr>>,
3076 hir_id: self.next_id(),
3077 rules: hir::DefaultBlock,
3079 targeted_by_break: false,
3083 /// Constructs a `true` or `false` literal pattern.
3084 fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
3085 let expr = self.expr_bool(span, val);
3086 self.pat(span, hir::PatKind::Lit(P(expr)))
3089 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3090 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
3093 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3094 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
3097 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3098 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
3101 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
3102 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
3108 components: &[Symbol],
3109 subpats: hir::HirVec<P<hir::Pat>>,
3111 let path = self.std_path(span, components, None, true);
3112 let qpath = hir::QPath::Resolved(None, P(path));
3113 let pt = if subpats.is_empty() {
3114 hir::PatKind::Path(qpath)
3116 hir::PatKind::TupleStruct(qpath, subpats, None)
3121 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
3122 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
3125 fn pat_ident_binding_mode(
3129 bm: hir::BindingAnnotation,
3130 ) -> (P<hir::Pat>, hir::HirId) {
3131 let hir_id = self.next_id();
3136 node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
3143 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
3144 self.pat(span, hir::PatKind::Wild)
3147 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
3149 hir_id: self.next_id(),
3155 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
3156 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
3157 /// The path is also resolved according to `is_value`.
3161 components: &[Symbol],
3162 params: Option<P<hir::GenericArgs>>,
3165 let ns = if is_value { Namespace::ValueNS } else { Namespace::TypeNS };
3166 let (path, res) = self.resolver.resolve_str_path(span, self.crate_root, components, ns);
3168 let mut segments: Vec<_> = path.segments.iter().map(|segment| {
3169 let res = self.expect_full_res(segment.id);
3171 ident: segment.ident,
3172 hir_id: Some(self.lower_node_id(segment.id)),
3173 res: Some(self.lower_res(res)),
3178 segments.last_mut().unwrap().args = params;
3182 res: res.map_id(|_| panic!("unexpected `NodeId`")),
3183 segments: segments.into(),
3187 fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
3188 let node = match qpath {
3189 hir::QPath::Resolved(None, path) => {
3190 // Turn trait object paths into `TyKind::TraitObject` instead.
3192 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
3193 let principal = hir::PolyTraitRef {
3194 bound_generic_params: hir::HirVec::new(),
3195 trait_ref: hir::TraitRef {
3202 // The original ID is taken by the `PolyTraitRef`,
3203 // so the `Ty` itself needs a different one.
3204 hir_id = self.next_id();
3205 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
3207 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
3210 _ => hir::TyKind::Path(qpath),
3219 /// Invoked to create the lifetime argument for a type `&T`
3220 /// with no explicit lifetime.
3221 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
3222 match self.anonymous_lifetime_mode {
3223 // Intercept when we are in an impl header or async fn and introduce an in-band
3225 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
3227 AnonymousLifetimeMode::CreateParameter => {
3228 let fresh_name = self.collect_fresh_in_band_lifetime(span);
3230 hir_id: self.next_id(),
3232 name: hir::LifetimeName::Param(fresh_name),
3236 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
3238 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
3242 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
3243 /// return a "error lifetime".
3244 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
3245 let (id, msg, label) = match id {
3246 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
3249 self.sess.next_node_id(),
3250 "`&` without an explicit lifetime name cannot be used here",
3251 "explicit lifetime name needed here",
3255 let mut err = struct_span_err!(
3262 err.span_label(span, label);
3265 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3268 /// Invoked to create the lifetime argument(s) for a path like
3269 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
3270 /// sorts of cases are deprecated. This may therefore report a warning or an
3271 /// error, depending on the mode.
3272 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
3274 .map(|_| self.elided_path_lifetime(span))
3278 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
3279 match self.anonymous_lifetime_mode {
3280 AnonymousLifetimeMode::CreateParameter => {
3281 // We should have emitted E0726 when processing this path above
3282 self.sess.delay_span_bug(
3284 "expected 'implicit elided lifetime not allowed' error",
3286 let id = self.sess.next_node_id();
3287 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3289 // This is the normal case.
3290 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
3292 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
3296 /// Invoked to create the lifetime argument(s) for an elided trait object
3297 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
3298 /// when the bound is written, even if it is written with `'_` like in
3299 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
3300 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
3301 match self.anonymous_lifetime_mode {
3302 // NB. We intentionally ignore the create-parameter mode here.
3303 // and instead "pass through" to resolve-lifetimes, which will apply
3304 // the object-lifetime-defaulting rules. Elided object lifetime defaults
3305 // do not act like other elided lifetimes. In other words, given this:
3307 // impl Foo for Box<dyn Debug>
3309 // we do not introduce a fresh `'_` to serve as the bound, but instead
3310 // ultimately translate to the equivalent of:
3312 // impl Foo for Box<dyn Debug + 'static>
3314 // `resolve_lifetime` has the code to make that happen.
3315 AnonymousLifetimeMode::CreateParameter => {}
3317 AnonymousLifetimeMode::ReportError => {
3318 // ReportError applies to explicit use of `'_`.
3321 // This is the normal case.
3322 AnonymousLifetimeMode::PassThrough => {}
3325 let r = hir::Lifetime {
3326 hir_id: self.next_id(),
3328 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
3330 debug!("elided_dyn_bound: r={:?}", r);
3334 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
3336 hir_id: self.next_id(),
3338 name: hir::LifetimeName::Implicit,
3342 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
3343 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
3344 // call site which do not have a macro backtrace. See #61963.
3345 let is_macro_callsite = self.sess.source_map()
3346 .span_to_snippet(span)
3347 .map(|snippet| snippet.starts_with("#["))
3349 if !is_macro_callsite {
3350 self.sess.buffer_lint_with_diagnostic(
3351 builtin::BARE_TRAIT_OBJECTS,
3354 "trait objects without an explicit `dyn` are deprecated",
3355 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
3361 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
3362 // Sorting by span ensures that we get things in order within a
3363 // file, and also puts the files in a sensible order.
3364 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
3365 body_ids.sort_by_key(|b| bodies[b].value.span);
3369 /// Checks if the specified expression is a built-in range literal.
3370 /// (See: `LoweringContext::lower_expr()`).
3371 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
3372 use hir::{Path, QPath, ExprKind, TyKind};
3374 // Returns whether the given path represents a (desugared) range,
3375 // either in std or core, i.e. has either a `::std::ops::Range` or
3376 // `::core::ops::Range` prefix.
3377 fn is_range_path(path: &Path) -> bool {
3378 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.as_str().to_string()).collect();
3379 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
3381 // "{{root}}" is the equivalent of `::` prefix in `Path`.
3382 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
3383 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
3389 // Check whether a span corresponding to a range expression is a
3390 // range literal, rather than an explicit struct or `new()` call.
3391 fn is_lit(sess: &Session, span: &Span) -> bool {
3392 let source_map = sess.source_map();
3393 let end_point = source_map.end_point(*span);
3395 if let Ok(end_string) = source_map.span_to_snippet(end_point) {
3396 !(end_string.ends_with("}") || end_string.ends_with(")"))
3403 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
3404 ExprKind::Struct(ref qpath, _, _) => {
3405 if let QPath::Resolved(None, ref path) = **qpath {
3406 return is_range_path(&path) && is_lit(sess, &expr.span);
3410 // `..` desugars to its struct path.
3411 ExprKind::Path(QPath::Resolved(None, ref path)) => {
3412 return is_range_path(&path) && is_lit(sess, &expr.span);
3415 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
3416 ExprKind::Call(ref func, _) => {
3417 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
3418 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
3419 let new_call = segment.ident.as_str() == "new";
3420 return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;