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.
35 use crate::dep_graph::DepGraph;
36 use crate::hir::{self, ParamName};
37 use crate::hir::HirVec;
38 use crate::hir::map::{DefKey, DefPathData, Definitions};
39 use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
40 use crate::hir::def::{Res, DefKind, PartialRes, PerNS};
41 use crate::hir::{GenericArg, ConstArg};
42 use crate::hir::ptr::P;
43 use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
44 ELIDED_LIFETIMES_IN_PATHS};
45 use crate::middle::cstore::CrateStore;
46 use crate::session::Session;
47 use crate::session::config::nightly_options;
48 use crate::util::common::FN_OUTPUT_NAME;
49 use crate::util::nodemap::{DefIdMap, NodeMap};
50 use errors::Applicability;
51 use rustc_data_structures::fx::FxHashSet;
52 use rustc_data_structures::indexed_vec::IndexVec;
53 use rustc_data_structures::thin_vec::ThinVec;
54 use rustc_data_structures::sync::Lrc;
56 use std::collections::{BTreeSet, BTreeMap};
58 use smallvec::SmallVec;
63 use syntax::ext::hygiene::{Mark, SyntaxContext};
64 use syntax::print::pprust;
65 use syntax::source_map::{self, respan, ExpnInfo, CompilerDesugaringKind, Spanned};
66 use syntax::source_map::CompilerDesugaringKind::IfTemporary;
67 use syntax::std_inject;
68 use syntax::symbol::{kw, sym, Symbol};
69 use syntax::tokenstream::{TokenStream, TokenTree};
70 use syntax::parse::token::{self, Token};
71 use syntax::visit::{self, Visitor};
72 use syntax_pos::{DUMMY_SP, Span};
74 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
76 pub struct LoweringContext<'a> {
77 crate_root: Option<Symbol>,
79 /// Used to assign ids to HIR nodes that do not directly correspond to an AST node.
82 cstore: &'a dyn CrateStore,
84 resolver: &'a mut dyn Resolver,
86 /// The items being lowered are collected here.
87 items: BTreeMap<hir::HirId, hir::Item>,
89 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
90 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
91 bodies: BTreeMap<hir::BodyId, hir::Body>,
92 exported_macros: Vec<hir::MacroDef>,
94 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
96 modules: BTreeMap<NodeId, hir::ModuleItems>,
98 generator_kind: Option<hir::GeneratorKind>,
100 /// Used to get the current `fn`'s def span to point to when using `await`
101 /// outside of an `async fn`.
102 current_item: Option<Span>,
104 catch_scopes: Vec<NodeId>,
105 loop_scopes: Vec<NodeId>,
106 is_in_loop_condition: bool,
107 is_in_trait_impl: bool,
108 is_in_dyn_type: bool,
110 /// What to do when we encounter either an "anonymous lifetime
111 /// reference". The term "anonymous" is meant to encompass both
112 /// `'_` lifetimes as well as fully elided cases where nothing is
113 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
114 anonymous_lifetime_mode: AnonymousLifetimeMode,
116 /// Used to create lifetime definitions from in-band lifetime usages.
117 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
118 /// When a named lifetime is encountered in a function or impl header and
119 /// has not been defined
120 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
121 /// to this list. The results of this list are then added to the list of
122 /// lifetime definitions in the corresponding impl or function generics.
123 lifetimes_to_define: Vec<(Span, ParamName)>,
125 /// Whether or not in-band lifetimes are being collected. This is used to
126 /// indicate whether or not we're in a place where new lifetimes will result
127 /// in in-band lifetime definitions, such a function or an impl header,
128 /// including implicit lifetimes from `impl_header_lifetime_elision`.
129 is_collecting_in_band_lifetimes: bool,
131 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
132 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
133 /// against this list to see if it is already in-scope, or if a definition
134 /// needs to be created for it.
135 in_scope_lifetimes: Vec<Ident>,
137 current_module: NodeId,
139 type_def_lifetime_params: DefIdMap<usize>,
141 current_hir_id_owner: Vec<(DefIndex, u32)>,
142 item_local_id_counters: NodeMap<u32>,
143 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
145 allow_try_trait: Option<Lrc<[Symbol]>>,
146 allow_gen_future: Option<Lrc<[Symbol]>>,
150 /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
157 /// Obtain resolution for a `NodeId` with a single resolution.
158 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
160 /// Obtain per-namespace resolutions for `use` statement with the given `NoedId`.
161 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
163 /// Obtain 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>);
181 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
182 /// and if so, what meaning it has.
184 enum ImplTraitContext<'a> {
185 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
186 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
187 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
189 /// Newly generated parameters should be inserted into the given `Vec`.
190 Universal(&'a mut Vec<hir::GenericParam>),
192 /// Treat `impl Trait` as shorthand for a new existential parameter.
193 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
194 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
196 /// We optionally store a `DefId` for the parent item here so we can look up necessary
197 /// information later. It is `None` when no information about the context should be stored
198 /// (e.g., for consts and statics).
199 Existential(Option<DefId> /* fn def-ID */),
201 /// `impl Trait` is not accepted in this position.
202 Disallowed(ImplTraitPosition),
205 /// Position in which `impl Trait` is disallowed.
206 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
207 enum ImplTraitPosition {
208 /// Disallowed in `let` / `const` / `static` bindings.
211 /// All other posiitons.
215 impl<'a> ImplTraitContext<'a> {
217 fn disallowed() -> Self {
218 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
221 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
222 use self::ImplTraitContext::*;
224 Universal(params) => Universal(params),
225 Existential(fn_def_id) => Existential(*fn_def_id),
226 Disallowed(pos) => Disallowed(*pos),
233 cstore: &dyn CrateStore,
234 dep_graph: &DepGraph,
236 resolver: &mut dyn Resolver,
238 // We're constructing the HIR here; we don't care what we will
239 // read, since we haven't even constructed the *input* to
241 dep_graph.assert_ignored();
244 crate_root: std_inject::injected_crate_name().map(Symbol::intern),
248 items: BTreeMap::new(),
249 trait_items: BTreeMap::new(),
250 impl_items: BTreeMap::new(),
251 bodies: BTreeMap::new(),
252 trait_impls: BTreeMap::new(),
253 modules: BTreeMap::new(),
254 exported_macros: Vec::new(),
255 catch_scopes: Vec::new(),
256 loop_scopes: Vec::new(),
257 is_in_loop_condition: false,
258 is_in_trait_impl: false,
259 is_in_dyn_type: false,
260 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
261 type_def_lifetime_params: Default::default(),
262 current_module: CRATE_NODE_ID,
263 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
264 item_local_id_counters: Default::default(),
265 node_id_to_hir_id: IndexVec::new(),
266 generator_kind: None,
268 lifetimes_to_define: Vec::new(),
269 is_collecting_in_band_lifetimes: false,
270 in_scope_lifetimes: Vec::new(),
271 allow_try_trait: Some([sym::try_trait][..].into()),
272 allow_gen_future: Some([sym::gen_future][..].into()),
276 #[derive(Copy, Clone, PartialEq)]
278 /// Any path in a type context.
280 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
282 /// The `module::Type` in `module::Type::method` in an expression.
286 enum ParenthesizedGenericArgs {
292 /// What to do when we encounter an **anonymous** lifetime
293 /// reference. Anonymous lifetime references come in two flavors. You
294 /// have implicit, or fully elided, references to lifetimes, like the
295 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
296 /// or `Ref<'_, T>`. These often behave the same, but not always:
298 /// - certain usages of implicit references are deprecated, like
299 /// `Ref<T>`, and we sometimes just give hard errors in those cases
301 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
302 /// the same as `Box<dyn Foo + '_>`.
304 /// We describe the effects of the various modes in terms of three cases:
306 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
307 /// of a `&` (e.g., the missing lifetime in something like `&T`)
308 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
309 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
310 /// elided bounds follow special rules. Note that this only covers
311 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
312 /// '_>` is a case of "modern" elision.
313 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
314 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
315 /// non-deprecated equivalent.
317 /// Currently, the handling of lifetime elision is somewhat spread out
318 /// between HIR lowering and -- as described below -- the
319 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
320 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
321 /// everything into HIR lowering.
322 #[derive(Copy, Clone)]
323 enum AnonymousLifetimeMode {
324 /// For **Modern** cases, create a new anonymous region parameter
325 /// and reference that.
327 /// For **Dyn Bound** cases, pass responsibility to
328 /// `resolve_lifetime` code.
330 /// For **Deprecated** cases, report an error.
333 /// Give a hard error when either `&` or `'_` is written. Used to
334 /// rule out things like `where T: Foo<'_>`. Does not imply an
335 /// error on default object bounds (e.g., `Box<dyn Foo>`).
338 /// Pass responsibility to `resolve_lifetime` code for all cases.
341 /// Used in the return types of `async fn` where there exists
342 /// exactly one argument-position elided lifetime.
344 /// In `async fn`, we lower the arguments types using the `CreateParameter`
345 /// mode, meaning that non-`dyn` elided lifetimes are assigned a fresh name.
346 /// If any corresponding elided lifetimes appear in the output, we need to
347 /// replace them with references to the fresh name assigned to the corresponding
348 /// elided lifetime in the arguments.
350 /// For **Modern cases**, replace the anonymous parameter with a
351 /// reference to a specific freshly-named lifetime that was
352 /// introduced in argument
354 /// For **Dyn Bound** cases, pass responsibility to
355 /// `resole_lifetime` code.
356 Replace(LtReplacement),
359 /// The type of elided lifetime replacement to perform on `async fn` return types.
360 #[derive(Copy, Clone)]
362 /// Fresh name introduced by the single non-dyn elided lifetime
363 /// in the arguments of the async fn.
366 /// There is no single non-dyn elided lifetime because no lifetimes
367 /// appeared in the arguments.
370 /// There is no single non-dyn elided lifetime because multiple
371 /// lifetimes appeared in the arguments.
375 /// Calculates the `LtReplacement` to use for elided lifetimes in the return
376 /// type based on the fresh elided lifetimes introduced in argument position.
377 fn get_elided_lt_replacement(arg_position_lifetimes: &[(Span, ParamName)]) -> LtReplacement {
378 match arg_position_lifetimes {
379 [] => LtReplacement::NoLifetimes,
380 [(_span, param)] => LtReplacement::Some(*param),
381 _ => LtReplacement::MultipleLifetimes,
385 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
387 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
388 fn visit_ty(&mut self, ty: &'a Ty) {
394 TyKind::ImplTrait(id, _) => self.ids.push(id),
397 visit::walk_ty(self, ty);
400 fn visit_path_segment(
403 path_segment: &'v PathSegment,
405 if let Some(ref p) = path_segment.args {
406 if let GenericArgs::Parenthesized(_) = **p {
410 visit::walk_path_segment(self, path_span, path_segment)
414 impl<'a> LoweringContext<'a> {
415 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
416 /// Full-crate AST visitor that inserts into a fresh
417 /// `LoweringContext` any information that may be
418 /// needed from arbitrary locations in the crate,
419 /// e.g., the number of lifetime generic parameters
420 /// declared for every type and trait definition.
421 struct MiscCollector<'tcx, 'interner> {
422 lctx: &'tcx mut LoweringContext<'interner>,
423 hir_id_owner: Option<NodeId>,
426 impl MiscCollector<'_, '_> {
427 fn allocate_use_tree_hir_id_counters(
433 UseTreeKind::Simple(_, id1, id2) => {
434 for &id in &[id1, id2] {
435 self.lctx.resolver.definitions().create_def_with_parent(
442 self.lctx.allocate_hir_id_counter(id);
445 UseTreeKind::Glob => (),
446 UseTreeKind::Nested(ref trees) => {
447 for &(ref use_tree, id) in trees {
448 let hir_id = self.lctx.allocate_hir_id_counter(id);
449 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
455 fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
457 F: FnOnce(&mut Self) -> T,
459 let old = mem::replace(&mut self.hir_id_owner, owner);
461 self.hir_id_owner = old;
466 impl<'tcx, 'interner> Visitor<'tcx> for MiscCollector<'tcx, 'interner> {
467 fn visit_pat(&mut self, p: &'tcx Pat) {
469 // Doesn't generate a HIR node
470 PatKind::Paren(..) => {},
472 if let Some(owner) = self.hir_id_owner {
473 self.lctx.lower_node_id_with_owner(p.id, owner);
478 visit::walk_pat(self, p)
481 fn visit_item(&mut self, item: &'tcx Item) {
482 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
485 ItemKind::Struct(_, ref generics)
486 | ItemKind::Union(_, ref generics)
487 | ItemKind::Enum(_, ref generics)
488 | ItemKind::Ty(_, ref generics)
489 | ItemKind::Existential(_, ref generics)
490 | ItemKind::Trait(_, _, ref generics, ..) => {
491 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
495 .filter(|param| match param.kind {
496 ast::GenericParamKind::Lifetime { .. } => true,
500 self.lctx.type_def_lifetime_params.insert(def_id, count);
502 ItemKind::Use(ref use_tree) => {
503 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
508 self.with_hir_id_owner(Some(item.id), |this| {
509 visit::walk_item(this, item);
513 fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
514 self.lctx.allocate_hir_id_counter(item.id);
517 TraitItemKind::Method(_, None) => {
518 // Ignore patterns in trait methods without bodies
519 self.with_hir_id_owner(None, |this| {
520 visit::walk_trait_item(this, item)
523 _ => self.with_hir_id_owner(Some(item.id), |this| {
524 visit::walk_trait_item(this, item);
529 fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
530 self.lctx.allocate_hir_id_counter(item.id);
531 self.with_hir_id_owner(Some(item.id), |this| {
532 visit::walk_impl_item(this, item);
536 fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) {
537 // Ignore patterns in foreign items
538 self.with_hir_id_owner(None, |this| {
539 visit::walk_foreign_item(this, i)
543 fn visit_ty(&mut self, t: &'tcx Ty) {
545 // Mirrors the case in visit::walk_ty
546 TyKind::BareFn(ref f) => {
552 // Mirrors visit::walk_fn_decl
553 for argument in &f.decl.inputs {
554 // We don't lower the ids of argument patterns
555 self.with_hir_id_owner(None, |this| {
556 this.visit_pat(&argument.pat);
558 self.visit_ty(&argument.ty)
560 self.visit_fn_ret_ty(&f.decl.output)
562 _ => visit::walk_ty(self, t),
567 struct ItemLowerer<'tcx, 'interner> {
568 lctx: &'tcx mut LoweringContext<'interner>,
571 impl<'tcx, 'interner> ItemLowerer<'tcx, 'interner> {
572 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
574 F: FnOnce(&mut Self),
576 let old = self.lctx.is_in_trait_impl;
577 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
583 self.lctx.is_in_trait_impl = old;
587 impl<'tcx, 'interner> Visitor<'tcx> for ItemLowerer<'tcx, 'interner> {
588 fn visit_mod(&mut self, m: &'tcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
589 self.lctx.modules.insert(n, hir::ModuleItems {
590 items: BTreeSet::new(),
591 trait_items: BTreeSet::new(),
592 impl_items: BTreeSet::new(),
595 let old = self.lctx.current_module;
596 self.lctx.current_module = n;
597 visit::walk_mod(self, m);
598 self.lctx.current_module = old;
601 fn visit_item(&mut self, item: &'tcx Item) {
602 let mut item_hir_id = None;
603 self.lctx.with_hir_id_owner(item.id, |lctx| {
604 if let Some(hir_item) = lctx.lower_item(item) {
605 item_hir_id = Some(hir_item.hir_id);
606 lctx.insert_item(hir_item);
610 if let Some(hir_id) = item_hir_id {
611 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
612 let this = &mut ItemLowerer { lctx: this };
613 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
614 this.with_trait_impl_ref(opt_trait_ref, |this| {
615 visit::walk_item(this, item)
618 visit::walk_item(this, item);
624 fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
625 self.lctx.with_hir_id_owner(item.id, |lctx| {
626 let hir_item = lctx.lower_trait_item(item);
627 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
628 lctx.trait_items.insert(id, hir_item);
629 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
632 visit::walk_trait_item(self, item);
635 fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
636 self.lctx.with_hir_id_owner(item.id, |lctx| {
637 let hir_item = lctx.lower_impl_item(item);
638 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
639 lctx.impl_items.insert(id, hir_item);
640 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
642 visit::walk_impl_item(self, item);
646 self.lower_node_id(CRATE_NODE_ID);
647 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
649 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
650 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
652 let module = self.lower_mod(&c.module);
653 let attrs = self.lower_attrs(&c.attrs);
654 let body_ids = body_ids(&self.bodies);
658 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
664 exported_macros: hir::HirVec::from(self.exported_macros),
666 trait_items: self.trait_items,
667 impl_items: self.impl_items,
670 trait_impls: self.trait_impls,
671 modules: self.modules,
675 fn insert_item(&mut self, item: hir::Item) {
676 let id = item.hir_id;
677 // FIXME: Use `debug_asset-rt`.
678 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
679 self.items.insert(id, item);
680 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
683 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
684 // Set up the counter if needed.
685 self.item_local_id_counters.entry(owner).or_insert(0);
686 // Always allocate the first `HirId` for the owner itself.
687 let lowered = self.lower_node_id_with_owner(owner, owner);
688 debug_assert_eq!(lowered.local_id.as_u32(), 0);
692 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> hir::HirId
694 F: FnOnce(&mut Self) -> hir::HirId,
696 if ast_node_id == DUMMY_NODE_ID {
697 return hir::DUMMY_HIR_ID;
700 let min_size = ast_node_id.as_usize() + 1;
702 if min_size > self.node_id_to_hir_id.len() {
703 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
706 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
708 if existing_hir_id == hir::DUMMY_HIR_ID {
709 // Generate a new `HirId`.
710 let hir_id = alloc_hir_id(self);
711 self.node_id_to_hir_id[ast_node_id] = hir_id;
719 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
721 F: FnOnce(&mut Self) -> T,
723 let counter = self.item_local_id_counters
724 .insert(owner, HIR_ID_COUNTER_LOCKED)
725 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
726 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
727 self.current_hir_id_owner.push((def_index, counter));
729 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
731 debug_assert!(def_index == new_def_index);
732 debug_assert!(new_counter >= counter);
734 let prev = self.item_local_id_counters
735 .insert(owner, new_counter)
737 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
741 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
742 /// the `LoweringContext`'s `NodeId => HirId` map.
743 /// Take care not to call this method if the resulting `HirId` is then not
744 /// actually used in the HIR, as that would trigger an assertion in the
745 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
746 /// properly. Calling the method twice with the same `NodeId` is fine though.
747 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
748 self.lower_node_id_generic(ast_node_id, |this| {
749 let &mut (def_index, ref mut local_id_counter) =
750 this.current_hir_id_owner.last_mut().unwrap();
751 let local_id = *local_id_counter;
752 *local_id_counter += 1;
755 local_id: hir::ItemLocalId::from_u32(local_id),
760 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
761 self.lower_node_id_generic(ast_node_id, |this| {
762 let local_id_counter = this
763 .item_local_id_counters
765 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
766 let local_id = *local_id_counter;
768 // We want to be sure not to modify the counter in the map while it
769 // is also on the stack. Otherwise we'll get lost updates when writing
770 // back from the stack to the map.
771 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
773 *local_id_counter += 1;
777 .opt_def_index(owner)
778 .expect("you forgot to call `create_def_with_parent` or are lowering node-IDs \
779 that do not belong to the current owner");
783 local_id: hir::ItemLocalId::from_u32(local_id),
788 fn generator_movability_for_fn(
792 generator_kind: Option<hir::GeneratorKind>,
793 movability: Movability,
794 ) -> Option<hir::GeneratorMovability> {
795 match generator_kind {
796 Some(hir::GeneratorKind::Gen) => {
797 if !decl.inputs.is_empty() {
802 "generators cannot have explicit arguments"
804 self.sess.abort_if_errors();
806 Some(match movability {
807 Movability::Movable => hir::GeneratorMovability::Movable,
808 Movability::Static => hir::GeneratorMovability::Static,
811 Some(hir::GeneratorKind::Async) => {
812 bug!("non-`async` closure body turned `async` during lowering");
815 if movability == Movability::Static {
820 "closures cannot be static"
828 fn record_body(&mut self, arguments: HirVec<hir::Arg>, value: hir::Expr) -> hir::BodyId {
829 let body = hir::Body {
830 generator_kind: self.generator_kind,
835 self.bodies.insert(id, body);
839 fn next_id(&mut self) -> hir::HirId {
840 self.lower_node_id(self.sess.next_node_id())
843 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
845 self.lower_node_id_generic(id, |_| {
846 panic!("expected node_id to be lowered already for res {:#?}", res)
851 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
852 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
853 if pr.unresolved_segments() != 0 {
854 bug!("path not fully resolved: {:?}", pr);
860 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
861 self.resolver.get_import_res(id).present_items()
864 fn diagnostic(&self) -> &errors::Handler {
865 self.sess.diagnostic()
868 /// Reuses the span but adds information like the kind of the desugaring and features that are
869 /// allowed inside this span.
870 fn mark_span_with_reason(
872 reason: CompilerDesugaringKind,
874 allow_internal_unstable: Option<Lrc<[Symbol]>>,
876 let mark = Mark::fresh(Mark::root());
877 mark.set_expn_info(ExpnInfo {
878 def_site: Some(span),
879 allow_internal_unstable,
880 ..ExpnInfo::default(source_map::CompilerDesugaring(reason), span, self.sess.edition())
882 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
885 fn with_anonymous_lifetime_mode<R>(
887 anonymous_lifetime_mode: AnonymousLifetimeMode,
888 op: impl FnOnce(&mut Self) -> R,
890 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
891 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
892 let result = op(self);
893 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
897 /// Creates a new `hir::GenericParam` for every new lifetime and
898 /// type parameter encountered while evaluating `f`. Definitions
899 /// are created with the parent provided. If no `parent_id` is
900 /// provided, no definitions will be returned.
902 /// Presuming that in-band lifetimes are enabled, then
903 /// `self.anonymous_lifetime_mode` will be updated to match the
904 /// argument while `f` is running (and restored afterwards).
905 fn collect_in_band_defs<T, F>(
908 anonymous_lifetime_mode: AnonymousLifetimeMode,
910 ) -> (Vec<hir::GenericParam>, T)
912 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
914 assert!(!self.is_collecting_in_band_lifetimes);
915 assert!(self.lifetimes_to_define.is_empty());
916 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
918 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
919 self.is_collecting_in_band_lifetimes = true;
921 let (in_band_ty_params, res) = f(self);
923 self.is_collecting_in_band_lifetimes = false;
924 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
926 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
928 let params = lifetimes_to_define
930 .map(|(span, hir_name)| self.lifetime_to_generic_param(
931 span, hir_name, parent_id.index,
933 .chain(in_band_ty_params.into_iter())
939 /// Converts a lifetime into a new generic parameter.
940 fn lifetime_to_generic_param(
944 parent_index: DefIndex,
945 ) -> hir::GenericParam {
946 let node_id = self.sess.next_node_id();
948 // Get the name we'll use to make the def-path. Note
949 // that collisions are ok here and this shouldn't
950 // really show up for end-user.
951 let (str_name, kind) = match hir_name {
952 ParamName::Plain(ident) => (
953 ident.as_interned_str(),
954 hir::LifetimeParamKind::InBand,
956 ParamName::Fresh(_) => (
957 kw::UnderscoreLifetime.as_interned_str(),
958 hir::LifetimeParamKind::Elided,
960 ParamName::Error => (
961 kw::UnderscoreLifetime.as_interned_str(),
962 hir::LifetimeParamKind::Error,
966 // Add a definition for the in-band lifetime def.
967 self.resolver.definitions().create_def_with_parent(
970 DefPathData::LifetimeNs(str_name),
976 hir_id: self.lower_node_id(node_id),
981 pure_wrt_drop: false,
982 kind: hir::GenericParamKind::Lifetime { kind }
986 /// When there is a reference to some lifetime `'a`, and in-band
987 /// lifetimes are enabled, then we want to push that lifetime into
988 /// the vector of names to define later. In that case, it will get
989 /// added to the appropriate generics.
990 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
991 if !self.is_collecting_in_band_lifetimes {
995 if !self.sess.features_untracked().in_band_lifetimes {
999 if self.in_scope_lifetimes.contains(&ident.modern()) {
1003 let hir_name = ParamName::Plain(ident);
1005 if self.lifetimes_to_define.iter()
1006 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
1010 self.lifetimes_to_define.push((ident.span, hir_name));
1013 /// When we have either an elided or `'_` lifetime in an impl
1014 /// header, we convert it to an in-band lifetime.
1015 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
1016 assert!(self.is_collecting_in_band_lifetimes);
1017 let index = self.lifetimes_to_define.len();
1018 let hir_name = ParamName::Fresh(index);
1019 self.lifetimes_to_define.push((span, hir_name));
1023 // Evaluates `f` with the lifetimes in `params` in-scope.
1024 // This is used to track which lifetimes have already been defined, and
1025 // which are new in-band lifetimes that need to have a definition created
1027 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
1029 F: FnOnce(&mut LoweringContext<'_>) -> T,
1031 let old_len = self.in_scope_lifetimes.len();
1032 let lt_def_names = params.iter().filter_map(|param| match param.kind {
1033 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
1036 self.in_scope_lifetimes.extend(lt_def_names);
1040 self.in_scope_lifetimes.truncate(old_len);
1044 // Same as the method above, but accepts `hir::GenericParam`s
1045 // instead of `ast::GenericParam`s.
1046 // This should only be used with generics that have already had their
1047 // in-band lifetimes added. In practice, this means that this function is
1048 // only used when lowering a child item of a trait or impl.
1049 fn with_parent_item_lifetime_defs<T, F>(&mut self,
1050 parent_hir_id: hir::HirId,
1053 F: FnOnce(&mut LoweringContext<'_>) -> T,
1055 let old_len = self.in_scope_lifetimes.len();
1057 let parent_generics = match self.items.get(&parent_hir_id).unwrap().node {
1058 hir::ItemKind::Impl(_, _, _, ref generics, ..)
1059 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1060 &generics.params[..]
1064 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
1065 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
1068 self.in_scope_lifetimes.extend(lt_def_names);
1072 self.in_scope_lifetimes.truncate(old_len);
1076 /// Appends in-band lifetime defs and argument-position `impl
1077 /// Trait` defs to the existing set of generics.
1079 /// Presuming that in-band lifetimes are enabled, then
1080 /// `self.anonymous_lifetime_mode` will be updated to match the
1081 /// argument while `f` is running (and restored afterwards).
1082 fn add_in_band_defs<F, T>(
1084 generics: &Generics,
1086 anonymous_lifetime_mode: AnonymousLifetimeMode,
1088 ) -> (hir::Generics, T)
1090 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
1092 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
1095 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
1096 let mut params = Vec::new();
1097 // Note: it is necessary to lower generics *before* calling `f`.
1098 // When lowering `async fn`, there's a final step when lowering
1099 // the return type that assumes that all in-scope lifetimes have
1100 // already been added to either `in_scope_lifetimes` or
1101 // `lifetimes_to_define`. If we swapped the order of these two,
1102 // in-band-lifetimes introduced by generics or where-clauses
1103 // wouldn't have been added yet.
1104 let generics = this.lower_generics(
1106 ImplTraitContext::Universal(&mut params),
1108 let res = f(this, &mut params);
1109 (params, (generics, res))
1114 let mut lowered_params: Vec<_> = lowered_generics
1117 .chain(in_band_defs)
1120 // FIXME(const_generics): the compiler doesn't always cope with
1121 // unsorted generic parameters at the moment, so we make sure
1122 // that they're ordered correctly here for now. (When we chain
1123 // the `in_band_defs`, we might make the order unsorted.)
1124 lowered_params.sort_by_key(|param| {
1126 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
1127 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
1128 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
1132 lowered_generics.params = lowered_params.into();
1134 (lowered_generics, res)
1137 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
1139 F: FnOnce(&mut LoweringContext<'_>) -> T,
1141 let len = self.catch_scopes.len();
1142 self.catch_scopes.push(catch_id);
1144 let result = f(self);
1147 self.catch_scopes.len(),
1148 "catch scopes should be added and removed in stack order"
1151 self.catch_scopes.pop().unwrap();
1158 capture_clause: CaptureBy,
1159 closure_node_id: NodeId,
1160 ret_ty: Option<syntax::ptr::P<Ty>>,
1162 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1163 ) -> hir::ExprKind {
1164 let capture_clause = self.lower_capture_clause(capture_clause);
1165 let output = match ret_ty {
1166 Some(ty) => FunctionRetTy::Ty(ty),
1167 None => FunctionRetTy::Default(span),
1169 let ast_decl = FnDecl {
1174 let decl = self.lower_fn_decl(&ast_decl, None, /* impl trait allowed */ false, None);
1175 let body_id = self.lower_fn_body(&ast_decl, |this| {
1176 this.generator_kind = Some(hir::GeneratorKind::Async);
1179 let generator = hir::Expr {
1180 hir_id: self.lower_node_id(closure_node_id),
1181 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
1182 Some(hir::GeneratorMovability::Static)),
1184 attrs: ThinVec::new(),
1187 let unstable_span = self.mark_span_with_reason(
1188 CompilerDesugaringKind::Async,
1190 self.allow_gen_future.clone(),
1192 let gen_future = self.expr_std_path(
1193 unstable_span, &[sym::future, sym::from_generator], None, ThinVec::new());
1194 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
1199 f: impl FnOnce(&mut LoweringContext<'_>) -> (HirVec<hir::Arg>, hir::Expr),
1201 let prev_gen_kind = self.generator_kind.take();
1202 let (arguments, result) = f(self);
1203 let body_id = self.record_body(arguments, result);
1204 self.generator_kind = prev_gen_kind;
1211 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1213 self.lower_body(|this| (
1214 decl.inputs.iter().map(|x| this.lower_arg(x)).collect(),
1219 fn lower_const_body(&mut self, expr: &Expr) -> hir::BodyId {
1220 self.lower_body(|this| (hir_vec![], this.lower_expr(expr)))
1223 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
1225 F: FnOnce(&mut LoweringContext<'_>) -> T,
1227 // We're no longer in the base loop's condition; we're in another loop.
1228 let was_in_loop_condition = self.is_in_loop_condition;
1229 self.is_in_loop_condition = false;
1231 let len = self.loop_scopes.len();
1232 self.loop_scopes.push(loop_id);
1234 let result = f(self);
1237 self.loop_scopes.len(),
1238 "loop scopes should be added and removed in stack order"
1241 self.loop_scopes.pop().unwrap();
1243 self.is_in_loop_condition = was_in_loop_condition;
1248 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
1250 F: FnOnce(&mut LoweringContext<'_>) -> T,
1252 let was_in_loop_condition = self.is_in_loop_condition;
1253 self.is_in_loop_condition = true;
1255 let result = f(self);
1257 self.is_in_loop_condition = was_in_loop_condition;
1262 fn with_dyn_type_scope<T, F>(&mut self, in_scope: bool, f: F) -> T
1264 F: FnOnce(&mut LoweringContext<'_>) -> T,
1266 let was_in_dyn_type = self.is_in_dyn_type;
1267 self.is_in_dyn_type = in_scope;
1269 let result = f(self);
1271 self.is_in_dyn_type = was_in_dyn_type;
1276 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1278 F: FnOnce(&mut LoweringContext<'_>) -> T,
1280 let was_in_loop_condition = self.is_in_loop_condition;
1281 self.is_in_loop_condition = false;
1283 let catch_scopes = mem::take(&mut self.catch_scopes);
1284 let loop_scopes = mem::take(&mut self.loop_scopes);
1286 self.catch_scopes = catch_scopes;
1287 self.loop_scopes = loop_scopes;
1289 self.is_in_loop_condition = was_in_loop_condition;
1294 fn def_key(&mut self, id: DefId) -> DefKey {
1296 self.resolver.definitions().def_key(id.index)
1298 self.cstore.def_key(id)
1302 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1303 label.map(|label| hir::Label {
1308 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1309 let target_id = match destination {
1311 if let Some(loop_id) = self.resolver.get_label_res(id) {
1312 Ok(self.lower_node_id(loop_id))
1314 Err(hir::LoopIdError::UnresolvedLabel)
1321 .map(|id| Ok(self.lower_node_id(id)))
1322 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1327 label: self.lower_label(destination.map(|(_, label)| label)),
1332 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1335 .map(|a| self.lower_attr(a))
1339 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1340 // Note that we explicitly do not walk the path. Since we don't really
1341 // lower attributes (we use the AST version) there is nowhere to keep
1342 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1346 path: attr.path.clone(),
1347 tokens: self.lower_token_stream(attr.tokens.clone()),
1348 is_sugared_doc: attr.is_sugared_doc,
1353 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1356 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1360 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1362 TokenTree::Token(token) => self.lower_token(token),
1363 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1366 self.lower_token_stream(tts),
1371 fn lower_token(&mut self, token: Token) -> TokenStream {
1373 token::Interpolated(nt) => {
1374 let tts = nt.to_tokenstream(&self.sess.parse_sess, token.span);
1375 self.lower_token_stream(tts)
1377 _ => TokenTree::Token(token).into(),
1381 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1383 hir_id: self.next_id(),
1384 attrs: self.lower_attrs(&arm.attrs),
1385 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1386 guard: match arm.guard {
1387 Some(ref x) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1390 body: P(self.lower_expr(&arm.body)),
1395 /// Given an associated type constraint like one of these:
1398 /// T: Iterator<Item: Debug>
1400 /// T: Iterator<Item = Debug>
1404 /// returns a `hir::TypeBinding` representing `Item`.
1405 fn lower_assoc_ty_constraint(&mut self,
1406 c: &AssocTyConstraint,
1407 itctx: ImplTraitContext<'_>)
1408 -> hir::TypeBinding {
1409 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", c, itctx);
1411 let kind = match c.kind {
1412 AssocTyConstraintKind::Equality { ref ty } => hir::TypeBindingKind::Equality {
1413 ty: self.lower_ty(ty, itctx)
1415 AssocTyConstraintKind::Bound { ref bounds } => {
1416 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1417 let (desugar_to_impl_trait, itctx) = match itctx {
1418 // We are in the return position:
1420 // fn foo() -> impl Iterator<Item: Debug>
1424 // fn foo() -> impl Iterator<Item = impl Debug>
1425 ImplTraitContext::Existential(_) => (true, itctx),
1427 // We are in the argument position, but within a dyn type:
1429 // fn foo(x: dyn Iterator<Item: Debug>)
1433 // fn foo(x: dyn Iterator<Item = impl Debug>)
1434 ImplTraitContext::Universal(_) if self.is_in_dyn_type => (true, itctx),
1436 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1437 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1438 // "impl trait context" to permit `impl Debug` in this position (it desugars
1439 // then to an existential type).
1441 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1442 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type =>
1443 (true, ImplTraitContext::Existential(None)),
1445 // We are in the argument position, but not within a dyn type:
1447 // fn foo(x: impl Iterator<Item: Debug>)
1449 // so we leave it as is and this gets expanded in astconv to a bound like
1450 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1452 _ => (false, itctx),
1455 if desugar_to_impl_trait {
1456 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1457 // constructing the HIR for `impl bounds...` and then lowering that.
1459 let impl_trait_node_id = self.sess.next_node_id();
1460 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1461 self.resolver.definitions().create_def_with_parent(
1464 DefPathData::ImplTrait,
1469 self.with_dyn_type_scope(false, |this| {
1470 let ty = this.lower_ty(
1472 id: this.sess.next_node_id(),
1473 node: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1479 hir::TypeBindingKind::Equality {
1484 // Desugar `AssocTy: Bounds` into a type binding where the
1485 // later desugars into a trait predicate.
1486 let bounds = self.lower_param_bounds(bounds, itctx);
1488 hir::TypeBindingKind::Constraint {
1496 hir_id: self.lower_node_id(c.id),
1503 fn lower_generic_arg(&mut self,
1504 arg: &ast::GenericArg,
1505 itctx: ImplTraitContext<'_>)
1506 -> hir::GenericArg {
1508 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1509 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1510 ast::GenericArg::Const(ct) => {
1511 GenericArg::Const(ConstArg {
1512 value: self.lower_anon_const(&ct),
1513 span: ct.value.span,
1519 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1520 P(self.lower_ty_direct(t, itctx))
1526 qself: &Option<QSelf>,
1528 param_mode: ParamMode,
1529 itctx: ImplTraitContext<'_>
1531 let id = self.lower_node_id(t.id);
1532 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1533 let ty = self.ty_path(id, t.span, qpath);
1534 if let hir::TyKind::TraitObject(..) = ty.node {
1535 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1540 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1541 let kind = match t.node {
1542 TyKind::Infer => hir::TyKind::Infer,
1543 TyKind::Err => hir::TyKind::Err,
1544 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1545 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1546 TyKind::Rptr(ref region, ref mt) => {
1547 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1548 let lifetime = match *region {
1549 Some(ref lt) => self.lower_lifetime(lt),
1550 None => self.elided_ref_lifetime(span),
1552 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1554 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1557 this.with_anonymous_lifetime_mode(
1558 AnonymousLifetimeMode::PassThrough,
1560 hir::TyKind::BareFn(P(hir::BareFnTy {
1561 generic_params: this.lower_generic_params(
1563 &NodeMap::default(),
1564 ImplTraitContext::disallowed(),
1566 unsafety: this.lower_unsafety(f.unsafety),
1568 decl: this.lower_fn_decl(&f.decl, None, false, None),
1569 arg_names: this.lower_fn_args_to_names(&f.decl),
1575 TyKind::Never => hir::TyKind::Never,
1576 TyKind::Tup(ref tys) => {
1577 hir::TyKind::Tup(tys.iter().map(|ty| {
1578 self.lower_ty_direct(ty, itctx.reborrow())
1581 TyKind::Paren(ref ty) => {
1582 return self.lower_ty_direct(ty, itctx);
1584 TyKind::Path(ref qself, ref path) => {
1585 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1587 TyKind::ImplicitSelf => {
1588 let res = self.expect_full_res(t.id);
1589 let res = self.lower_res(res);
1590 hir::TyKind::Path(hir::QPath::Resolved(
1594 segments: hir_vec![hir::PathSegment::from_ident(
1595 Ident::with_empty_ctxt(kw::SelfUpper)
1601 TyKind::Array(ref ty, ref length) => {
1602 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1604 TyKind::Typeof(ref expr) => {
1605 hir::TyKind::Typeof(self.lower_anon_const(expr))
1607 TyKind::TraitObject(ref bounds, kind) => {
1608 let mut lifetime_bound = None;
1609 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1612 .filter_map(|bound| match *bound {
1613 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1614 Some(this.lower_poly_trait_ref(ty, itctx.reborrow()))
1616 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1617 GenericBound::Outlives(ref lifetime) => {
1618 if lifetime_bound.is_none() {
1619 lifetime_bound = Some(this.lower_lifetime(lifetime));
1625 let lifetime_bound =
1626 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1627 (bounds, lifetime_bound)
1629 if kind != TraitObjectSyntax::Dyn {
1630 self.maybe_lint_bare_trait(t.span, t.id, false);
1632 hir::TyKind::TraitObject(bounds, lifetime_bound)
1634 TyKind::ImplTrait(def_node_id, ref bounds) => {
1637 ImplTraitContext::Existential(fn_def_id) => {
1638 self.lower_existential_impl_trait(
1639 span, fn_def_id, def_node_id,
1640 |this| this.lower_param_bounds(bounds, itctx),
1643 ImplTraitContext::Universal(in_band_ty_params) => {
1644 // Add a definition for the in-band `Param`.
1645 let def_index = self
1648 .opt_def_index(def_node_id)
1651 let hir_bounds = self.lower_param_bounds(
1653 ImplTraitContext::Universal(in_band_ty_params),
1655 // Set the name to `impl Bound1 + Bound2`.
1656 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1657 in_band_ty_params.push(hir::GenericParam {
1658 hir_id: self.lower_node_id(def_node_id),
1659 name: ParamName::Plain(ident),
1660 pure_wrt_drop: false,
1664 kind: hir::GenericParamKind::Type {
1666 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1670 hir::TyKind::Path(hir::QPath::Resolved(
1674 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1675 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1679 ImplTraitContext::Disallowed(pos) => {
1680 let allowed_in = if self.sess.features_untracked()
1681 .impl_trait_in_bindings {
1682 "bindings or function and inherent method return types"
1684 "function and inherent method return types"
1686 let mut err = struct_span_err!(
1690 "`impl Trait` not allowed outside of {}",
1693 if pos == ImplTraitPosition::Binding &&
1694 nightly_options::is_nightly_build() {
1696 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1704 TyKind::Mac(_) => bug!("`TyMac` should have been expanded by now."),
1705 TyKind::CVarArgs => {
1706 // Create the implicit lifetime of the "spoofed" `VaListImpl`.
1707 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1708 let lt = self.new_implicit_lifetime(span);
1709 hir::TyKind::CVarArgs(lt)
1716 hir_id: self.lower_node_id(t.id),
1720 fn lower_existential_impl_trait(
1723 fn_def_id: Option<DefId>,
1724 exist_ty_node_id: NodeId,
1725 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1727 // Make sure we know that some funky desugaring has been going on here.
1728 // This is a first: there is code in other places like for loop
1729 // desugaring that explicitly states that we don't want to track that.
1730 // Not tracking it makes lints in rustc and clippy very fragile, as
1731 // frequently opened issues show.
1732 let exist_ty_span = self.mark_span_with_reason(
1733 CompilerDesugaringKind::ExistentialType,
1738 let exist_ty_def_index = self
1741 .opt_def_index(exist_ty_node_id)
1744 self.allocate_hir_id_counter(exist_ty_node_id);
1746 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1748 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1754 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1755 let exist_ty_item = hir::ExistTy {
1756 generics: hir::Generics {
1757 params: lifetime_defs,
1758 where_clause: hir::WhereClause {
1759 predicates: hir_vec![],
1765 impl_trait_fn: fn_def_id,
1766 origin: hir::ExistTyOrigin::ReturnImplTrait,
1769 trace!("exist ty from impl trait def-index: {:#?}", exist_ty_def_index);
1770 let exist_ty_id = lctx.generate_existential_type(
1777 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1778 hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, lifetimes)
1782 /// Registers a new existential type with the proper `NodeId`s and
1783 /// returns the lowered node-ID for the existential type.
1784 fn generate_existential_type(
1786 exist_ty_node_id: NodeId,
1787 exist_ty_item: hir::ExistTy,
1789 exist_ty_span: Span,
1791 let exist_ty_item_kind = hir::ItemKind::Existential(exist_ty_item);
1792 let exist_ty_id = self.lower_node_id(exist_ty_node_id);
1793 // Generate an `existential type Foo: Trait;` declaration.
1794 trace!("registering existential type with id {:#?}", exist_ty_id);
1795 let exist_ty_item = hir::Item {
1796 hir_id: exist_ty_id,
1797 ident: Ident::invalid(),
1798 attrs: Default::default(),
1799 node: exist_ty_item_kind,
1800 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1801 span: exist_ty_span,
1804 // Insert the item into the global item list. This usually happens
1805 // automatically for all AST items. But this existential type item
1806 // does not actually exist in the AST.
1807 self.insert_item(exist_ty_item);
1811 fn lifetimes_from_impl_trait_bounds(
1813 exist_ty_id: NodeId,
1814 parent_index: DefIndex,
1815 bounds: &hir::GenericBounds,
1816 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1817 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1818 // appear in the bounds, excluding lifetimes that are created within the bounds.
1819 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1820 struct ImplTraitLifetimeCollector<'r, 'a> {
1821 context: &'r mut LoweringContext<'a>,
1823 exist_ty_id: NodeId,
1824 collect_elided_lifetimes: bool,
1825 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1826 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1827 output_lifetimes: Vec<hir::GenericArg>,
1828 output_lifetime_params: Vec<hir::GenericParam>,
1831 impl<'r, 'a, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1832 fn nested_visit_map<'this>(
1834 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1835 hir::intravisit::NestedVisitorMap::None
1838 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1839 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1840 if parameters.parenthesized {
1841 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1842 self.collect_elided_lifetimes = false;
1843 hir::intravisit::walk_generic_args(self, span, parameters);
1844 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1846 hir::intravisit::walk_generic_args(self, span, parameters);
1850 fn visit_ty(&mut self, t: &'v hir::Ty) {
1851 // Don't collect elided lifetimes used inside of `fn()` syntax.
1852 if let hir::TyKind::BareFn(_) = t.node {
1853 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1854 self.collect_elided_lifetimes = false;
1856 // Record the "stack height" of `for<'a>` lifetime bindings
1857 // to be able to later fully undo their introduction.
1858 let old_len = self.currently_bound_lifetimes.len();
1859 hir::intravisit::walk_ty(self, t);
1860 self.currently_bound_lifetimes.truncate(old_len);
1862 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1864 hir::intravisit::walk_ty(self, t)
1868 fn visit_poly_trait_ref(
1870 trait_ref: &'v hir::PolyTraitRef,
1871 modifier: hir::TraitBoundModifier,
1873 // Record the "stack height" of `for<'a>` lifetime bindings
1874 // to be able to later fully undo their introduction.
1875 let old_len = self.currently_bound_lifetimes.len();
1876 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1877 self.currently_bound_lifetimes.truncate(old_len);
1880 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1881 // Record the introduction of 'a in `for<'a> ...`.
1882 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1883 // Introduce lifetimes one at a time so that we can handle
1884 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1885 let lt_name = hir::LifetimeName::Param(param.name);
1886 self.currently_bound_lifetimes.push(lt_name);
1889 hir::intravisit::walk_generic_param(self, param);
1892 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1893 let name = match lifetime.name {
1894 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1895 if self.collect_elided_lifetimes {
1896 // Use `'_` for both implicit and underscore lifetimes in
1897 // `abstract type Foo<'_>: SomeTrait<'_>;`.
1898 hir::LifetimeName::Underscore
1903 hir::LifetimeName::Param(_) => lifetime.name,
1904 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1907 if !self.currently_bound_lifetimes.contains(&name)
1908 && !self.already_defined_lifetimes.contains(&name) {
1909 self.already_defined_lifetimes.insert(name);
1911 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1912 hir_id: self.context.next_id(),
1913 span: lifetime.span,
1917 let def_node_id = self.context.sess.next_node_id();
1919 self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1920 self.context.resolver.definitions().create_def_with_parent(
1923 DefPathData::LifetimeNs(name.ident().as_interned_str()),
1927 let (name, kind) = match name {
1928 hir::LifetimeName::Underscore => (
1929 hir::ParamName::Plain(Ident::with_empty_ctxt(kw::UnderscoreLifetime)),
1930 hir::LifetimeParamKind::Elided,
1932 hir::LifetimeName::Param(param_name) => (
1934 hir::LifetimeParamKind::Explicit,
1936 _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1939 self.output_lifetime_params.push(hir::GenericParam {
1942 span: lifetime.span,
1943 pure_wrt_drop: false,
1946 kind: hir::GenericParamKind::Lifetime { kind }
1952 let mut lifetime_collector = ImplTraitLifetimeCollector {
1954 parent: parent_index,
1956 collect_elided_lifetimes: true,
1957 currently_bound_lifetimes: Vec::new(),
1958 already_defined_lifetimes: FxHashSet::default(),
1959 output_lifetimes: Vec::new(),
1960 output_lifetime_params: Vec::new(),
1963 for bound in bounds {
1964 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1968 lifetime_collector.output_lifetimes.into(),
1969 lifetime_collector.output_lifetime_params.into(),
1973 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1978 .map(|x| self.lower_foreign_item(x))
1983 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1990 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1992 node: hir::VariantKind {
1993 ident: v.node.ident,
1994 id: self.lower_node_id(v.node.id),
1995 attrs: self.lower_attrs(&v.node.attrs),
1996 data: self.lower_variant_data(&v.node.data),
1997 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
2006 qself: &Option<QSelf>,
2008 param_mode: ParamMode,
2009 mut itctx: ImplTraitContext<'_>,
2011 let qself_position = qself.as_ref().map(|q| q.position);
2012 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
2014 let partial_res = self.resolver
2015 .get_partial_res(id)
2016 .unwrap_or_else(|| PartialRes::new(Res::Err));
2018 let proj_start = p.segments.len() - partial_res.unresolved_segments();
2019 let path = P(hir::Path {
2020 res: self.lower_res(partial_res.base_res()),
2021 segments: p.segments[..proj_start]
2024 .map(|(i, segment)| {
2025 let param_mode = match (qself_position, param_mode) {
2026 (Some(j), ParamMode::Optional) if i < j => {
2027 // This segment is part of the trait path in a
2028 // qualified path - one of `a`, `b` or `Trait`
2029 // in `<X as a::b::Trait>::T::U::method`.
2035 // Figure out if this is a type/trait segment,
2036 // which may need lifetime elision performed.
2037 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
2038 krate: def_id.krate,
2039 index: this.def_key(def_id).parent.expect("missing parent"),
2041 let type_def_id = match partial_res.base_res() {
2042 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2043 Some(parent_def_id(self, def_id))
2045 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2046 Some(parent_def_id(self, def_id))
2048 Res::Def(DefKind::Struct, def_id)
2049 | Res::Def(DefKind::Union, def_id)
2050 | Res::Def(DefKind::Enum, def_id)
2051 | Res::Def(DefKind::TyAlias, def_id)
2052 | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
2058 let parenthesized_generic_args = match partial_res.base_res() {
2059 // `a::b::Trait(Args)`
2060 Res::Def(DefKind::Trait, _)
2061 if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
2062 // `a::b::Trait(Args)::TraitItem`
2063 Res::Def(DefKind::Method, _)
2064 | Res::Def(DefKind::AssocConst, _)
2065 | Res::Def(DefKind::AssocTy, _)
2066 if i + 2 == proj_start =>
2068 ParenthesizedGenericArgs::Ok
2070 // Avoid duplicated errors.
2071 Res::Err => ParenthesizedGenericArgs::Ok,
2073 Res::Def(DefKind::Struct, _)
2074 | Res::Def(DefKind::Enum, _)
2075 | Res::Def(DefKind::Union, _)
2076 | Res::Def(DefKind::TyAlias, _)
2077 | Res::Def(DefKind::Variant, _) if i + 1 == proj_start =>
2079 ParenthesizedGenericArgs::Err
2081 // A warning for now, for compatibility reasons.
2082 _ => ParenthesizedGenericArgs::Warn,
2085 let num_lifetimes = type_def_id.map_or(0, |def_id| {
2086 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
2089 assert!(!def_id.is_local());
2091 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
2092 let n = item_generics.own_counts().lifetimes;
2093 self.type_def_lifetime_params.insert(def_id, n);
2096 self.lower_path_segment(
2101 parenthesized_generic_args,
2110 // Simple case, either no projections, or only fully-qualified.
2111 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
2112 if partial_res.unresolved_segments() == 0 {
2113 return hir::QPath::Resolved(qself, path);
2116 // Create the innermost type that we're projecting from.
2117 let mut ty = if path.segments.is_empty() {
2118 // If the base path is empty that means there exists a
2119 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
2120 qself.expect("missing QSelf for <T>::...")
2122 // Otherwise, the base path is an implicit `Self` type path,
2123 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
2124 // `<I as Iterator>::Item::default`.
2125 let new_id = self.next_id();
2126 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
2129 // Anything after the base path are associated "extensions",
2130 // out of which all but the last one are associated types,
2131 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
2132 // * base path is `std::vec::Vec<T>`
2133 // * "extensions" are `IntoIter`, `Item` and `clone`
2134 // * type nodes are:
2135 // 1. `std::vec::Vec<T>` (created above)
2136 // 2. `<std::vec::Vec<T>>::IntoIter`
2137 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
2138 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
2139 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
2140 let segment = P(self.lower_path_segment(
2145 ParenthesizedGenericArgs::Warn,
2149 let qpath = hir::QPath::TypeRelative(ty, segment);
2151 // It's finished, return the extension of the right node type.
2152 if i == p.segments.len() - 1 {
2156 // Wrap the associated extension in another type node.
2157 let new_id = self.next_id();
2158 ty = P(self.ty_path(new_id, p.span, qpath));
2161 // We should've returned in the for loop above.
2164 "lower_qpath: no final extension segment in {}..{}",
2170 fn lower_path_extra(
2174 param_mode: ParamMode,
2175 explicit_owner: Option<NodeId>,
2179 segments: p.segments
2182 self.lower_path_segment(
2187 ParenthesizedGenericArgs::Err,
2188 ImplTraitContext::disallowed(),
2197 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
2198 let res = self.expect_full_res(id);
2199 let res = self.lower_res(res);
2200 self.lower_path_extra(res, p, param_mode, None)
2203 fn lower_path_segment(
2206 segment: &PathSegment,
2207 param_mode: ParamMode,
2208 expected_lifetimes: usize,
2209 parenthesized_generic_args: ParenthesizedGenericArgs,
2210 itctx: ImplTraitContext<'_>,
2211 explicit_owner: Option<NodeId>,
2212 ) -> hir::PathSegment {
2213 let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
2214 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
2215 match **generic_args {
2216 GenericArgs::AngleBracketed(ref data) => {
2217 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
2219 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
2220 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
2221 ParenthesizedGenericArgs::Warn => {
2222 self.sess.buffer_lint(
2223 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
2228 (hir::GenericArgs::none(), true)
2230 ParenthesizedGenericArgs::Err => {
2231 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
2232 err.span_label(data.span, "only `Fn` traits may use parentheses");
2233 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
2234 // Do not suggest going from `Trait()` to `Trait<>`
2235 if data.inputs.len() > 0 {
2236 err.span_suggestion(
2238 "use angle brackets instead",
2239 format!("<{}>", &snippet[1..snippet.len() - 1]),
2240 Applicability::MaybeIncorrect,
2246 self.lower_angle_bracketed_parameter_data(
2247 &data.as_angle_bracketed_args(),
2257 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
2260 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
2261 GenericArg::Lifetime(_) => true,
2264 let first_generic_span = generic_args.args.iter().map(|a| a.span())
2265 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
2266 if !generic_args.parenthesized && !has_lifetimes {
2268 self.elided_path_lifetimes(path_span, expected_lifetimes)
2270 .map(|lt| GenericArg::Lifetime(lt))
2271 .chain(generic_args.args.into_iter())
2273 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
2274 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
2275 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
2276 let no_bindings = generic_args.bindings.is_empty();
2277 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
2278 // If there are no (non-implicit) generic args or associated type
2279 // bindings, our suggestion includes the angle brackets.
2280 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
2282 // Otherwise (sorry, this is kind of gross) we need to infer the
2283 // place to splice in the `'_, ` from the generics that do exist.
2284 let first_generic_span = first_generic_span
2285 .expect("already checked that non-lifetime args or bindings exist");
2286 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
2288 match self.anonymous_lifetime_mode {
2289 // In create-parameter mode we error here because we don't want to support
2290 // deprecated impl elision in new features like impl elision and `async fn`,
2291 // both of which work using the `CreateParameter` mode:
2293 // impl Foo for std::cell::Ref<u32> // note lack of '_
2294 // async fn foo(_: std::cell::Ref<u32>) { ... }
2295 AnonymousLifetimeMode::CreateParameter => {
2296 let mut err = struct_span_err!(
2300 "implicit elided lifetime not allowed here"
2302 crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
2313 AnonymousLifetimeMode::PassThrough |
2314 AnonymousLifetimeMode::ReportError |
2315 AnonymousLifetimeMode::Replace(_) => {
2316 self.sess.buffer_lint_with_diagnostic(
2317 ELIDED_LIFETIMES_IN_PATHS,
2320 "hidden lifetime parameters in types are deprecated",
2321 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2334 let res = self.expect_full_res(segment.id);
2335 let id = if let Some(owner) = explicit_owner {
2336 self.lower_node_id_with_owner(segment.id, owner)
2338 self.lower_node_id(segment.id)
2341 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2342 segment.ident, segment.id, id,
2345 hir::PathSegment::new(
2348 Some(self.lower_res(res)),
2354 fn lower_angle_bracketed_parameter_data(
2356 data: &AngleBracketedArgs,
2357 param_mode: ParamMode,
2358 mut itctx: ImplTraitContext<'_>,
2359 ) -> (hir::GenericArgs, bool) {
2360 let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
2361 let has_non_lt_args = args.iter().any(|arg| match arg {
2362 ast::GenericArg::Lifetime(_) => false,
2363 ast::GenericArg::Type(_) => true,
2364 ast::GenericArg::Const(_) => true,
2368 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2369 bindings: constraints.iter()
2370 .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow()))
2372 parenthesized: false,
2374 !has_non_lt_args && param_mode == ParamMode::Optional
2378 fn lower_parenthesized_parameter_data(
2380 data: &ParenthesizedArgs,
2381 ) -> (hir::GenericArgs, bool) {
2382 // Switch to `PassThrough` mode for anonymous lifetimes; this
2383 // means that we permit things like `&Ref<T>`, where `Ref` has
2384 // a hidden lifetime parameter. This is needed for backwards
2385 // compatibility, even in contexts like an impl header where
2386 // we generally don't permit such things (see #51008).
2387 self.with_anonymous_lifetime_mode(
2388 AnonymousLifetimeMode::PassThrough,
2390 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2393 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2395 let mk_tup = |this: &mut Self, tys, span| {
2396 hir::Ty { node: hir::TyKind::Tup(tys), hir_id: this.next_id(), span }
2400 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2403 hir_id: this.next_id(),
2404 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2405 kind: hir::TypeBindingKind::Equality {
2408 .map(|ty| this.lower_ty(
2410 ImplTraitContext::disallowed()
2413 P(mk_tup(this, hir::HirVec::new(), span))
2416 span: output.as_ref().map_or(span, |ty| ty.span),
2419 parenthesized: true,
2427 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2428 let mut ids = SmallVec::<[NodeId; 1]>::new();
2429 if self.sess.features_untracked().impl_trait_in_bindings {
2430 if let Some(ref ty) = l.ty {
2431 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2432 visitor.visit_ty(ty);
2435 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2437 hir_id: self.lower_node_id(l.id),
2440 .map(|t| self.lower_ty(t,
2441 if self.sess.features_untracked().impl_trait_in_bindings {
2442 ImplTraitContext::Existential(Some(parent_def_id))
2444 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2447 pat: self.lower_pat(&l.pat),
2448 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2450 attrs: l.attrs.clone(),
2451 source: hir::LocalSource::Normal,
2455 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2457 Mutability::Mutable => hir::MutMutable,
2458 Mutability::Immutable => hir::MutImmutable,
2462 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
2464 hir_id: self.lower_node_id(arg.id),
2465 pat: self.lower_pat(&arg.pat),
2469 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2472 .map(|arg| match arg.pat.node {
2473 PatKind::Ident(_, ident, _) => ident,
2474 _ => Ident::new(kw::Invalid, arg.pat.span),
2479 // Lowers a function declaration.
2481 // `decl`: the unlowered (AST) function declaration.
2482 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2483 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2484 // `make_ret_async` is also `Some`.
2485 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2486 // This guards against trait declarations and implementations where `impl Trait` is
2488 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2489 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2490 // return type `impl Trait` item.
2494 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2495 impl_trait_return_allow: bool,
2496 make_ret_async: Option<NodeId>,
2497 ) -> P<hir::FnDecl> {
2498 let lt_mode = if make_ret_async.is_some() {
2499 // In `async fn`, argument-position elided lifetimes
2500 // must be transformed into fresh generic parameters so that
2501 // they can be applied to the existential return type.
2502 AnonymousLifetimeMode::CreateParameter
2504 self.anonymous_lifetime_mode
2507 // Remember how many lifetimes were already around so that we can
2508 // only look at the lifetime parameters introduced by the arguments.
2509 let lifetime_count_before_args = self.lifetimes_to_define.len();
2510 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2514 if let Some((_, ibty)) = &mut in_band_ty_params {
2515 this.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2517 this.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2520 .collect::<HirVec<_>>()
2523 let output = if let Some(ret_id) = make_ret_async {
2524 // Calculate the `LtReplacement` to use for any return-position elided
2525 // lifetimes based on the elided lifetime parameters introduced in the args.
2526 let lt_replacement = get_elided_lt_replacement(
2527 &self.lifetimes_to_define[lifetime_count_before_args..]
2529 self.lower_async_fn_ret_ty(
2531 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2537 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2538 Some((def_id, _)) if impl_trait_return_allow => {
2539 hir::Return(self.lower_ty(ty,
2540 ImplTraitContext::Existential(Some(def_id))
2544 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2547 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2554 c_variadic: decl.c_variadic,
2555 implicit_self: decl.inputs.get(0).map_or(
2556 hir::ImplicitSelfKind::None,
2558 let is_mutable_pat = match arg.pat.node {
2559 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2560 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2561 mt == Mutability::Mutable,
2566 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2567 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2568 // Given we are only considering `ImplicitSelf` types, we needn't consider
2569 // the case where we have a mutable pattern to a reference as that would
2570 // no longer be an `ImplicitSelf`.
2571 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2572 mt.mutbl == ast::Mutability::Mutable =>
2573 hir::ImplicitSelfKind::MutRef,
2574 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2575 hir::ImplicitSelfKind::ImmRef,
2576 _ => hir::ImplicitSelfKind::None,
2583 // Transforms `-> T` for `async fn` into `-> ExistTy { .. }`
2584 // combined with the following definition of `ExistTy`:
2586 // existential type ExistTy<generics_from_parent_fn>: Future<Output = T>;
2588 // `inputs`: lowered types of arguments to the function (used to collect lifetimes)
2589 // `output`: unlowered output type (`T` in `-> T`)
2590 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2591 // `exist_ty_node_id`: `NodeId` of the existential type that should be created
2592 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2593 fn lower_async_fn_ret_ty(
2595 output: &FunctionRetTy,
2597 exist_ty_node_id: NodeId,
2598 elided_lt_replacement: LtReplacement,
2599 ) -> hir::FunctionRetTy {
2600 let span = output.span();
2602 let exist_ty_span = self.mark_span_with_reason(
2603 CompilerDesugaringKind::Async,
2608 let exist_ty_def_index = self
2611 .opt_def_index(exist_ty_node_id)
2614 self.allocate_hir_id_counter(exist_ty_node_id);
2616 let (exist_ty_id, lifetime_params) = self.with_hir_id_owner(exist_ty_node_id, |this| {
2617 let future_bound = this.with_anonymous_lifetime_mode(
2618 AnonymousLifetimeMode::Replace(elided_lt_replacement),
2619 |this| this.lower_async_fn_output_type_to_future_bound(
2626 // Calculate all the lifetimes that should be captured
2627 // by the existential type. This should include all in-scope
2628 // lifetime parameters, including those defined in-band.
2630 // Note: this must be done after lowering the output type,
2631 // as the output type may introduce new in-band lifetimes.
2632 let lifetime_params: Vec<(Span, ParamName)> =
2633 this.in_scope_lifetimes
2635 .map(|ident| (ident.span, ParamName::Plain(ident)))
2636 .chain(this.lifetimes_to_define.iter().cloned())
2639 let generic_params =
2642 .map(|(span, hir_name)| {
2643 this.lifetime_to_generic_param(span, hir_name, exist_ty_def_index)
2647 let exist_ty_item = hir::ExistTy {
2648 generics: hir::Generics {
2649 params: generic_params,
2650 where_clause: hir::WhereClause {
2651 predicates: hir_vec![],
2656 bounds: hir_vec![future_bound],
2657 impl_trait_fn: Some(fn_def_id),
2658 origin: hir::ExistTyOrigin::AsyncFn,
2661 trace!("exist ty from async fn def index: {:#?}", exist_ty_def_index);
2662 let exist_ty_id = this.generate_existential_type(
2669 (exist_ty_id, lifetime_params)
2675 .map(|(span, hir_name)| {
2676 GenericArg::Lifetime(hir::Lifetime {
2677 hir_id: self.next_id(),
2679 name: hir::LifetimeName::Param(hir_name),
2684 let exist_ty_ref = hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, generic_args);
2686 hir::FunctionRetTy::Return(P(hir::Ty {
2689 hir_id: self.next_id(),
2693 /// Transforms `-> T` into `Future<Output = T>`
2694 fn lower_async_fn_output_type_to_future_bound(
2696 output: &FunctionRetTy,
2699 ) -> hir::GenericBound {
2700 // Compute the `T` in `Future<Output = T>` from the return type.
2701 let output_ty = match output {
2702 FunctionRetTy::Ty(ty) => {
2703 self.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2705 FunctionRetTy::Default(ret_ty_span) => {
2707 hir_id: self.next_id(),
2708 node: hir::TyKind::Tup(hir_vec![]),
2715 let future_params = P(hir::GenericArgs {
2717 bindings: hir_vec![hir::TypeBinding {
2718 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2719 kind: hir::TypeBindingKind::Equality {
2722 hir_id: self.next_id(),
2725 parenthesized: false,
2728 // ::std::future::Future<future_params>
2730 P(self.std_path(span, &[sym::future, sym::Future], Some(future_params), false));
2732 hir::GenericBound::Trait(
2734 trait_ref: hir::TraitRef {
2736 hir_ref_id: self.next_id(),
2738 bound_generic_params: hir_vec![],
2741 hir::TraitBoundModifier::None,
2745 fn lower_param_bound(
2748 itctx: ImplTraitContext<'_>,
2749 ) -> hir::GenericBound {
2751 GenericBound::Trait(ref ty, modifier) => {
2752 hir::GenericBound::Trait(
2753 self.lower_poly_trait_ref(ty, itctx),
2754 self.lower_trait_bound_modifier(modifier),
2757 GenericBound::Outlives(ref lifetime) => {
2758 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2763 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2764 let span = l.ident.span;
2766 ident if ident.name == kw::StaticLifetime =>
2767 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2768 ident if ident.name == kw::UnderscoreLifetime =>
2769 match self.anonymous_lifetime_mode {
2770 AnonymousLifetimeMode::CreateParameter => {
2771 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2772 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2775 AnonymousLifetimeMode::PassThrough => {
2776 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2779 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2781 AnonymousLifetimeMode::Replace(replacement) => {
2782 let hir_id = self.lower_node_id(l.id);
2783 self.replace_elided_lifetime(hir_id, span, replacement)
2787 self.maybe_collect_in_band_lifetime(ident);
2788 let param_name = ParamName::Plain(ident);
2789 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2794 fn new_named_lifetime(
2798 name: hir::LifetimeName,
2799 ) -> hir::Lifetime {
2801 hir_id: self.lower_node_id(id),
2807 /// Replace a return-position elided lifetime with the elided lifetime
2808 /// from the arguments.
2809 fn replace_elided_lifetime(
2813 replacement: LtReplacement,
2814 ) -> hir::Lifetime {
2815 let multiple_or_none = match replacement {
2816 LtReplacement::Some(name) => {
2817 return hir::Lifetime {
2820 name: hir::LifetimeName::Param(name),
2823 LtReplacement::MultipleLifetimes => "multiple",
2824 LtReplacement::NoLifetimes => "none",
2827 let mut err = crate::middle::resolve_lifetime::report_missing_lifetime_specifiers(
2833 "return-position elided lifetimes require exactly one \
2834 input-position elided lifetime, found {}.", multiple_or_none));
2837 hir::Lifetime { hir_id, span, name: hir::LifetimeName::Error }
2840 fn lower_generic_params(
2842 params: &[GenericParam],
2843 add_bounds: &NodeMap<Vec<GenericBound>>,
2844 mut itctx: ImplTraitContext<'_>,
2845 ) -> hir::HirVec<hir::GenericParam> {
2846 params.iter().map(|param| {
2847 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2851 fn lower_generic_param(&mut self,
2852 param: &GenericParam,
2853 add_bounds: &NodeMap<Vec<GenericBound>>,
2854 mut itctx: ImplTraitContext<'_>)
2855 -> hir::GenericParam {
2856 let mut bounds = self.with_anonymous_lifetime_mode(
2857 AnonymousLifetimeMode::ReportError,
2858 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2861 let (name, kind) = match param.kind {
2862 GenericParamKind::Lifetime => {
2863 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2864 self.is_collecting_in_band_lifetimes = false;
2866 let lt = self.with_anonymous_lifetime_mode(
2867 AnonymousLifetimeMode::ReportError,
2868 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2870 let param_name = match lt.name {
2871 hir::LifetimeName::Param(param_name) => param_name,
2872 hir::LifetimeName::Implicit
2873 | hir::LifetimeName::Underscore
2874 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2875 hir::LifetimeName::Error => ParamName::Error,
2878 let kind = hir::GenericParamKind::Lifetime {
2879 kind: hir::LifetimeParamKind::Explicit
2882 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2886 GenericParamKind::Type { ref default, .. } => {
2887 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2888 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2889 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2890 let ident = if param.ident.name == kw::SelfUpper {
2891 param.ident.gensym()
2896 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2897 if !add_bounds.is_empty() {
2898 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2899 bounds = bounds.into_iter()
2904 let kind = hir::GenericParamKind::Type {
2905 default: default.as_ref().map(|x| {
2906 self.lower_ty(x, ImplTraitContext::Existential(None))
2908 synthetic: param.attrs.iter()
2909 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2910 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2914 (hir::ParamName::Plain(ident), kind)
2916 GenericParamKind::Const { ref ty } => {
2917 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2918 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2924 hir_id: self.lower_node_id(param.id),
2926 span: param.ident.span,
2927 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2928 attrs: self.lower_attrs(¶m.attrs),
2936 generics: &Generics,
2937 itctx: ImplTraitContext<'_>)
2940 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2941 // FIXME: this could probably be done with less rightward drift. It also looks like two
2942 // control paths where `report_error` is called are the only paths that advance to after the
2943 // match statement, so the error reporting could probably just be moved there.
2944 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2945 for pred in &generics.where_clause.predicates {
2946 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2947 'next_bound: for bound in &bound_pred.bounds {
2948 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2949 let report_error = |this: &mut Self| {
2950 this.diagnostic().span_err(
2951 bound_pred.bounded_ty.span,
2952 "`?Trait` bounds are only permitted at the \
2953 point where a type parameter is declared",
2956 // Check if the where clause type is a plain type parameter.
2957 match bound_pred.bounded_ty.node {
2958 TyKind::Path(None, ref path)
2959 if path.segments.len() == 1
2960 && bound_pred.bound_generic_params.is_empty() =>
2962 if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver
2963 .get_partial_res(bound_pred.bounded_ty.id)
2964 .map(|d| d.base_res())
2966 if let Some(node_id) =
2967 self.resolver.definitions().as_local_node_id(def_id)
2969 for param in &generics.params {
2971 GenericParamKind::Type { .. } => {
2972 if node_id == param.id {
2973 add_bounds.entry(param.id)
2975 .push(bound.clone());
2976 continue 'next_bound;
2986 _ => report_error(self),
2994 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2995 where_clause: self.lower_where_clause(&generics.where_clause),
2996 span: generics.span,
3000 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
3001 self.with_anonymous_lifetime_mode(
3002 AnonymousLifetimeMode::ReportError,
3005 predicates: wc.predicates
3007 .map(|predicate| this.lower_where_predicate(predicate))
3015 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
3017 WherePredicate::BoundPredicate(WhereBoundPredicate {
3018 ref bound_generic_params,
3023 self.with_in_scope_lifetime_defs(
3024 &bound_generic_params,
3026 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
3027 bound_generic_params: this.lower_generic_params(
3028 bound_generic_params,
3029 &NodeMap::default(),
3030 ImplTraitContext::disallowed(),
3032 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
3035 .filter_map(|bound| match *bound {
3036 // Ignore `?Trait` bounds.
3037 // They were copied into type parameters already.
3038 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
3039 _ => Some(this.lower_param_bound(
3041 ImplTraitContext::disallowed(),
3050 WherePredicate::RegionPredicate(WhereRegionPredicate {
3054 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
3056 lifetime: self.lower_lifetime(lifetime),
3057 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3059 WherePredicate::EqPredicate(WhereEqPredicate {
3065 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
3066 hir_id: self.lower_node_id(id),
3067 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
3068 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
3075 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
3077 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
3078 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
3081 VariantData::Tuple(ref fields, id) => {
3082 hir::VariantData::Tuple(
3086 .map(|f| self.lower_struct_field(f))
3088 self.lower_node_id(id),
3091 VariantData::Unit(id) => {
3092 hir::VariantData::Unit(self.lower_node_id(id))
3097 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
3098 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
3099 hir::QPath::Resolved(None, path) => path,
3100 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
3104 hir_ref_id: self.lower_node_id(p.ref_id),
3108 fn lower_poly_trait_ref(
3111 mut itctx: ImplTraitContext<'_>,
3112 ) -> hir::PolyTraitRef {
3113 let bound_generic_params = self.lower_generic_params(
3114 &p.bound_generic_params,
3115 &NodeMap::default(),
3118 let trait_ref = self.with_in_scope_lifetime_defs(
3119 &p.bound_generic_params,
3120 |this| this.lower_trait_ref(&p.trait_ref, itctx),
3124 bound_generic_params,
3130 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
3131 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.node {
3132 let t = self.lower_path_ty(
3136 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
3137 ImplTraitContext::disallowed()
3141 self.lower_ty(&f.ty, ImplTraitContext::disallowed())
3145 hir_id: self.lower_node_id(f.id),
3146 ident: match f.ident {
3147 Some(ident) => ident,
3148 // FIXME(jseyfried): positional field hygiene.
3149 None => Ident::new(sym::integer(index), f.span),
3151 vis: self.lower_visibility(&f.vis, None),
3153 attrs: self.lower_attrs(&f.attrs),
3157 fn lower_field(&mut self, f: &Field) -> hir::Field {
3159 hir_id: self.next_id(),
3161 expr: P(self.lower_expr(&f.expr)),
3163 is_shorthand: f.is_shorthand,
3167 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
3169 ty: self.lower_ty(&mt.ty, itctx),
3170 mutbl: self.lower_mutability(mt.mutbl),
3174 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
3175 -> hir::GenericBounds {
3176 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
3179 fn lower_block_with_stmts(
3182 targeted_by_break: bool,
3183 mut stmts: Vec<hir::Stmt>,
3184 ) -> P<hir::Block> {
3185 let mut expr = None;
3187 for (index, stmt) in b.stmts.iter().enumerate() {
3188 if index == b.stmts.len() - 1 {
3189 if let StmtKind::Expr(ref e) = stmt.node {
3190 expr = Some(P(self.lower_expr(e)));
3192 stmts.extend(self.lower_stmt(stmt));
3195 stmts.extend(self.lower_stmt(stmt));
3200 hir_id: self.lower_node_id(b.id),
3201 stmts: stmts.into(),
3203 rules: self.lower_block_check_mode(&b.rules),
3209 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
3210 self.lower_block_with_stmts(b, targeted_by_break, vec![])
3213 fn lower_maybe_async_body(
3219 let closure_id = match asyncness {
3220 IsAsync::Async { closure_id, .. } => closure_id,
3221 IsAsync::NotAsync => return self.lower_fn_body(&decl, |this| {
3222 let body = this.lower_block(body, false);
3223 this.expr_block(body, ThinVec::new())
3227 self.lower_body(|this| {
3228 let mut arguments: Vec<hir::Arg> = Vec::new();
3229 let mut statements: Vec<hir::Stmt> = Vec::new();
3231 // Async function arguments are lowered into the closure body so that they are
3232 // captured and so that the drop order matches the equivalent non-async functions.
3236 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
3243 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
3245 // let __arg2 = __arg2;
3246 // let <pattern> = __arg2;
3247 // let __arg1 = __arg1;
3248 // let <pattern> = __arg1;
3249 // let __arg0 = __arg0;
3250 // let <pattern> = __arg0;
3254 // If `<pattern>` is a simple ident, then it is lowered to a single
3255 // `let <pattern> = <pattern>;` statement as an optimization.
3256 for (index, argument) in decl.inputs.iter().enumerate() {
3257 let argument = this.lower_arg(argument);
3258 let span = argument.pat.span;
3260 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
3261 // `let <pat> = __argN;` statement. In this case, we do not rename the argument.
3262 let (ident, is_simple_argument) = match argument.pat.node {
3263 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) =>
3266 // Replace the ident for bindings that aren't simple.
3267 let name = format!("__arg{}", index);
3268 let ident = Ident::from_str(&name);
3274 let desugared_span =
3275 this.mark_span_with_reason(CompilerDesugaringKind::Async, span, None);
3277 // Construct an argument representing `__argN: <ty>` to replace the argument of the
3280 // If this is the simple case, this argument will end up being the same as the
3281 // original argument, but with a different pattern id.
3282 let (new_argument_pat, new_argument_id) = this.pat_ident(desugared_span, ident);
3283 let new_argument = hir::Arg {
3284 hir_id: argument.hir_id,
3285 pat: new_argument_pat,
3288 if is_simple_argument {
3289 // If this is the simple case, then we only insert one statement that is
3290 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
3291 // `HirId`s are densely assigned.
3292 let expr = this.expr_ident(desugared_span, ident, new_argument_id);
3293 let stmt = this.stmt_let_pat(
3294 desugared_span, Some(P(expr)), argument.pat, hir::LocalSource::AsyncFn);
3295 statements.push(stmt);
3297 // If this is not the simple case, then we construct two statements:
3300 // let __argN = __argN;
3301 // let <pat> = __argN;
3304 // The first statement moves the argument into the closure and thus ensures
3305 // that the drop order is correct.
3307 // The second statement creates the bindings that the user wrote.
3309 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
3310 // because the user may have specified a `ref mut` binding in the next
3312 let (move_pat, move_id) = this.pat_ident_binding_mode(
3313 desugared_span, ident, hir::BindingAnnotation::Mutable);
3314 let move_expr = this.expr_ident(desugared_span, ident, new_argument_id);
3315 let move_stmt = this.stmt_let_pat(
3316 desugared_span, Some(P(move_expr)), move_pat, hir::LocalSource::AsyncFn);
3318 // Construct the `let <pat> = __argN;` statement. We re-use the original
3319 // argument's pattern so that `HirId`s are densely assigned.
3320 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
3321 let pattern_stmt = this.stmt_let_pat(
3322 desugared_span, Some(P(pattern_expr)), argument.pat,
3323 hir::LocalSource::AsyncFn);
3325 statements.push(move_stmt);
3326 statements.push(pattern_stmt);
3329 arguments.push(new_argument);
3332 let async_expr = this.make_async_expr(
3333 CaptureBy::Value, closure_id, None, body.span,
3335 let body = this.lower_block_with_stmts(body, false, statements);
3336 this.expr_block(body, ThinVec::new())
3338 (HirVec::from(arguments), this.expr(body.span, async_expr, ThinVec::new()))
3346 attrs: &hir::HirVec<Attribute>,
3347 vis: &mut hir::Visibility,
3349 ) -> hir::ItemKind {
3351 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
3352 ItemKind::Use(ref use_tree) => {
3353 // Start with an empty prefix.
3356 span: use_tree.span,
3359 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
3361 ItemKind::Static(ref t, m, ref e) => {
3362 hir::ItemKind::Static(
3365 if self.sess.features_untracked().impl_trait_in_bindings {
3366 ImplTraitContext::Existential(None)
3368 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3371 self.lower_mutability(m),
3372 self.lower_const_body(e),
3375 ItemKind::Const(ref t, ref e) => {
3376 hir::ItemKind::Const(
3379 if self.sess.features_untracked().impl_trait_in_bindings {
3380 ImplTraitContext::Existential(None)
3382 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3385 self.lower_const_body(e)
3388 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
3389 let fn_def_id = self.resolver.definitions().local_def_id(id);
3390 self.with_new_scopes(|this| {
3391 this.current_item = Some(ident.span);
3393 // Note: we don't need to change the return type from `T` to
3394 // `impl Future<Output = T>` here because lower_body
3395 // only cares about the input argument patterns in the function
3396 // declaration (decl), not the return types.
3397 let body_id = this.lower_maybe_async_body(&decl, header.asyncness.node, body);
3399 let (generics, fn_decl) = this.add_in_band_defs(
3402 AnonymousLifetimeMode::PassThrough,
3403 |this, idty| this.lower_fn_decl(
3405 Some((fn_def_id, idty)),
3407 header.asyncness.node.opt_return_id()
3413 this.lower_fn_header(header),
3419 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
3420 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
3421 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
3422 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
3423 self.lower_ty(t, ImplTraitContext::disallowed()),
3424 self.lower_generics(generics, ImplTraitContext::disallowed()),
3426 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(
3428 generics: self.lower_generics(generics,
3429 ImplTraitContext::Existential(None)),
3430 bounds: self.lower_param_bounds(b,
3431 ImplTraitContext::Existential(None)),
3432 impl_trait_fn: None,
3433 origin: hir::ExistTyOrigin::ExistentialType,
3436 ItemKind::Enum(ref enum_definition, ref generics) => {
3437 hir::ItemKind::Enum(
3439 variants: enum_definition
3442 .map(|x| self.lower_variant(x))
3445 self.lower_generics(generics, ImplTraitContext::disallowed()),
3448 ItemKind::Struct(ref struct_def, ref generics) => {
3449 let struct_def = self.lower_variant_data(struct_def);
3450 hir::ItemKind::Struct(
3452 self.lower_generics(generics, ImplTraitContext::disallowed()),
3455 ItemKind::Union(ref vdata, ref generics) => {
3456 let vdata = self.lower_variant_data(vdata);
3457 hir::ItemKind::Union(
3459 self.lower_generics(generics, ImplTraitContext::disallowed()),
3471 let def_id = self.resolver.definitions().local_def_id(id);
3473 // Lower the "impl header" first. This ordering is important
3474 // for in-band lifetimes! Consider `'a` here:
3476 // impl Foo<'a> for u32 {
3477 // fn method(&'a self) { .. }
3480 // Because we start by lowering the `Foo<'a> for u32`
3481 // part, we will add `'a` to the list of generics on
3482 // the impl. When we then encounter it later in the
3483 // method, it will not be considered an in-band
3484 // lifetime to be added, but rather a reference to a
3486 let lowered_trait_impl_id = self.lower_node_id(id);
3487 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
3490 AnonymousLifetimeMode::CreateParameter,
3492 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
3493 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
3496 if let Some(ref trait_ref) = trait_ref {
3497 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
3498 this.trait_impls.entry(def_id).or_default().push(
3499 lowered_trait_impl_id);
3503 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
3505 (trait_ref, lowered_ty)
3509 let new_impl_items = self.with_in_scope_lifetime_defs(
3510 &ast_generics.params,
3514 .map(|item| this.lower_impl_item_ref(item))
3519 hir::ItemKind::Impl(
3520 self.lower_unsafety(unsafety),
3521 self.lower_impl_polarity(polarity),
3522 self.lower_defaultness(defaultness, true /* [1] */),
3529 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
3530 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
3533 .map(|item| self.lower_trait_item_ref(item))
3535 hir::ItemKind::Trait(
3536 self.lower_is_auto(is_auto),
3537 self.lower_unsafety(unsafety),
3538 self.lower_generics(generics, ImplTraitContext::disallowed()),
3543 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
3544 self.lower_generics(generics, ImplTraitContext::disallowed()),
3545 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3547 ItemKind::MacroDef(..)
3548 | ItemKind::Mac(..) => bug!("`TyMac` should have been expanded by now"),
3551 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
3552 // not cause an assertion failure inside the `lower_defaultness` function.
3560 vis: &mut hir::Visibility,
3562 attrs: &hir::HirVec<Attribute>,
3563 ) -> hir::ItemKind {
3564 debug!("lower_use_tree(tree={:?})", tree);
3565 debug!("lower_use_tree: vis = {:?}", vis);
3567 let path = &tree.prefix;
3568 let segments = prefix
3571 .chain(path.segments.iter())
3576 UseTreeKind::Simple(rename, id1, id2) => {
3577 *ident = tree.ident();
3579 // First, apply the prefix to the path.
3580 let mut path = Path {
3585 // Correctly resolve `self` imports.
3586 if path.segments.len() > 1
3587 && path.segments.last().unwrap().ident.name == kw::SelfLower
3589 let _ = path.segments.pop();
3590 if rename.is_none() {
3591 *ident = path.segments.last().unwrap().ident;
3595 let mut resolutions = self.expect_full_res_from_use(id);
3596 // We want to return *something* from this function, so hold onto the first item
3598 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
3600 // Here, we are looping over namespaces, if they exist for the definition
3601 // being imported. We only handle type and value namespaces because we
3602 // won't be dealing with macros in the rest of the compiler.
3603 // Essentially a single `use` which imports two names is desugared into
3605 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
3607 let mut path = path.clone();
3608 for seg in &mut path.segments {
3609 seg.id = self.sess.next_node_id();
3611 let span = path.span;
3613 self.with_hir_id_owner(new_node_id, |this| {
3614 let new_id = this.lower_node_id(new_node_id);
3615 let res = this.lower_res(res);
3617 this.lower_path_extra(res, &path, ParamMode::Explicit, None);
3618 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3619 let vis = this.rebuild_vis(&vis);
3625 attrs: attrs.into_iter().cloned().collect(),
3635 P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None));
3636 hir::ItemKind::Use(path, hir::UseKind::Single)
3638 UseTreeKind::Glob => {
3639 let path = P(self.lower_path(
3645 ParamMode::Explicit,
3647 hir::ItemKind::Use(path, hir::UseKind::Glob)
3649 UseTreeKind::Nested(ref trees) => {
3650 // Nested imports are desugared into simple imports.
3651 // So, if we start with
3654 // pub(x) use foo::{a, b};
3657 // we will create three items:
3660 // pub(x) use foo::a;
3661 // pub(x) use foo::b;
3662 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3665 // The first two are produced by recursively invoking
3666 // `lower_use_tree` (and indeed there may be things
3667 // like `use foo::{a::{b, c}}` and so forth). They
3668 // wind up being directly added to
3669 // `self.items`. However, the structure of this
3670 // function also requires us to return one item, and
3671 // for that we return the `{}` import (called the
3676 span: prefix.span.to(path.span),
3679 // Add all the nested `PathListItem`s to the HIR.
3680 for &(ref use_tree, id) in trees {
3681 let new_hir_id = self.lower_node_id(id);
3683 let mut prefix = prefix.clone();
3685 // Give the segments new node-ids since they are being cloned.
3686 for seg in &mut prefix.segments {
3687 seg.id = self.sess.next_node_id();
3690 // Each `use` import is an item and thus are owners of the
3691 // names in the path. Up to this point the nested import is
3692 // the current owner, since we want each desugared import to
3693 // own its own names, we have to adjust the owner before
3694 // lowering the rest of the import.
3695 self.with_hir_id_owner(id, |this| {
3696 let mut vis = this.rebuild_vis(&vis);
3697 let mut ident = *ident;
3699 let item = this.lower_use_tree(use_tree,
3710 attrs: attrs.into_iter().cloned().collect(),
3713 span: use_tree.span,
3719 // Subtle and a bit hacky: we lower the privacy level
3720 // of the list stem to "private" most of the time, but
3721 // not for "restricted" paths. The key thing is that
3722 // we don't want it to stay as `pub` (with no caveats)
3723 // because that affects rustdoc and also the lints
3724 // about `pub` items. But we can't *always* make it
3725 // private -- particularly not for restricted paths --
3726 // because it contains node-ids that would then be
3727 // unused, failing the check that HirIds are "densely
3730 hir::VisibilityKind::Public |
3731 hir::VisibilityKind::Crate(_) |
3732 hir::VisibilityKind::Inherited => {
3733 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3735 hir::VisibilityKind::Restricted { .. } => {
3736 // Do nothing here, as described in the comment on the match.
3740 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
3741 let res = self.lower_res(res);
3742 let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None));
3743 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3748 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3749 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3750 /// `NodeId`s. (See, e.g., #56128.)
3751 fn rebuild_use_path(&mut self, path: &hir::Path) -> hir::Path {
3752 debug!("rebuild_use_path(path = {:?})", path);
3753 let segments = path.segments.iter().map(|seg| hir::PathSegment {
3755 hir_id: seg.hir_id.map(|_| self.next_id()),
3758 infer_args: seg.infer_args,
3767 fn rebuild_vis(&mut self, vis: &hir::Visibility) -> hir::Visibility {
3768 let vis_kind = match vis.node {
3769 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3770 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3771 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3772 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3773 hir::VisibilityKind::Restricted {
3774 path: P(self.rebuild_use_path(path)),
3775 hir_id: self.next_id(),
3779 respan(vis.span, vis_kind)
3782 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3783 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
3785 let (generics, node) = match i.node {
3786 TraitItemKind::Const(ref ty, ref default) => (
3787 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3788 hir::TraitItemKind::Const(
3789 self.lower_ty(ty, ImplTraitContext::disallowed()),
3792 .map(|x| self.lower_const_body(x)),
3795 TraitItemKind::Method(ref sig, None) => {
3796 let names = self.lower_fn_args_to_names(&sig.decl);
3797 let (generics, sig) = self.lower_method_sig(
3804 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3806 TraitItemKind::Method(ref sig, Some(ref body)) => {
3807 let body_id = self.lower_fn_body(&sig.decl, |this| {
3808 let body = this.lower_block(body, false);
3809 this.expr_block(body, ThinVec::new())
3811 let (generics, sig) = self.lower_method_sig(
3818 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3820 TraitItemKind::Type(ref bounds, ref default) => {
3821 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
3822 let node = hir::TraitItemKind::Type(
3823 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3826 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3831 TraitItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
3835 hir_id: self.lower_node_id(i.id),
3837 attrs: self.lower_attrs(&i.attrs),
3844 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3845 let (kind, has_default) = match i.node {
3846 TraitItemKind::Const(_, ref default) => {
3847 (hir::AssocItemKind::Const, default.is_some())
3849 TraitItemKind::Type(_, ref default) => {
3850 (hir::AssocItemKind::Type, default.is_some())
3852 TraitItemKind::Method(ref sig, ref default) => (
3853 hir::AssocItemKind::Method {
3854 has_self: sig.decl.has_self(),
3858 TraitItemKind::Macro(..) => unimplemented!(),
3861 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
3864 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3869 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3870 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
3872 let (generics, node) = match i.node {
3873 ImplItemKind::Const(ref ty, ref expr) => (
3874 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3875 hir::ImplItemKind::Const(
3876 self.lower_ty(ty, ImplTraitContext::disallowed()),
3877 self.lower_const_body(expr),
3880 ImplItemKind::Method(ref sig, ref body) => {
3881 self.current_item = Some(i.span);
3882 let body_id = self.lower_maybe_async_body(
3883 &sig.decl, sig.header.asyncness.node, body
3885 let impl_trait_return_allow = !self.is_in_trait_impl;
3886 let (generics, sig) = self.lower_method_sig(
3890 impl_trait_return_allow,
3891 sig.header.asyncness.node.opt_return_id(),
3894 (generics, hir::ImplItemKind::Method(sig, body_id))
3896 ImplItemKind::Type(ref ty) => (
3897 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3898 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3900 ImplItemKind::Existential(ref bounds) => (
3901 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3902 hir::ImplItemKind::Existential(
3903 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3906 ImplItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
3910 hir_id: self.lower_node_id(i.id),
3912 attrs: self.lower_attrs(&i.attrs),
3914 vis: self.lower_visibility(&i.vis, None),
3915 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3920 // [1] since `default impl` is not yet implemented, this is always true in impls
3923 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3925 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
3928 vis: self.lower_visibility(&i.vis, Some(i.id)),
3929 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3930 kind: match i.node {
3931 ImplItemKind::Const(..) => hir::AssocItemKind::Const,
3932 ImplItemKind::Type(..) => hir::AssocItemKind::Type,
3933 ImplItemKind::Existential(..) => hir::AssocItemKind::Existential,
3934 ImplItemKind::Method(ref sig, _) => hir::AssocItemKind::Method {
3935 has_self: sig.decl.has_self(),
3937 ImplItemKind::Macro(..) => unimplemented!(),
3941 // [1] since `default impl` is not yet implemented, this is always true in impls
3944 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3947 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3951 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3952 let node_ids = match i.node {
3953 ItemKind::Use(ref use_tree) => {
3954 let mut vec = smallvec![i.id];
3955 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3958 ItemKind::MacroDef(..) => SmallVec::new(),
3960 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
3961 ItemKind::Static(ref ty, ..) => {
3962 let mut ids = smallvec![i.id];
3963 if self.sess.features_untracked().impl_trait_in_bindings {
3964 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3965 visitor.visit_ty(ty);
3969 ItemKind::Const(ref ty, ..) => {
3970 let mut ids = smallvec![i.id];
3971 if self.sess.features_untracked().impl_trait_in_bindings {
3972 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3973 visitor.visit_ty(ty);
3977 _ => smallvec![i.id],
3980 node_ids.into_iter().map(|node_id| hir::ItemId {
3981 id: self.allocate_hir_id_counter(node_id)
3985 fn lower_item_id_use_tree(&mut self,
3988 vec: &mut SmallVec<[NodeId; 1]>)
3991 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3993 self.lower_item_id_use_tree(nested, id, vec);
3995 UseTreeKind::Glob => {}
3996 UseTreeKind::Simple(_, id1, id2) => {
3997 for (_, &id) in self.expect_full_res_from_use(base_id)
3999 .zip([id1, id2].iter())
4007 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
4008 let mut ident = i.ident;
4009 let mut vis = self.lower_visibility(&i.vis, None);
4010 let attrs = self.lower_attrs(&i.attrs);
4011 if let ItemKind::MacroDef(ref def) = i.node {
4012 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) ||
4013 attr::contains_name(&i.attrs, sym::rustc_doc_only_macro) {
4014 let body = self.lower_token_stream(def.stream());
4015 let hir_id = self.lower_node_id(i.id);
4016 self.exported_macros.push(hir::MacroDef {
4029 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
4032 hir_id: self.lower_node_id(i.id),
4041 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
4042 let def_id = self.resolver.definitions().local_def_id(i.id);
4044 hir_id: self.lower_node_id(i.id),
4046 attrs: self.lower_attrs(&i.attrs),
4047 node: match i.node {
4048 ForeignItemKind::Fn(ref fdec, ref generics) => {
4049 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
4052 AnonymousLifetimeMode::PassThrough,
4055 // Disallow impl Trait in foreign items
4056 this.lower_fn_decl(fdec, None, false, None),
4057 this.lower_fn_args_to_names(fdec),
4062 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
4064 ForeignItemKind::Static(ref t, m) => {
4065 hir::ForeignItemKind::Static(
4066 self.lower_ty(t, ImplTraitContext::disallowed()), self.lower_mutability(m))
4068 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
4069 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
4071 vis: self.lower_visibility(&i.vis, None),
4076 fn lower_method_sig(
4078 generics: &Generics,
4081 impl_trait_return_allow: bool,
4082 is_async: Option<NodeId>,
4083 ) -> (hir::Generics, hir::MethodSig) {
4084 let header = self.lower_fn_header(sig.header);
4085 let (generics, decl) = self.add_in_band_defs(
4088 AnonymousLifetimeMode::PassThrough,
4089 |this, idty| this.lower_fn_decl(
4091 Some((fn_def_id, idty)),
4092 impl_trait_return_allow,
4096 (generics, hir::MethodSig { header, decl })
4099 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
4101 IsAuto::Yes => hir::IsAuto::Yes,
4102 IsAuto::No => hir::IsAuto::No,
4106 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
4108 unsafety: self.lower_unsafety(h.unsafety),
4109 asyncness: self.lower_asyncness(h.asyncness.node),
4110 constness: self.lower_constness(h.constness),
4115 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
4117 Unsafety::Unsafe => hir::Unsafety::Unsafe,
4118 Unsafety::Normal => hir::Unsafety::Normal,
4122 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
4124 Constness::Const => hir::Constness::Const,
4125 Constness::NotConst => hir::Constness::NotConst,
4129 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
4131 IsAsync::Async { .. } => hir::IsAsync::Async,
4132 IsAsync::NotAsync => hir::IsAsync::NotAsync,
4136 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
4138 UnOp::Deref => hir::UnDeref,
4139 UnOp::Not => hir::UnNot,
4140 UnOp::Neg => hir::UnNeg,
4144 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
4146 node: match b.node {
4147 BinOpKind::Add => hir::BinOpKind::Add,
4148 BinOpKind::Sub => hir::BinOpKind::Sub,
4149 BinOpKind::Mul => hir::BinOpKind::Mul,
4150 BinOpKind::Div => hir::BinOpKind::Div,
4151 BinOpKind::Rem => hir::BinOpKind::Rem,
4152 BinOpKind::And => hir::BinOpKind::And,
4153 BinOpKind::Or => hir::BinOpKind::Or,
4154 BinOpKind::BitXor => hir::BinOpKind::BitXor,
4155 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
4156 BinOpKind::BitOr => hir::BinOpKind::BitOr,
4157 BinOpKind::Shl => hir::BinOpKind::Shl,
4158 BinOpKind::Shr => hir::BinOpKind::Shr,
4159 BinOpKind::Eq => hir::BinOpKind::Eq,
4160 BinOpKind::Lt => hir::BinOpKind::Lt,
4161 BinOpKind::Le => hir::BinOpKind::Le,
4162 BinOpKind::Ne => hir::BinOpKind::Ne,
4163 BinOpKind::Ge => hir::BinOpKind::Ge,
4164 BinOpKind::Gt => hir::BinOpKind::Gt,
4170 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
4171 let node = match p.node {
4172 PatKind::Wild => hir::PatKind::Wild,
4173 PatKind::Ident(ref binding_mode, ident, ref sub) => {
4174 match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
4175 // `None` can occur in body-less function signatures
4176 res @ None | res @ Some(Res::Local(_)) => {
4177 let canonical_id = match res {
4178 Some(Res::Local(id)) => id,
4182 hir::PatKind::Binding(
4183 self.lower_binding_mode(binding_mode),
4184 self.lower_node_id(canonical_id),
4186 sub.as_ref().map(|x| self.lower_pat(x)),
4189 Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
4193 res: self.lower_res(res),
4194 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4199 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
4200 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
4201 let qpath = self.lower_qpath(
4205 ParamMode::Optional,
4206 ImplTraitContext::disallowed(),
4208 hir::PatKind::TupleStruct(
4210 pats.iter().map(|x| self.lower_pat(x)).collect(),
4214 PatKind::Path(ref qself, ref path) => {
4215 let qpath = self.lower_qpath(
4219 ParamMode::Optional,
4220 ImplTraitContext::disallowed(),
4222 hir::PatKind::Path(qpath)
4224 PatKind::Struct(ref path, ref fields, etc) => {
4225 let qpath = self.lower_qpath(
4229 ParamMode::Optional,
4230 ImplTraitContext::disallowed(),
4238 node: hir::FieldPat {
4239 hir_id: self.next_id(),
4240 ident: f.node.ident,
4241 pat: self.lower_pat(&f.node.pat),
4242 is_shorthand: f.node.is_shorthand,
4247 hir::PatKind::Struct(qpath, fs, etc)
4249 PatKind::Tuple(ref elts, ddpos) => {
4250 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
4252 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
4253 PatKind::Ref(ref inner, mutbl) => {
4254 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
4256 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
4257 P(self.lower_expr(e1)),
4258 P(self.lower_expr(e2)),
4259 self.lower_range_end(end),
4261 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
4262 before.iter().map(|x| self.lower_pat(x)).collect(),
4263 slice.as_ref().map(|x| self.lower_pat(x)),
4264 after.iter().map(|x| self.lower_pat(x)).collect(),
4266 PatKind::Paren(ref inner) => return self.lower_pat(inner),
4267 PatKind::Mac(_) => panic!("Shouldn't exist here"),
4271 hir_id: self.lower_node_id(p.id),
4277 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
4279 RangeEnd::Included(_) => hir::RangeEnd::Included,
4280 RangeEnd::Excluded => hir::RangeEnd::Excluded,
4284 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
4285 self.with_new_scopes(|this| {
4287 hir_id: this.lower_node_id(c.id),
4288 body: this.lower_const_body(&c.value),
4293 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
4294 let kind = match e.node {
4295 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
4296 ExprKind::Array(ref exprs) => {
4297 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
4299 ExprKind::Repeat(ref expr, ref count) => {
4300 let expr = P(self.lower_expr(expr));
4301 let count = self.lower_anon_const(count);
4302 hir::ExprKind::Repeat(expr, count)
4304 ExprKind::Tup(ref elts) => {
4305 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
4307 ExprKind::Call(ref f, ref args) => {
4308 let f = P(self.lower_expr(f));
4309 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
4311 ExprKind::MethodCall(ref seg, ref args) => {
4312 let hir_seg = P(self.lower_path_segment(
4315 ParamMode::Optional,
4317 ParenthesizedGenericArgs::Err,
4318 ImplTraitContext::disallowed(),
4321 let args = args.iter().map(|x| self.lower_expr(x)).collect();
4322 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
4324 ExprKind::Binary(binop, ref lhs, ref rhs) => {
4325 let binop = self.lower_binop(binop);
4326 let lhs = P(self.lower_expr(lhs));
4327 let rhs = P(self.lower_expr(rhs));
4328 hir::ExprKind::Binary(binop, lhs, rhs)
4330 ExprKind::Unary(op, ref ohs) => {
4331 let op = self.lower_unop(op);
4332 let ohs = P(self.lower_expr(ohs));
4333 hir::ExprKind::Unary(op, ohs)
4335 ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.node.clone())),
4336 ExprKind::Cast(ref expr, ref ty) => {
4337 let expr = P(self.lower_expr(expr));
4338 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4340 ExprKind::Type(ref expr, ref ty) => {
4341 let expr = P(self.lower_expr(expr));
4342 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4344 ExprKind::AddrOf(m, ref ohs) => {
4345 let m = self.lower_mutability(m);
4346 let ohs = P(self.lower_expr(ohs));
4347 hir::ExprKind::AddrOf(m, ohs)
4349 ExprKind::Let(ref pats, ref scrutinee) => {
4350 // If we got here, the `let` expression is not allowed.
4352 .struct_span_err(e.span, "`let` expressions are not supported here")
4353 .note("only supported directly in conditions of `if`- and `while`-expressions")
4354 .note("as well as when nested within `&&` and parenthesis in those conditions")
4357 // For better recovery, we emit:
4359 // match scrutinee { pats => true, _ => false }
4361 // While this doesn't fully match the user's intent, it has key advantages:
4362 // 1. We can avoid using `abort_if_errors`.
4363 // 2. We can typeck both `pats` and `scrutinee`.
4364 // 3. `pats` is allowed to be refutable.
4365 // 4. The return type of the block is `bool` which seems like what the user wanted.
4366 let scrutinee = self.lower_expr(scrutinee);
4368 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4369 let expr = self.expr_bool(e.span, true);
4370 self.arm(pats, P(expr))
4373 let pats = hir_vec![self.pat_wild(e.span)];
4374 let expr = self.expr_bool(e.span, false);
4375 self.arm(pats, P(expr))
4377 hir::ExprKind::Match(
4379 vec![then_arm, else_arm].into(),
4380 hir::MatchSource::Normal,
4383 // FIXME(#53667): handle lowering of && and parens.
4384 ExprKind::If(ref cond, ref then, ref else_opt) => {
4385 // `_ => else_block` where `else_block` is `{}` if there's `None`:
4386 let else_pat = self.pat_wild(e.span);
4387 let (else_expr, contains_else_clause) = match else_opt {
4388 None => (self.expr_block_empty(e.span), false),
4389 Some(els) => (self.lower_expr(els), true),
4391 let else_arm = self.arm(hir_vec![else_pat], P(else_expr));
4393 // Handle then + scrutinee:
4394 let then_blk = self.lower_block(then, false);
4395 let then_expr = self.expr_block(then_blk, ThinVec::new());
4396 let (then_pats, scrutinee, desugar) = match cond.node {
4397 // `<pat> => <then>`
4398 ExprKind::Let(ref pats, ref scrutinee) => {
4399 let scrutinee = self.lower_expr(scrutinee);
4400 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4401 let desugar = hir::MatchSource::IfLetDesugar { contains_else_clause };
4402 (pats, scrutinee, desugar)
4407 let cond = self.lower_expr(cond);
4408 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
4409 // to preserve drop semantics since `if cond { ... }`
4410 // don't let temporaries live outside of `cond`.
4411 let span_block = self.mark_span_with_reason(IfTemporary, cond.span, None);
4412 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
4413 // to preserve drop semantics since `if cond { ... }` does not
4414 // let temporaries live outside of `cond`.
4415 let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new());
4417 let desugar = hir::MatchSource::IfDesugar { contains_else_clause };
4418 let pats = hir_vec![self.pat_bool(e.span, true)];
4419 (pats, cond, desugar)
4422 let then_arm = self.arm(then_pats, P(then_expr));
4424 hir::ExprKind::Match(P(scrutinee), vec![then_arm, else_arm].into(), desugar)
4426 // FIXME(#53667): handle lowering of && and parens.
4427 ExprKind::While(ref cond, ref body, opt_label) => {
4428 // Desugar `ExprWhileLet`
4429 // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4430 if let ExprKind::Let(ref pats, ref sub_expr) = cond.node {
4433 // [opt_ident]: loop {
4434 // match <sub_expr> {
4440 // Note that the block AND the condition are evaluated in the loop scope.
4441 // This is done to allow `break` from inside the condition of the loop.
4442 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4444 this.lower_block(body, false),
4445 this.expr_break(e.span, ThinVec::new()),
4446 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4450 // `<pat> => <body>`
4452 let body_expr = P(self.expr_block(body, ThinVec::new()));
4453 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4454 self.arm(pats, body_expr)
4459 let pat_under = self.pat_wild(e.span);
4460 self.arm(hir_vec![pat_under], break_expr)
4463 // `match <sub_expr> { ... }`
4464 let arms = hir_vec![pat_arm, break_arm];
4465 let match_expr = self.expr(
4467 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4471 // `[opt_ident]: loop { ... }`
4472 let loop_block = P(self.block_expr(P(match_expr)));
4473 let loop_expr = hir::ExprKind::Loop(
4475 self.lower_label(opt_label),
4476 hir::LoopSource::WhileLet,
4478 // Add attributes to the outer returned expr node.
4481 self.with_loop_scope(e.id, |this| {
4482 hir::ExprKind::While(
4483 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
4484 this.lower_block(body, false),
4485 this.lower_label(opt_label),
4490 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4491 hir::ExprKind::Loop(
4492 this.lower_block(body, false),
4493 this.lower_label(opt_label),
4494 hir::LoopSource::Loop,
4497 ExprKind::TryBlock(ref body) => {
4498 self.with_catch_scope(body.id, |this| {
4499 let unstable_span = this.mark_span_with_reason(
4500 CompilerDesugaringKind::TryBlock,
4502 this.allow_try_trait.clone(),
4504 let mut block = this.lower_block(body, true).into_inner();
4505 let tail = block.expr.take().map_or_else(
4507 let span = this.sess.source_map().end_point(unstable_span);
4510 node: hir::ExprKind::Tup(hir_vec![]),
4511 attrs: ThinVec::new(),
4512 hir_id: this.next_id(),
4515 |x: P<hir::Expr>| x.into_inner(),
4517 block.expr = Some(this.wrap_in_try_constructor(
4518 sym::from_ok, tail, unstable_span));
4519 hir::ExprKind::Block(P(block), None)
4522 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
4523 P(self.lower_expr(expr)),
4524 arms.iter().map(|x| self.lower_arm(x)).collect(),
4525 hir::MatchSource::Normal,
4527 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
4528 self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| {
4529 this.with_new_scopes(|this| {
4530 let block = this.lower_block(block, false);
4531 this.expr_block(block, ThinVec::new())
4535 ExprKind::Await(_origin, ref expr) => self.lower_await(e.span, expr),
4537 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
4539 if let IsAsync::Async { closure_id, .. } = asyncness {
4540 let outer_decl = FnDecl {
4541 inputs: decl.inputs.clone(),
4542 output: FunctionRetTy::Default(fn_decl_span),
4545 // We need to lower the declaration outside the new scope, because we
4546 // have to conserve the state of being inside a loop condition for the
4547 // closure argument types.
4548 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
4550 self.with_new_scopes(|this| {
4551 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
4552 if capture_clause == CaptureBy::Ref &&
4553 !decl.inputs.is_empty()
4559 "`async` non-`move` closures with arguments \
4560 are not currently supported",
4562 .help("consider using `let` statements to manually capture \
4563 variables by reference before entering an \
4564 `async move` closure")
4568 // Transform `async |x: u8| -> X { ... }` into
4569 // `|x: u8| future_from_generator(|| -> X { ... })`.
4570 let body_id = this.lower_fn_body(&outer_decl, |this| {
4571 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
4574 let async_body = this.make_async_expr(
4575 capture_clause, closure_id, async_ret_ty, body.span,
4577 this.with_new_scopes(|this| this.lower_expr(body))
4579 this.expr(fn_decl_span, async_body, ThinVec::new())
4581 hir::ExprKind::Closure(
4582 this.lower_capture_clause(capture_clause),
4590 // Lower outside new scope to preserve `is_in_loop_condition`.
4591 let fn_decl = self.lower_fn_decl(decl, None, false, None);
4593 self.with_new_scopes(|this| {
4594 this.current_item = Some(fn_decl_span);
4595 let mut generator_kind = None;
4596 let body_id = this.lower_fn_body(decl, |this| {
4597 let e = this.lower_expr(body);
4598 generator_kind = this.generator_kind;
4601 let generator_option = this.generator_movability_for_fn(
4607 hir::ExprKind::Closure(
4608 this.lower_capture_clause(capture_clause),
4617 ExprKind::Block(ref blk, opt_label) => {
4618 hir::ExprKind::Block(self.lower_block(blk,
4619 opt_label.is_some()),
4620 self.lower_label(opt_label))
4622 ExprKind::Assign(ref el, ref er) => {
4623 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
4625 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
4626 self.lower_binop(op),
4627 P(self.lower_expr(el)),
4628 P(self.lower_expr(er)),
4630 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
4631 ExprKind::Index(ref el, ref er) => {
4632 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
4634 // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
4635 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
4636 let id = self.next_id();
4637 let e1 = self.lower_expr(e1);
4638 let e2 = self.lower_expr(e2);
4639 self.expr_call_std_assoc_fn(
4642 &[sym::ops, sym::RangeInclusive],
4647 ExprKind::Range(ref e1, ref e2, lims) => {
4648 use syntax::ast::RangeLimits::*;
4650 let path = match (e1, e2, lims) {
4651 (&None, &None, HalfOpen) => sym::RangeFull,
4652 (&Some(..), &None, HalfOpen) => sym::RangeFrom,
4653 (&None, &Some(..), HalfOpen) => sym::RangeTo,
4654 (&Some(..), &Some(..), HalfOpen) => sym::Range,
4655 (&None, &Some(..), Closed) => sym::RangeToInclusive,
4656 (&Some(..), &Some(..), Closed) => unreachable!(),
4657 (_, &None, Closed) => self.diagnostic()
4658 .span_fatal(e.span, "inclusive range with no end")
4662 let fields = e1.iter()
4663 .map(|e| ("start", e))
4664 .chain(e2.iter().map(|e| ("end", e)))
4666 let expr = P(self.lower_expr(&e));
4667 let ident = Ident::new(Symbol::intern(s), e.span);
4668 self.field(ident, expr, e.span)
4670 .collect::<P<[hir::Field]>>();
4672 let is_unit = fields.is_empty();
4673 let struct_path = [sym::ops, path];
4674 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4675 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4678 hir_id: self.lower_node_id(e.id),
4680 hir::ExprKind::Path(struct_path)
4682 hir::ExprKind::Struct(P(struct_path), fields, None)
4685 attrs: e.attrs.clone(),
4688 ExprKind::Path(ref qself, ref path) => {
4689 let qpath = self.lower_qpath(
4693 ParamMode::Optional,
4694 ImplTraitContext::disallowed(),
4696 hir::ExprKind::Path(qpath)
4698 ExprKind::Break(opt_label, ref opt_expr) => {
4699 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4702 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4705 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4707 hir::ExprKind::Break(
4709 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4712 ExprKind::Continue(opt_label) => {
4713 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4716 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4719 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4722 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4723 ExprKind::InlineAsm(ref asm) => {
4724 let hir_asm = hir::InlineAsm {
4725 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4726 outputs: asm.outputs
4728 .map(|out| hir::InlineAsmOutput {
4729 constraint: out.constraint.clone(),
4731 is_indirect: out.is_indirect,
4732 span: out.expr.span,
4735 asm: asm.asm.clone(),
4736 asm_str_style: asm.asm_str_style,
4737 clobbers: asm.clobbers.clone().into(),
4738 volatile: asm.volatile,
4739 alignstack: asm.alignstack,
4740 dialect: asm.dialect,
4743 let outputs = asm.outputs
4745 .map(|out| self.lower_expr(&out.expr))
4747 let inputs = asm.inputs
4749 .map(|&(_, ref input)| self.lower_expr(input))
4751 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4753 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4758 ParamMode::Optional,
4759 ImplTraitContext::disallowed(),
4761 fields.iter().map(|x| self.lower_field(x)).collect(),
4762 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4764 ExprKind::Paren(ref ex) => {
4765 let mut ex = self.lower_expr(ex);
4766 // Include parens in span, but only if it is a super-span.
4767 if e.span.contains(ex.span) {
4770 // Merge attributes into the inner expression.
4771 let mut attrs = e.attrs.clone();
4772 attrs.extend::<Vec<_>>(ex.attrs.into());
4777 ExprKind::Yield(ref opt_expr) => {
4778 match self.generator_kind {
4779 Some(hir::GeneratorKind::Gen) => {},
4780 Some(hir::GeneratorKind::Async) => {
4785 "`async` generators are not yet supported",
4787 self.sess.abort_if_errors();
4790 self.generator_kind = Some(hir::GeneratorKind::Gen);
4795 .map(|x| self.lower_expr(x))
4796 .unwrap_or_else(|| self.expr_unit(e.span));
4797 hir::ExprKind::Yield(P(expr), hir::YieldSource::Yield)
4800 ExprKind::Err => hir::ExprKind::Err,
4802 // Desugar `ExprForLoop`
4803 // from: `[opt_ident]: for <pat> in <head> <body>`
4804 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4808 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4810 // [opt_ident]: loop {
4812 // match ::std::iter::Iterator::next(&mut iter) {
4813 // ::std::option::Option::Some(val) => __next = val,
4814 // ::std::option::Option::None => break
4816 // let <pat> = __next;
4817 // StmtKind::Expr(<body>);
4825 let mut head = self.lower_expr(head);
4826 let head_sp = head.span;
4827 let desugared_span = self.mark_span_with_reason(
4828 CompilerDesugaringKind::ForLoop,
4832 head.span = desugared_span;
4834 let iter = Ident::with_empty_ctxt(sym::iter);
4836 let next_ident = Ident::with_empty_ctxt(sym::__next);
4837 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
4840 hir::BindingAnnotation::Mutable,
4843 // `::std::option::Option::Some(val) => __next = val`
4845 let val_ident = Ident::with_empty_ctxt(sym::val);
4846 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
4847 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
4848 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
4849 let assign = P(self.expr(
4851 hir::ExprKind::Assign(next_expr, val_expr),
4854 let some_pat = self.pat_some(pat.span, val_pat);
4855 self.arm(hir_vec![some_pat], assign)
4858 // `::std::option::Option::None => break`
4861 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4862 let pat = self.pat_none(e.span);
4863 self.arm(hir_vec![pat], break_expr)
4867 let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(
4870 hir::BindingAnnotation::Mutable
4873 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4875 let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
4876 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4877 let next_path = &[sym::iter, sym::Iterator, sym::next];
4878 let next_expr = P(self.expr_call_std_path(
4881 hir_vec![ref_mut_iter],
4883 let arms = hir_vec![pat_arm, break_arm];
4887 hir::ExprKind::Match(
4890 hir::MatchSource::ForLoopDesugar
4895 let match_stmt = self.stmt(head_sp, hir::StmtKind::Expr(match_expr));
4897 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid));
4900 let next_let = self.stmt_let_pat(
4904 hir::LocalSource::ForLoopDesugar,
4907 // `let <pat> = __next`
4908 let pat = self.lower_pat(pat);
4909 let pat_let = self.stmt_let_pat(
4913 hir::LocalSource::ForLoopDesugar,
4916 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4917 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4918 let body_stmt = self.stmt(body.span, hir::StmtKind::Expr(body_expr));
4920 let loop_block = P(self.block_all(
4922 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4926 // `[opt_ident]: loop { ... }`
4927 let loop_expr = hir::ExprKind::Loop(
4929 self.lower_label(opt_label),
4930 hir::LoopSource::ForLoop,
4932 let loop_expr = P(hir::Expr {
4933 hir_id: self.lower_node_id(e.id),
4936 attrs: ThinVec::new(),
4939 // `mut iter => { ... }`
4940 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4942 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4943 let into_iter_expr = {
4944 let into_iter_path =
4945 &[sym::iter, sym::IntoIterator, sym::into_iter];
4946 P(self.expr_call_std_path(
4953 let match_expr = P(self.expr_match(
4957 hir::MatchSource::ForLoopDesugar,
4960 // This is effectively `{ let _result = ...; _result }`.
4961 // The construct was introduced in #21984.
4962 // FIXME(60253): Is this still necessary?
4963 // Also, add the attributes to the outer returned expr node.
4964 return self.expr_drop_temps(head_sp, match_expr, e.attrs.clone())
4967 // Desugar `ExprKind::Try`
4969 ExprKind::Try(ref sub_expr) => {
4972 // match Try::into_result(<expr>) {
4973 // Ok(val) => #[allow(unreachable_code)] val,
4974 // Err(err) => #[allow(unreachable_code)]
4975 // // If there is an enclosing `catch {...}`
4976 // break 'catch_target Try::from_error(From::from(err)),
4978 // return Try::from_error(From::from(err)),
4981 let unstable_span = self.mark_span_with_reason(
4982 CompilerDesugaringKind::QuestionMark,
4984 self.allow_try_trait.clone(),
4986 let try_span = self.sess.source_map().end_point(e.span);
4987 let try_span = self.mark_span_with_reason(
4988 CompilerDesugaringKind::QuestionMark,
4990 self.allow_try_trait.clone(),
4993 // `Try::into_result(<expr>)`
4996 let sub_expr = self.lower_expr(sub_expr);
4998 let path = &[sym::ops, sym::Try, sym::into_result];
4999 P(self.expr_call_std_path(
5006 // `#[allow(unreachable_code)]`
5008 // `allow(unreachable_code)`
5010 let allow_ident = Ident::with_empty_ctxt(sym::allow).with_span_pos(e.span);
5011 let uc_ident = Ident::with_empty_ctxt(sym::unreachable_code)
5012 .with_span_pos(e.span);
5013 let uc_nested = attr::mk_nested_word_item(uc_ident);
5014 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
5016 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
5018 let attrs = vec![attr];
5020 // `Ok(val) => #[allow(unreachable_code)] val,`
5022 let val_ident = Ident::with_empty_ctxt(sym::val);
5023 let (val_pat, val_pat_nid) = self.pat_ident(e.span, val_ident);
5024 let val_expr = P(self.expr_ident_with_attrs(
5028 ThinVec::from(attrs.clone()),
5030 let ok_pat = self.pat_ok(e.span, val_pat);
5032 self.arm(hir_vec![ok_pat], val_expr)
5035 // `Err(err) => #[allow(unreachable_code)]
5036 // return Try::from_error(From::from(err)),`
5038 let err_ident = Ident::with_empty_ctxt(sym::err);
5039 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
5041 let from_path = &[sym::convert, sym::From, sym::from];
5042 let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
5043 self.expr_call_std_path(try_span, from_path, hir_vec![err_expr])
5046 self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span);
5047 let thin_attrs = ThinVec::from(attrs);
5048 let catch_scope = self.catch_scopes.last().map(|x| *x);
5049 let ret_expr = if let Some(catch_node) = catch_scope {
5050 let target_id = Ok(self.lower_node_id(catch_node));
5053 hir::ExprKind::Break(
5058 Some(from_err_expr),
5063 P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
5066 let err_pat = self.pat_err(try_span, err_local);
5067 self.arm(hir_vec![err_pat], ret_expr)
5070 hir::ExprKind::Match(
5072 hir_vec![err_arm, ok_arm],
5073 hir::MatchSource::TryDesugar,
5077 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
5081 hir_id: self.lower_node_id(e.id),
5084 attrs: e.attrs.clone(),
5088 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
5089 smallvec![match s.node {
5090 StmtKind::Local(ref l) => {
5091 let (l, item_ids) = self.lower_local(l);
5092 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
5095 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
5096 self.stmt(s.span, hir::StmtKind::Item(item_id))
5101 hir_id: self.lower_node_id(s.id),
5102 node: hir::StmtKind::Local(P(l)),
5108 StmtKind::Item(ref it) => {
5109 // Can only use the ID once.
5110 let mut id = Some(s.id);
5111 return self.lower_item_id(it)
5114 let hir_id = id.take()
5115 .map(|id| self.lower_node_id(id))
5116 .unwrap_or_else(|| self.next_id());
5120 node: hir::StmtKind::Item(item_id),
5126 StmtKind::Expr(ref e) => {
5128 hir_id: self.lower_node_id(s.id),
5129 node: hir::StmtKind::Expr(P(self.lower_expr(e))),
5133 StmtKind::Semi(ref e) => {
5135 hir_id: self.lower_node_id(s.id),
5136 node: hir::StmtKind::Semi(P(self.lower_expr(e))),
5140 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
5144 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
5146 CaptureBy::Value => hir::CaptureByValue,
5147 CaptureBy::Ref => hir::CaptureByRef,
5151 /// If an `explicit_owner` is given, this method allocates the `HirId` in
5152 /// the address space of that item instead of the item currently being
5153 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
5154 /// lower a `Visibility` value although we haven't lowered the owning
5155 /// `ImplItem` in question yet.
5156 fn lower_visibility(
5159 explicit_owner: Option<NodeId>,
5160 ) -> hir::Visibility {
5161 let node = match v.node {
5162 VisibilityKind::Public => hir::VisibilityKind::Public,
5163 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
5164 VisibilityKind::Restricted { ref path, id } => {
5165 debug!("lower_visibility: restricted path id = {:?}", id);
5166 let lowered_id = if let Some(owner) = explicit_owner {
5167 self.lower_node_id_with_owner(id, owner)
5169 self.lower_node_id(id)
5171 let res = self.expect_full_res(id);
5172 let res = self.lower_res(res);
5173 hir::VisibilityKind::Restricted {
5174 path: P(self.lower_path_extra(
5177 ParamMode::Explicit,
5183 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
5185 respan(v.span, node)
5188 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
5190 Defaultness::Default => hir::Defaultness::Default {
5191 has_value: has_value,
5193 Defaultness::Final => {
5195 hir::Defaultness::Final
5200 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
5202 BlockCheckMode::Default => hir::DefaultBlock,
5203 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
5207 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
5209 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
5210 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
5211 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
5212 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
5216 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
5218 CompilerGenerated => hir::CompilerGenerated,
5219 UserProvided => hir::UserProvided,
5223 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
5225 ImplPolarity::Positive => hir::ImplPolarity::Positive,
5226 ImplPolarity::Negative => hir::ImplPolarity::Negative,
5230 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
5232 TraitBoundModifier::None => hir::TraitBoundModifier::None,
5233 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
5237 // Helper methods for building HIR.
5239 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
5241 hir_id: self.next_id(),
5250 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
5252 hir_id: self.next_id(),
5256 is_shorthand: false,
5260 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
5261 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
5262 P(self.expr(span, expr_break, attrs))
5269 args: hir::HirVec<hir::Expr>,
5271 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
5274 // Note: associated functions must use `expr_call_std_path`.
5275 fn expr_call_std_path(
5278 path_components: &[Symbol],
5279 args: hir::HirVec<hir::Expr>,
5281 let path = P(self.expr_std_path(span, path_components, None, ThinVec::new()));
5282 self.expr_call(span, path, args)
5285 // Create an expression calling an associated function of an std type.
5287 // Associated functions cannot be resolved through the normal `std_path` function,
5288 // as they are resolved differently and so cannot use `expr_call_std_path`.
5290 // This function accepts the path component (`ty_path_components`) separately from
5291 // the name of the associated function (`assoc_fn_name`) in order to facilitate
5292 // separate resolution of the type and creation of a path referring to its associated
5294 fn expr_call_std_assoc_fn(
5296 ty_path_id: hir::HirId,
5298 ty_path_components: &[Symbol],
5299 assoc_fn_name: &str,
5300 args: hir::HirVec<hir::Expr>,
5301 ) -> hir::ExprKind {
5302 let ty_path = P(self.std_path(span, ty_path_components, None, false));
5303 let ty = P(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path)));
5304 let fn_seg = P(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name)));
5305 let fn_path = hir::QPath::TypeRelative(ty, fn_seg);
5306 let fn_expr = P(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
5307 hir::ExprKind::Call(fn_expr, args)
5310 fn expr_ident(&mut self, span: Span, ident: Ident, binding: hir::HirId) -> hir::Expr {
5311 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
5314 fn expr_ident_with_attrs(
5318 binding: hir::HirId,
5319 attrs: ThinVec<Attribute>,
5321 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
5325 res: Res::Local(binding),
5326 segments: hir_vec![hir::PathSegment::from_ident(ident)],
5330 self.expr(span, expr_path, attrs)
5333 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
5334 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
5340 components: &[Symbol],
5341 params: Option<P<hir::GenericArgs>>,
5342 attrs: ThinVec<Attribute>,
5344 let path = self.std_path(span, components, params, true);
5347 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
5352 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
5354 /// In terms of drop order, it has the same effect as wrapping `expr` in
5355 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
5357 /// The drop order can be important in e.g. `if expr { .. }`.
5362 attrs: ThinVec<Attribute>
5364 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
5371 arms: hir::HirVec<hir::Arm>,
5372 source: hir::MatchSource,
5374 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
5377 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
5378 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
5381 fn expr_unit(&mut self, sp: Span) -> hir::Expr {
5382 self.expr_tuple(sp, hir_vec![])
5385 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> hir::Expr {
5386 self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new())
5389 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
5391 hir_id: self.next_id(),
5398 fn stmt(&mut self, span: Span, node: hir::StmtKind) -> hir::Stmt {
5399 hir::Stmt { span, node, hir_id: self.next_id() }
5405 init: Option<P<hir::Expr>>,
5407 source: hir::LocalSource,
5409 let local = hir::Local {
5413 hir_id: self.next_id(),
5416 attrs: ThinVec::new()
5418 self.stmt(span, hir::StmtKind::Local(P(local)))
5421 fn expr_block_empty(&mut self, span: Span) -> hir::Expr {
5422 let blk = self.block_all(span, hir_vec![], None);
5423 self.expr_block(P(blk), ThinVec::new())
5426 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
5427 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
5433 stmts: hir::HirVec<hir::Stmt>,
5434 expr: Option<P<hir::Expr>>,
5439 hir_id: self.next_id(),
5440 rules: hir::DefaultBlock,
5442 targeted_by_break: false,
5446 fn expr_unsafe(&mut self, expr: P<hir::Expr>) -> hir::Expr {
5447 let hir_id = self.next_id();
5448 let span = expr.span;
5451 hir::ExprKind::Block(P(hir::Block {
5455 rules: hir::UnsafeBlock(hir::CompilerGenerated),
5457 targeted_by_break: false,
5463 /// Constructs a `true` or `false` literal expression.
5464 fn expr_bool(&mut self, span: Span, val: bool) -> hir::Expr {
5465 let lit = Spanned { span, node: LitKind::Bool(val) };
5466 self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new())
5469 /// Constructs a `true` or `false` literal pattern.
5470 fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
5471 let expr = self.expr_bool(span, val);
5472 self.pat(span, hir::PatKind::Lit(P(expr)))
5475 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5476 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
5479 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5480 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
5483 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5484 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
5487 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
5488 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
5494 components: &[Symbol],
5495 subpats: hir::HirVec<P<hir::Pat>>,
5497 let path = self.std_path(span, components, None, true);
5498 let qpath = hir::QPath::Resolved(None, P(path));
5499 let pt = if subpats.is_empty() {
5500 hir::PatKind::Path(qpath)
5502 hir::PatKind::TupleStruct(qpath, subpats, None)
5507 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
5508 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
5511 fn pat_ident_binding_mode(
5515 bm: hir::BindingAnnotation,
5516 ) -> (P<hir::Pat>, hir::HirId) {
5517 let hir_id = self.next_id();
5522 node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
5529 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
5530 self.pat(span, hir::PatKind::Wild)
5533 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
5535 hir_id: self.next_id(),
5541 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
5542 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
5543 /// The path is also resolved according to `is_value`.
5547 components: &[Symbol],
5548 params: Option<P<hir::GenericArgs>>,
5551 let (path, res) = self.resolver
5552 .resolve_str_path(span, self.crate_root, components, is_value);
5554 let mut segments: Vec<_> = path.segments.iter().map(|segment| {
5555 let res = self.expect_full_res(segment.id);
5557 ident: segment.ident,
5558 hir_id: Some(self.lower_node_id(segment.id)),
5559 res: Some(self.lower_res(res)),
5564 segments.last_mut().unwrap().args = params;
5568 res: res.map_id(|_| panic!("unexpected node_id")),
5569 segments: segments.into(),
5573 fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
5574 let node = match qpath {
5575 hir::QPath::Resolved(None, path) => {
5576 // Turn trait object paths into `TyKind::TraitObject` instead.
5578 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
5579 let principal = hir::PolyTraitRef {
5580 bound_generic_params: hir::HirVec::new(),
5581 trait_ref: hir::TraitRef {
5588 // The original ID is taken by the `PolyTraitRef`,
5589 // so the `Ty` itself needs a different one.
5590 hir_id = self.next_id();
5591 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
5593 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
5596 _ => hir::TyKind::Path(qpath),
5605 /// Invoked to create the lifetime argument for a type `&T`
5606 /// with no explicit lifetime.
5607 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
5608 match self.anonymous_lifetime_mode {
5609 // Intercept when we are in an impl header or async fn and introduce an in-band
5611 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
5613 AnonymousLifetimeMode::CreateParameter => {
5614 let fresh_name = self.collect_fresh_in_band_lifetime(span);
5616 hir_id: self.next_id(),
5618 name: hir::LifetimeName::Param(fresh_name),
5622 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5624 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5626 AnonymousLifetimeMode::Replace(replacement) => {
5627 self.new_replacement_lifetime(replacement, span)
5632 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
5633 /// return a "error lifetime".
5634 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
5635 let (id, msg, label) = match id {
5636 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
5639 self.sess.next_node_id(),
5640 "`&` without an explicit lifetime name cannot be used here",
5641 "explicit lifetime name needed here",
5645 let mut err = struct_span_err!(
5652 err.span_label(span, label);
5655 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5658 /// Invoked to create the lifetime argument(s) for a path like
5659 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5660 /// sorts of cases are deprecated. This may therefore report a warning or an
5661 /// error, depending on the mode.
5662 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5664 .map(|_| self.elided_path_lifetime(span))
5668 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
5669 match self.anonymous_lifetime_mode {
5670 AnonymousLifetimeMode::CreateParameter => {
5671 // We should have emitted E0726 when processing this path above
5672 self.sess.delay_span_bug(
5674 "expected 'implicit elided lifetime not allowed' error",
5676 let id = self.sess.next_node_id();
5677 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5679 // This is the normal case.
5680 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5682 AnonymousLifetimeMode::Replace(replacement) => {
5683 self.new_replacement_lifetime(replacement, span)
5686 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5690 /// Invoked to create the lifetime argument(s) for an elided trait object
5691 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5692 /// when the bound is written, even if it is written with `'_` like in
5693 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5694 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5695 match self.anonymous_lifetime_mode {
5696 // NB. We intentionally ignore the create-parameter mode here.
5697 // and instead "pass through" to resolve-lifetimes, which will apply
5698 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5699 // do not act like other elided lifetimes. In other words, given this:
5701 // impl Foo for Box<dyn Debug>
5703 // we do not introduce a fresh `'_` to serve as the bound, but instead
5704 // ultimately translate to the equivalent of:
5706 // impl Foo for Box<dyn Debug + 'static>
5708 // `resolve_lifetime` has the code to make that happen.
5709 AnonymousLifetimeMode::CreateParameter => {}
5711 AnonymousLifetimeMode::ReportError => {
5712 // ReportError applies to explicit use of `'_`.
5715 // This is the normal case.
5716 AnonymousLifetimeMode::PassThrough => {}
5718 // We don't need to do any replacement here as this lifetime
5719 // doesn't refer to an elided lifetime elsewhere in the function
5721 AnonymousLifetimeMode::Replace(_) => {}
5724 self.new_implicit_lifetime(span)
5727 fn new_replacement_lifetime(
5729 replacement: LtReplacement,
5731 ) -> hir::Lifetime {
5732 let hir_id = self.next_id();
5733 self.replace_elided_lifetime(hir_id, span, replacement)
5736 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5738 hir_id: self.next_id(),
5740 name: hir::LifetimeName::Implicit,
5744 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5745 self.sess.buffer_lint_with_diagnostic(
5746 builtin::BARE_TRAIT_OBJECTS,
5749 "trait objects without an explicit `dyn` are deprecated",
5750 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5754 fn wrap_in_try_constructor(
5758 unstable_span: Span,
5760 let path = &[sym::ops, sym::Try, method];
5761 let from_err = P(self.expr_std_path(unstable_span, path, None,
5763 P(self.expr_call(e.span, from_err, hir_vec![e]))
5770 ) -> hir::ExprKind {
5774 // let mut pinned = <expr>;
5776 // match ::std::future::poll_with_tls_context(unsafe {
5777 // ::std::pin::Pin::new_unchecked(&mut pinned)
5779 // ::std::task::Poll::Ready(result) => break result,
5780 // ::std::task::Poll::Pending => {},
5785 match self.generator_kind {
5786 Some(hir::GeneratorKind::Async) => {},
5787 Some(hir::GeneratorKind::Gen) |
5789 let mut err = struct_span_err!(
5793 "`await` is only allowed inside `async` functions and blocks"
5795 err.span_label(await_span, "only allowed inside `async` functions and blocks");
5796 if let Some(item_sp) = self.current_item {
5797 err.span_label(item_sp, "this is not `async`");
5802 let span = self.mark_span_with_reason(
5803 CompilerDesugaringKind::Await,
5807 let gen_future_span = self.mark_span_with_reason(
5808 CompilerDesugaringKind::Await,
5810 self.allow_gen_future.clone(),
5813 // let mut pinned = <expr>;
5814 let expr = P(self.lower_expr(expr));
5815 let pinned_ident = Ident::with_empty_ctxt(sym::pinned);
5816 let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode(
5819 hir::BindingAnnotation::Mutable,
5821 let pinned_let = self.stmt_let_pat(
5825 hir::LocalSource::AwaitDesugar,
5828 // ::std::future::poll_with_tls_context(unsafe {
5829 // ::std::pin::Pin::new_unchecked(&mut pinned)
5832 let pinned = P(self.expr_ident(span, pinned_ident, pinned_pat_hid));
5833 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
5834 let pin_ty_id = self.next_id();
5835 let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
5838 &[sym::pin, sym::Pin],
5840 hir_vec![ref_mut_pinned],
5842 let new_unchecked = P(self.expr(span, new_unchecked_expr_kind, ThinVec::new()));
5843 let unsafe_expr = self.expr_unsafe(new_unchecked);
5844 P(self.expr_call_std_path(
5846 &[sym::future, sym::poll_with_tls_context],
5847 hir_vec![unsafe_expr],
5851 // `::std::task::Poll::Ready(result) => break result`
5852 let loop_node_id = self.sess.next_node_id();
5853 let loop_hir_id = self.lower_node_id(loop_node_id);
5855 let x_ident = Ident::with_empty_ctxt(sym::result);
5856 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
5857 let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid));
5858 let ready_pat = self.pat_std_enum(
5860 &[sym::task, sym::Poll, sym::Ready],
5863 let break_x = self.with_loop_scope(loop_node_id, |this| {
5864 let expr_break = hir::ExprKind::Break(
5865 this.lower_loop_destination(None),
5868 P(this.expr(await_span, expr_break, ThinVec::new()))
5870 self.arm(hir_vec![ready_pat], break_x)
5873 // `::std::task::Poll::Pending => {}`
5875 let pending_pat = self.pat_std_enum(
5877 &[sym::task, sym::Poll, sym::Pending],
5880 let empty_block = P(self.expr_block_empty(span));
5881 self.arm(hir_vec![pending_pat], empty_block)
5885 let match_expr = P(self.expr_match(
5888 hir_vec![ready_arm, pending_arm],
5889 hir::MatchSource::AwaitDesugar,
5891 self.stmt(span, hir::StmtKind::Expr(match_expr))
5895 let unit = self.expr_unit(span);
5896 let yield_expr = P(self.expr(
5898 hir::ExprKind::Yield(P(unit), hir::YieldSource::Await),
5901 self.stmt(span, hir::StmtKind::Expr(yield_expr))
5904 let loop_block = P(self.block_all(
5906 hir_vec![match_stmt, yield_stmt],
5910 let loop_expr = P(hir::Expr {
5911 hir_id: loop_hir_id,
5912 node: hir::ExprKind::Loop(
5915 hir::LoopSource::Loop,
5918 attrs: ThinVec::new(),
5921 hir::ExprKind::Block(
5922 P(self.block_all(span, hir_vec![pinned_let], Some(loop_expr))),
5928 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5929 // Sorting by span ensures that we get things in order within a
5930 // file, and also puts the files in a sensible order.
5931 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5932 body_ids.sort_by_key(|b| bodies[b].value.span);
5936 /// Checks if the specified expression is a built-in range literal.
5937 /// (See: `LoweringContext::lower_expr()`).
5938 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
5939 use hir::{Path, QPath, ExprKind, TyKind};
5941 // Returns whether the given path represents a (desugared) range,
5942 // either in std or core, i.e. has either a `::std::ops::Range` or
5943 // `::core::ops::Range` prefix.
5944 fn is_range_path(path: &Path) -> bool {
5945 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.as_str().to_string()).collect();
5946 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
5948 // "{{root}}" is the equivalent of `::` prefix in `Path`.
5949 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
5950 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
5956 // Check whether a span corresponding to a range expression is a
5957 // range literal, rather than an explicit struct or `new()` call.
5958 fn is_lit(sess: &Session, span: &Span) -> bool {
5959 let source_map = sess.source_map();
5960 let end_point = source_map.end_point(*span);
5962 if let Ok(end_string) = source_map.span_to_snippet(end_point) {
5963 !(end_string.ends_with("}") || end_string.ends_with(")"))
5970 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
5971 ExprKind::Struct(ref qpath, _, _) => {
5972 if let QPath::Resolved(None, ref path) = **qpath {
5973 return is_range_path(&path) && is_lit(sess, &expr.span);
5977 // `..` desugars to its struct path.
5978 ExprKind::Path(QPath::Resolved(None, ref path)) => {
5979 return is_range_path(&path) && is_lit(sess, &expr.span);
5982 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
5983 ExprKind::Call(ref func, _) => {
5984 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
5985 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
5986 let new_call = segment.ident.as_str() == "new";
5987 return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;