1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Lowers the AST to the HIR.
13 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
14 //! much like a fold. Where lowering involves a bit more work things get more
15 //! interesting and there are some invariants you should know about. These mostly
16 //! concern spans and ids.
18 //! Spans are assigned to AST nodes during parsing and then are modified during
19 //! expansion to indicate the origin of a node and the process it went through
20 //! being expanded. Ids are assigned to AST nodes just before lowering.
22 //! For the simpler lowering steps, ids and spans should be preserved. Unlike
23 //! expansion we do not preserve the process of lowering in the spans, so spans
24 //! should not be modified here. When creating a new node (as opposed to
25 //! 'folding' an existing one), then you create a new id using `next_id()`.
27 //! You must ensure that ids are unique. That means that you should only use the
28 //! id from an AST node in a single HIR node (you can assume that AST node ids
29 //! are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
30 //! If you do, you must then set the new node's id to a fresh one.
32 //! Spans are used for error messages and for tools to map semantics back to
33 //! source code. It is therefore not as important with spans as ids to be strict
34 //! about use (you can't break the compiler by screwing up a span). Obviously, a
35 //! HIR node can only have a single span. But multiple nodes can have the same
36 //! span and spans don't need to be kept in order, etc. Where code is preserved
37 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
38 //! new it is probably best to give a span for the whole AST node being lowered.
39 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
40 //! get confused if the spans from leaf AST nodes occur in multiple places
41 //! in the HIR, especially for multiple identifiers.
43 use dep_graph::DepGraph;
44 use hir::{self, ParamName};
46 use hir::map::{DefKey, DefPathData, Definitions};
47 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
48 use hir::def::{Def, PathResolution, PerNS};
50 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
51 ELIDED_LIFETIMES_IN_PATHS};
52 use middle::cstore::CrateStore;
53 use rustc_data_structures::fx::FxHashSet;
54 use rustc_data_structures::indexed_vec::IndexVec;
55 use rustc_data_structures::thin_vec::ThinVec;
57 use util::common::FN_OUTPUT_NAME;
58 use util::nodemap::{DefIdMap, NodeMap};
60 use std::collections::BTreeMap;
64 use smallvec::SmallVec;
69 use syntax::ext::hygiene::{Mark, SyntaxContext};
70 use syntax::feature_gate::{emit_feature_err, GateIssue};
71 use syntax::print::pprust;
73 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
74 use syntax::std_inject;
75 use syntax::symbol::{keywords, Symbol};
76 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
77 use syntax::parse::token::Token;
78 use syntax::visit::{self, Visitor};
79 use syntax_pos::{Span, MultiSpan};
81 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
83 pub struct LoweringContext<'a> {
84 crate_root: Option<&'static str>,
86 // Use to assign ids to hir nodes that do not directly correspond to an ast node
89 cstore: &'a dyn CrateStore,
91 resolver: &'a mut dyn Resolver,
93 /// The items being lowered are collected here.
94 items: BTreeMap<NodeId, hir::Item>,
96 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
97 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
98 bodies: BTreeMap<hir::BodyId, hir::Body>,
99 exported_macros: Vec<hir::MacroDef>,
101 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
102 trait_auto_impl: BTreeMap<DefId, NodeId>,
106 catch_scopes: Vec<NodeId>,
107 loop_scopes: Vec<NodeId>,
108 is_in_loop_condition: bool,
109 is_in_trait_impl: bool,
111 /// What to do when we encounter either an "anonymous lifetime
112 /// reference". The term "anonymous" is meant to encompass both
113 /// `'_` lifetimes as well as fully elided cases where nothing is
114 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
115 anonymous_lifetime_mode: AnonymousLifetimeMode,
117 // Used to create lifetime definitions from in-band lifetime usages.
118 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
119 // When a named lifetime is encountered in a function or impl header and
120 // has not been defined
121 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
122 // to this list. The results of this list are then added to the list of
123 // lifetime definitions in the corresponding impl or function generics.
124 lifetimes_to_define: Vec<(Span, ParamName)>,
126 // Whether or not in-band lifetimes are being collected. This is used to
127 // indicate whether or not we're in a place where new lifetimes will result
128 // in in-band lifetime definitions, such a function or an impl header.
129 // This will always be false unless the `in_band_lifetimes` or
130 // `impl_header_lifetime_elision` feature is enabled.
131 is_collecting_in_band_lifetimes: bool,
133 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
134 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
135 // against this list to see if it is already in-scope, or if a definition
136 // needs to be created for it.
137 in_scope_lifetimes: Vec<Ident>,
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>,
147 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
148 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
150 /// Obtain the resolution for a node id
151 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
153 /// Obtain the possible resolutions for the given `use` statement.
154 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
156 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
157 /// This should only return `None` during testing.
158 fn definitions(&mut self) -> &mut Definitions;
160 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
161 /// it based on `is_value`.
165 crate_root: Option<&str>,
167 params: Option<P<hir::GenericArgs>>,
173 enum ImplTraitContext<'a> {
174 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
175 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
176 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
178 /// Newly generated parameters should be inserted into the given `Vec`.
179 Universal(&'a mut Vec<hir::GenericParam>),
181 /// Treat `impl Trait` as shorthand for a new existential parameter.
182 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
183 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
185 /// We optionally store a `DefId` for the parent item here so we can look up necessary
186 /// information later. It is `None` when no information about the context should be stored,
187 /// e.g. for consts and statics.
188 Existential(Option<DefId>),
190 /// `impl Trait` is not accepted in this position.
194 impl<'a> ImplTraitContext<'a> {
195 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
196 use self::ImplTraitContext::*;
198 Universal(params) => Universal(params),
199 Existential(did) => Existential(*did),
200 Disallowed => Disallowed,
207 cstore: &dyn CrateStore,
208 dep_graph: &DepGraph,
210 resolver: &mut dyn Resolver,
212 // We're constructing the HIR here; we don't care what we will
213 // read, since we haven't even constructed the *input* to
215 dep_graph.assert_ignored();
218 crate_root: std_inject::injected_crate_name(),
222 items: BTreeMap::new(),
223 trait_items: BTreeMap::new(),
224 impl_items: BTreeMap::new(),
225 bodies: BTreeMap::new(),
226 trait_impls: BTreeMap::new(),
227 trait_auto_impl: BTreeMap::new(),
228 exported_macros: Vec::new(),
229 catch_scopes: Vec::new(),
230 loop_scopes: Vec::new(),
231 is_in_loop_condition: false,
232 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
233 type_def_lifetime_params: DefIdMap(),
234 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
235 item_local_id_counters: NodeMap(),
236 node_id_to_hir_id: IndexVec::new(),
238 is_in_trait_impl: false,
239 lifetimes_to_define: Vec::new(),
240 is_collecting_in_band_lifetimes: false,
241 in_scope_lifetimes: Vec::new(),
245 #[derive(Copy, Clone, PartialEq)]
247 /// Any path in a type context.
249 /// The `module::Type` in `module::Type::method` in an expression.
254 struct LoweredNodeId {
259 enum ParenthesizedGenericArgs {
265 /// What to do when we encounter an **anonymous** lifetime
266 /// reference. Anonymous lifetime references come in two flavors. You
267 /// have implicit, or fully elided, references to lifetimes, like the
268 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
269 /// or `Ref<'_, T>`. These often behave the same, but not always:
271 /// - certain usages of implicit references are deprecated, like
272 /// `Ref<T>`, and we sometimes just give hard errors in those cases
274 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
275 /// the same as `Box<dyn Foo + '_>`.
277 /// We describe the effects of the various modes in terms of three cases:
279 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
280 /// of a `&` (e.g., the missing lifetime in something like `&T`)
281 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
282 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
283 /// elided bounds follow special rules. Note that this only covers
284 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
285 /// '_>` is a case of "modern" elision.
286 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
287 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
288 /// non-deprecated equivalent.
290 /// Currently, the handling of lifetime elision is somewhat spread out
291 /// between HIR lowering and -- as described below -- the
292 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
293 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
294 /// everything into HIR lowering.
295 #[derive(Copy, Clone)]
296 enum AnonymousLifetimeMode {
297 /// For **Modern** cases, create a new anonymous region parameter
298 /// and reference that.
300 /// For **Dyn Bound** cases, pass responsibility to
301 /// `resolve_lifetime` code.
303 /// For **Deprecated** cases, report an error.
306 /// Pass responsibility to `resolve_lifetime` code for all cases.
310 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[hir::ItemId; 1]> }
312 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
313 fn visit_ty(&mut self, ty: &'a Ty) {
319 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
322 visit::walk_ty(self, ty);
325 fn visit_path_segment(
328 path_segment: &'v PathSegment,
330 if let Some(ref p) = path_segment.args {
331 if let GenericArgs::Parenthesized(_) = **p {
335 visit::walk_path_segment(self, path_span, path_segment)
339 impl<'a> LoweringContext<'a> {
340 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
341 /// Full-crate AST visitor that inserts into a fresh
342 /// `LoweringContext` any information that may be
343 /// needed from arbitrary locations in the crate.
344 /// E.g. The number of lifetime generic parameters
345 /// declared for every type and trait definition.
346 struct MiscCollector<'lcx, 'interner: 'lcx> {
347 lctx: &'lcx mut LoweringContext<'interner>,
350 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
351 fn visit_item(&mut self, item: &'lcx Item) {
352 self.lctx.allocate_hir_id_counter(item.id, item);
355 ItemKind::Struct(_, ref generics)
356 | ItemKind::Union(_, ref generics)
357 | ItemKind::Enum(_, ref generics)
358 | ItemKind::Ty(_, ref generics)
359 | ItemKind::Existential(_, ref generics)
360 | ItemKind::Trait(_, _, ref generics, ..) => {
361 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
365 .filter(|param| match param.kind {
366 ast::GenericParamKind::Lifetime { .. } => true,
370 self.lctx.type_def_lifetime_params.insert(def_id, count);
374 visit::walk_item(self, item);
377 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
378 self.lctx.allocate_hir_id_counter(item.id, item);
379 visit::walk_trait_item(self, item);
382 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
383 self.lctx.allocate_hir_id_counter(item.id, item);
384 visit::walk_impl_item(self, item);
388 struct ItemLowerer<'lcx, 'interner: 'lcx> {
389 lctx: &'lcx mut LoweringContext<'interner>,
392 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
393 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
395 F: FnOnce(&mut Self),
397 let old = self.lctx.is_in_trait_impl;
398 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
404 self.lctx.is_in_trait_impl = old;
408 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
409 fn visit_item(&mut self, item: &'lcx Item) {
410 let mut item_lowered = true;
411 self.lctx.with_hir_id_owner(item.id, |lctx| {
412 if let Some(hir_item) = lctx.lower_item(item) {
413 lctx.items.insert(item.id, hir_item);
415 item_lowered = false;
420 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
421 hir::ItemKind::Impl(_, _, _, ref generics, ..)
422 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
423 generics.params.clone()
428 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
429 let this = &mut ItemLowerer { lctx: this };
430 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
431 this.with_trait_impl_ref(opt_trait_ref, |this| {
432 visit::walk_item(this, item)
435 visit::walk_item(this, item);
441 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
442 self.lctx.with_hir_id_owner(item.id, |lctx| {
443 let id = hir::TraitItemId { node_id: item.id };
444 let hir_item = lctx.lower_trait_item(item);
445 lctx.trait_items.insert(id, hir_item);
448 visit::walk_trait_item(self, item);
451 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
452 self.lctx.with_hir_id_owner(item.id, |lctx| {
453 let id = hir::ImplItemId { node_id: item.id };
454 let hir_item = lctx.lower_impl_item(item);
455 lctx.impl_items.insert(id, hir_item);
457 visit::walk_impl_item(self, item);
461 self.lower_node_id(CRATE_NODE_ID);
462 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
464 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
465 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
467 let module = self.lower_mod(&c.module);
468 let attrs = self.lower_attrs(&c.attrs);
469 let body_ids = body_ids(&self.bodies);
473 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
479 exported_macros: hir::HirVec::from(self.exported_macros),
481 trait_items: self.trait_items,
482 impl_items: self.impl_items,
485 trait_impls: self.trait_impls,
486 trait_auto_impl: self.trait_auto_impl,
490 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
491 if self.item_local_id_counters.insert(owner, 0).is_some() {
493 "Tried to allocate item_local_id_counter for {:?} twice",
497 // Always allocate the first HirId for the owner itself
498 self.lower_node_id_with_owner(owner, owner)
501 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
503 F: FnOnce(&mut Self) -> hir::HirId,
505 if ast_node_id == DUMMY_NODE_ID {
506 return LoweredNodeId {
507 node_id: DUMMY_NODE_ID,
508 hir_id: hir::DUMMY_HIR_ID,
512 let min_size = ast_node_id.as_usize() + 1;
514 if min_size > self.node_id_to_hir_id.len() {
515 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
518 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
520 if existing_hir_id == hir::DUMMY_HIR_ID {
521 // Generate a new HirId
522 let hir_id = alloc_hir_id(self);
523 self.node_id_to_hir_id[ast_node_id] = hir_id;
525 node_id: ast_node_id,
530 node_id: ast_node_id,
531 hir_id: existing_hir_id,
536 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
538 F: FnOnce(&mut Self) -> T,
540 let counter = self.item_local_id_counters
541 .insert(owner, HIR_ID_COUNTER_LOCKED)
542 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
543 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
544 self.current_hir_id_owner.push((def_index, counter));
546 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
548 debug_assert!(def_index == new_def_index);
549 debug_assert!(new_counter >= counter);
551 let prev = self.item_local_id_counters
552 .insert(owner, new_counter)
554 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
558 /// This method allocates a new HirId for the given NodeId and stores it in
559 /// the LoweringContext's NodeId => HirId map.
560 /// Take care not to call this method if the resulting HirId is then not
561 /// actually used in the HIR, as that would trigger an assertion in the
562 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
563 /// properly. Calling the method twice with the same NodeId is fine though.
564 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
565 self.lower_node_id_generic(ast_node_id, |this| {
566 let &mut (def_index, ref mut local_id_counter) =
567 this.current_hir_id_owner.last_mut().unwrap();
568 let local_id = *local_id_counter;
569 *local_id_counter += 1;
572 local_id: hir::ItemLocalId(local_id),
577 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
578 self.lower_node_id_generic(ast_node_id, |this| {
579 let local_id_counter = this
580 .item_local_id_counters
582 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
583 let local_id = *local_id_counter;
585 // We want to be sure not to modify the counter in the map while it
586 // is also on the stack. Otherwise we'll get lost updates when writing
587 // back from the stack to the map.
588 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
590 *local_id_counter += 1;
594 .opt_def_index(owner)
595 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
596 that do not belong to the current owner");
600 local_id: hir::ItemLocalId(local_id),
605 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
606 let body = hir::Body {
607 arguments: decl.map_or(hir_vec![], |decl| {
608 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
610 is_generator: self.is_generator,
614 self.bodies.insert(id, body);
618 fn next_id(&mut self) -> LoweredNodeId {
619 self.lower_node_id(self.sess.next_node_id())
622 fn expect_full_def(&mut self, id: NodeId) -> Def {
623 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
624 if pr.unresolved_segments() != 0 {
625 bug!("path not fully resolved: {:?}", pr);
631 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def> {
632 self.resolver.get_import(id).present_items().map(|pr| {
633 if pr.unresolved_segments() != 0 {
634 bug!("path not fully resolved: {:?}", pr);
640 fn diagnostic(&self) -> &errors::Handler {
641 self.sess.diagnostic()
644 fn str_to_ident(&self, s: &'static str) -> Ident {
645 Ident::with_empty_ctxt(Symbol::gensym(s))
648 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
649 let mark = Mark::fresh(Mark::root());
650 mark.set_expn_info(source_map::ExpnInfo {
652 def_site: Some(span),
653 format: source_map::CompilerDesugaring(reason),
654 allow_internal_unstable: true,
655 allow_internal_unsafe: false,
656 local_inner_macros: false,
657 edition: source_map::hygiene::default_edition(),
659 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
662 fn with_anonymous_lifetime_mode<R>(
664 anonymous_lifetime_mode: AnonymousLifetimeMode,
665 op: impl FnOnce(&mut Self) -> R,
667 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
668 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
669 let result = op(self);
670 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
674 /// Creates a new hir::GenericParam for every new lifetime and
675 /// type parameter encountered while evaluating `f`. Definitions
676 /// are created with the parent provided. If no `parent_id` is
677 /// provided, no definitions will be returned.
679 /// Presuming that in-band lifetimes are enabled, then
680 /// `self.anonymous_lifetime_mode` will be updated to match the
681 /// argument while `f` is running (and restored afterwards).
682 fn collect_in_band_defs<T, F>(
685 anonymous_lifetime_mode: AnonymousLifetimeMode,
687 ) -> (Vec<hir::GenericParam>, T)
689 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
691 assert!(!self.is_collecting_in_band_lifetimes);
692 assert!(self.lifetimes_to_define.is_empty());
693 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
695 if self.sess.features_untracked().impl_header_lifetime_elision {
696 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
697 self.is_collecting_in_band_lifetimes = true;
698 } else if self.sess.features_untracked().in_band_lifetimes {
699 self.is_collecting_in_band_lifetimes = true;
702 let (in_band_ty_params, res) = f(self);
704 self.is_collecting_in_band_lifetimes = false;
705 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
707 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
709 let params = lifetimes_to_define
711 .map(|(span, hir_name)| {
712 let def_node_id = self.next_id().node_id;
714 // Get the name we'll use to make the def-path. Note
715 // that collisions are ok here and this shouldn't
716 // really show up for end-user.
717 let str_name = match hir_name {
718 ParamName::Plain(ident) => ident.as_interned_str(),
719 ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_interned_str(),
722 // Add a definition for the in-band lifetime def
723 self.resolver.definitions().create_def_with_parent(
726 DefPathData::LifetimeParam(str_name),
727 DefIndexAddressSpace::High,
738 pure_wrt_drop: false,
739 kind: hir::GenericParamKind::Lifetime { in_band: true }
742 .chain(in_band_ty_params.into_iter())
748 /// When there is a reference to some lifetime `'a`, and in-band
749 /// lifetimes are enabled, then we want to push that lifetime into
750 /// the vector of names to define later. In that case, it will get
751 /// added to the appropriate generics.
752 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
753 if !self.is_collecting_in_band_lifetimes {
757 if !self.sess.features_untracked().in_band_lifetimes {
761 if self.in_scope_lifetimes.contains(&ident.modern()) {
765 let hir_name = ParamName::Plain(ident);
767 if self.lifetimes_to_define.iter()
768 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
772 self.lifetimes_to_define.push((ident.span, hir_name));
775 /// When we have either an elided or `'_` lifetime in an impl
776 /// header, we convert it to
777 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
778 assert!(self.is_collecting_in_band_lifetimes);
779 let index = self.lifetimes_to_define.len();
780 let hir_name = ParamName::Fresh(index);
781 self.lifetimes_to_define.push((span, hir_name));
785 // Evaluates `f` with the lifetimes in `params` in-scope.
786 // This is used to track which lifetimes have already been defined, and
787 // which are new in-band lifetimes that need to have a definition created
789 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
791 F: FnOnce(&mut LoweringContext<'_>) -> T,
793 let old_len = self.in_scope_lifetimes.len();
794 let lt_def_names = params.iter().filter_map(|param| match param.kind {
795 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
798 self.in_scope_lifetimes.extend(lt_def_names);
802 self.in_scope_lifetimes.truncate(old_len);
806 // Same as the method above, but accepts `hir::GenericParam`s
807 // instead of `ast::GenericParam`s.
808 // This should only be used with generics that have already had their
809 // in-band lifetimes added. In practice, this means that this function is
810 // only used when lowering a child item of a trait or impl.
811 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
812 params: &HirVec<hir::GenericParam>,
815 F: FnOnce(&mut LoweringContext<'_>) -> T,
817 let old_len = self.in_scope_lifetimes.len();
818 let lt_def_names = params.iter().filter_map(|param| match param.kind {
819 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
822 self.in_scope_lifetimes.extend(lt_def_names);
826 self.in_scope_lifetimes.truncate(old_len);
830 /// Appends in-band lifetime defs and argument-position `impl
831 /// Trait` defs to the existing set of generics.
833 /// Presuming that in-band lifetimes are enabled, then
834 /// `self.anonymous_lifetime_mode` will be updated to match the
835 /// argument while `f` is running (and restored afterwards).
836 fn add_in_band_defs<F, T>(
840 anonymous_lifetime_mode: AnonymousLifetimeMode,
842 ) -> (hir::Generics, T)
844 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
846 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
849 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
850 let mut params = Vec::new();
851 let generics = this.lower_generics(
853 ImplTraitContext::Universal(&mut params),
855 let res = f(this, &mut params);
856 (params, (generics, res))
861 lowered_generics.params = lowered_generics
868 (lowered_generics, res)
871 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
873 F: FnOnce(&mut LoweringContext<'_>) -> T,
875 let len = self.catch_scopes.len();
876 self.catch_scopes.push(catch_id);
878 let result = f(self);
881 self.catch_scopes.len(),
882 "catch scopes should be added and removed in stack order"
885 self.catch_scopes.pop().unwrap();
892 capture_clause: CaptureBy,
893 closure_node_id: NodeId,
895 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
897 let prev_is_generator = mem::replace(&mut self.is_generator, true);
898 let body_expr = body(self);
899 let span = body_expr.span;
900 let output = match ret_ty {
901 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
902 None => FunctionRetTy::Default(span),
909 let body_id = self.record_body(body_expr, Some(&decl));
910 self.is_generator = prev_is_generator;
912 let capture_clause = self.lower_capture_clause(capture_clause);
913 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
914 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
915 let generator = hir::Expr {
917 hir_id: closure_hir_id,
918 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
919 Some(hir::GeneratorMovability::Static)),
921 attrs: ThinVec::new(),
924 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
925 let gen_future = self.expr_std_path(
926 unstable_span, &["future", "from_generator"], None, ThinVec::new());
927 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
930 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
932 F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
934 let prev = mem::replace(&mut self.is_generator, false);
935 let result = f(self);
936 let r = self.record_body(result, decl);
937 self.is_generator = prev;
941 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
943 F: FnOnce(&mut LoweringContext<'_>) -> T,
945 // We're no longer in the base loop's condition; we're in another loop.
946 let was_in_loop_condition = self.is_in_loop_condition;
947 self.is_in_loop_condition = false;
949 let len = self.loop_scopes.len();
950 self.loop_scopes.push(loop_id);
952 let result = f(self);
955 self.loop_scopes.len(),
956 "Loop scopes should be added and removed in stack order"
959 self.loop_scopes.pop().unwrap();
961 self.is_in_loop_condition = was_in_loop_condition;
966 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
968 F: FnOnce(&mut LoweringContext<'_>) -> T,
970 let was_in_loop_condition = self.is_in_loop_condition;
971 self.is_in_loop_condition = true;
973 let result = f(self);
975 self.is_in_loop_condition = was_in_loop_condition;
980 fn with_new_scopes<T, F>(&mut self, f: F) -> T
982 F: FnOnce(&mut LoweringContext<'_>) -> T,
984 let was_in_loop_condition = self.is_in_loop_condition;
985 self.is_in_loop_condition = false;
987 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
988 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
990 self.catch_scopes = catch_scopes;
991 self.loop_scopes = loop_scopes;
993 self.is_in_loop_condition = was_in_loop_condition;
998 fn def_key(&mut self, id: DefId) -> DefKey {
1000 self.resolver.definitions().def_key(id.index)
1002 self.cstore.def_key(id)
1006 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1007 label.map(|label| hir::Label {
1012 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1013 let target_id = match destination {
1015 if let Def::Label(loop_id) = self.expect_full_def(id) {
1016 Ok(self.lower_node_id(loop_id).node_id)
1018 Err(hir::LoopIdError::UnresolvedLabel)
1025 .map(|id| Ok(self.lower_node_id(id).node_id))
1026 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1031 label: self.lower_label(destination.map(|(_, label)| label)),
1036 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1039 .map(|a| self.lower_attr(a))
1040 .collect::<Vec<_>>()
1044 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1048 path: attr.path.clone(),
1049 tokens: self.lower_token_stream(attr.tokens.clone()),
1050 is_sugared_doc: attr.is_sugared_doc,
1055 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1058 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1062 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1064 TokenTree::Token(span, token) => self.lower_token(token, span),
1065 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1068 delim: delimited.delim,
1069 tts: self.lower_token_stream(delimited.tts.into()).into(),
1075 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1077 Token::Interpolated(_) => {}
1078 other => return TokenTree::Token(span, other).into(),
1081 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1082 self.lower_token_stream(tts)
1085 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1087 attrs: self.lower_attrs(&arm.attrs),
1088 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1089 guard: match arm.guard {
1090 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1093 body: P(self.lower_expr(&arm.body)),
1097 fn lower_ty_binding(&mut self, b: &TypeBinding,
1098 itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1100 id: self.lower_node_id(b.id).node_id,
1102 ty: self.lower_ty(&b.ty, itctx),
1107 fn lower_generic_arg(&mut self,
1108 arg: &ast::GenericArg,
1109 itctx: ImplTraitContext<'_>)
1110 -> hir::GenericArg {
1112 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1113 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1117 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1118 P(self.lower_ty_direct(t, itctx))
1121 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1122 let kind = match t.node {
1123 TyKind::Infer => hir::TyKind::Infer,
1124 TyKind::Err => hir::TyKind::Err,
1125 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1126 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1127 TyKind::Rptr(ref region, ref mt) => {
1128 let span = t.span.shrink_to_lo();
1129 let lifetime = match *region {
1130 Some(ref lt) => self.lower_lifetime(lt),
1131 None => self.elided_ref_lifetime(span),
1133 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1135 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1138 this.with_anonymous_lifetime_mode(
1139 AnonymousLifetimeMode::PassThrough,
1141 hir::TyKind::BareFn(P(hir::BareFnTy {
1142 generic_params: this.lower_generic_params(
1145 ImplTraitContext::Disallowed,
1147 unsafety: this.lower_unsafety(f.unsafety),
1149 decl: this.lower_fn_decl(&f.decl, None, false, None),
1150 arg_names: this.lower_fn_args_to_names(&f.decl),
1156 TyKind::Never => hir::TyKind::Never,
1157 TyKind::Tup(ref tys) => {
1158 hir::TyKind::Tup(tys.iter().map(|ty| {
1159 self.lower_ty_direct(ty, itctx.reborrow())
1162 TyKind::Paren(ref ty) => {
1163 return self.lower_ty_direct(ty, itctx);
1165 TyKind::Path(ref qself, ref path) => {
1166 let id = self.lower_node_id(t.id);
1167 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1168 let ty = self.ty_path(id, t.span, qpath);
1169 if let hir::TyKind::TraitObject(..) = ty.node {
1170 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1174 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1177 def: self.expect_full_def(t.id),
1178 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1182 TyKind::Array(ref ty, ref length) => {
1183 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1185 TyKind::Typeof(ref expr) => {
1186 hir::TyKind::Typeof(self.lower_anon_const(expr))
1188 TyKind::TraitObject(ref bounds, kind) => {
1189 let mut lifetime_bound = None;
1192 .filter_map(|bound| match *bound {
1193 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1194 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1196 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1197 GenericBound::Outlives(ref lifetime) => {
1198 if lifetime_bound.is_none() {
1199 lifetime_bound = Some(self.lower_lifetime(lifetime));
1205 let lifetime_bound =
1206 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1207 if kind != TraitObjectSyntax::Dyn {
1208 self.maybe_lint_bare_trait(t.span, t.id, false);
1210 hir::TyKind::TraitObject(bounds, lifetime_bound)
1212 TyKind::ImplTrait(def_node_id, ref bounds) => {
1215 ImplTraitContext::Existential(fn_def_id) => {
1216 self.lower_existential_impl_trait(
1217 span, fn_def_id, def_node_id,
1218 |this| this.lower_param_bounds(bounds, itctx),
1221 ImplTraitContext::Universal(in_band_ty_params) => {
1222 self.lower_node_id(def_node_id);
1223 // Add a definition for the in-band Param
1224 let def_index = self
1227 .opt_def_index(def_node_id)
1230 let hir_bounds = self.lower_param_bounds(
1232 ImplTraitContext::Universal(in_band_ty_params),
1234 // Set the name to `impl Bound1 + Bound2`
1235 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1236 in_band_ty_params.push(hir::GenericParam {
1238 name: ParamName::Plain(ident),
1239 pure_wrt_drop: false,
1243 kind: hir::GenericParamKind::Type {
1245 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1249 hir::TyKind::Path(hir::QPath::Resolved(
1253 def: Def::TyParam(DefId::local(def_index)),
1254 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1258 ImplTraitContext::Disallowed => {
1259 let allowed_in = if self.sess.features_untracked()
1260 .impl_trait_in_bindings {
1261 "bindings or function and inherent method return types"
1263 "function and inherent method return types"
1269 "`impl Trait` not allowed outside of {}",
1276 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1279 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1288 fn lower_existential_impl_trait(
1291 fn_def_id: Option<DefId>,
1292 exist_ty_node_id: NodeId,
1293 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1295 // Make sure we know that some funky desugaring has been going on here.
1296 // This is a first: there is code in other places like for loop
1297 // desugaring that explicitly states that we don't want to track that.
1298 // Not tracking it makes lints in rustc and clippy very fragile as
1299 // frequently opened issues show.
1300 let exist_ty_span = self.allow_internal_unstable(
1301 CompilerDesugaringKind::ExistentialReturnType,
1305 let exist_ty_def_index = self
1308 .opt_def_index(exist_ty_node_id)
1311 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1313 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1315 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1321 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1322 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1323 generics: hir::Generics {
1324 params: lifetime_defs,
1325 where_clause: hir::WhereClause {
1326 id: lctx.next_id().node_id,
1327 predicates: Vec::new().into(),
1332 impl_trait_fn: fn_def_id,
1334 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1335 // Generate an `existential type Foo: Trait;` declaration
1336 trace!("creating existential type with id {:#?}", exist_ty_id);
1338 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1339 let exist_ty_item = hir::Item {
1340 id: exist_ty_id.node_id,
1341 hir_id: exist_ty_id.hir_id,
1342 name: keywords::Invalid.name(),
1343 attrs: Default::default(),
1344 node: exist_ty_item_kind,
1345 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1346 span: exist_ty_span,
1349 // Insert the item into the global list. This usually happens
1350 // automatically for all AST items. But this existential type item
1351 // does not actually exist in the AST.
1352 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1354 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1355 let path = P(hir::Path {
1356 span: exist_ty_span,
1357 def: Def::Existential(DefId::local(exist_ty_def_index)),
1358 segments: hir_vec![hir::PathSegment {
1360 ident: Ident::new(keywords::Invalid.name(), exist_ty_span),
1361 args: Some(P(hir::GenericArgs {
1362 parenthesized: false,
1363 bindings: HirVec::new(),
1368 hir::TyKind::Path(hir::QPath::Resolved(None, path))
1372 fn lifetimes_from_impl_trait_bounds(
1374 exist_ty_id: NodeId,
1375 parent_index: DefIndex,
1376 bounds: &hir::GenericBounds,
1377 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1378 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1379 // appear in the bounds, excluding lifetimes that are created within the bounds.
1380 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1381 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1382 context: &'r mut LoweringContext<'a>,
1384 exist_ty_id: NodeId,
1385 collect_elided_lifetimes: bool,
1386 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1387 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1388 output_lifetimes: Vec<hir::GenericArg>,
1389 output_lifetime_params: Vec<hir::GenericParam>,
1392 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1393 fn nested_visit_map<'this>(
1395 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1396 hir::intravisit::NestedVisitorMap::None
1399 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1400 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1401 if parameters.parenthesized {
1402 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1403 self.collect_elided_lifetimes = false;
1404 hir::intravisit::walk_generic_args(self, span, parameters);
1405 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1407 hir::intravisit::walk_generic_args(self, span, parameters);
1411 fn visit_ty(&mut self, t: &'v hir::Ty) {
1412 // Don't collect elided lifetimes used inside of `fn()` syntax
1413 if let hir::TyKind::BareFn(_) = t.node {
1414 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1415 self.collect_elided_lifetimes = false;
1417 // Record the "stack height" of `for<'a>` lifetime bindings
1418 // to be able to later fully undo their introduction.
1419 let old_len = self.currently_bound_lifetimes.len();
1420 hir::intravisit::walk_ty(self, t);
1421 self.currently_bound_lifetimes.truncate(old_len);
1423 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1425 hir::intravisit::walk_ty(self, t)
1429 fn visit_poly_trait_ref(
1431 trait_ref: &'v hir::PolyTraitRef,
1432 modifier: hir::TraitBoundModifier,
1434 // Record the "stack height" of `for<'a>` lifetime bindings
1435 // to be able to later fully undo their introduction.
1436 let old_len = self.currently_bound_lifetimes.len();
1437 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1438 self.currently_bound_lifetimes.truncate(old_len);
1441 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1442 // Record the introduction of 'a in `for<'a> ...`
1443 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1444 // Introduce lifetimes one at a time so that we can handle
1445 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1446 let lt_name = hir::LifetimeName::Param(param.name);
1447 self.currently_bound_lifetimes.push(lt_name);
1450 hir::intravisit::walk_generic_param(self, param);
1453 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1454 let name = match lifetime.name {
1455 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1456 if self.collect_elided_lifetimes {
1457 // Use `'_` for both implicit and underscore lifetimes in
1458 // `abstract type Foo<'_>: SomeTrait<'_>;`
1459 hir::LifetimeName::Underscore
1464 hir::LifetimeName::Param(_) => lifetime.name,
1465 hir::LifetimeName::Static => return,
1468 if !self.currently_bound_lifetimes.contains(&name)
1469 && !self.already_defined_lifetimes.contains(&name) {
1470 self.already_defined_lifetimes.insert(name);
1472 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1473 id: self.context.next_id().node_id,
1474 span: lifetime.span,
1478 // We need to manually create the ids here, because the
1479 // definitions will go into the explicit `existential type`
1480 // declaration and thus need to have their owner set to that item
1481 let def_node_id = self.context.sess.next_node_id();
1482 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1483 self.context.resolver.definitions().create_def_with_parent(
1486 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1487 DefIndexAddressSpace::High,
1492 let name = match name {
1493 hir::LifetimeName::Underscore => {
1494 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident())
1496 hir::LifetimeName::Param(param_name) => param_name,
1497 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1500 self.output_lifetime_params.push(hir::GenericParam {
1503 span: lifetime.span,
1504 pure_wrt_drop: false,
1507 kind: hir::GenericParamKind::Lifetime {
1515 let mut lifetime_collector = ImplTraitLifetimeCollector {
1517 parent: parent_index,
1519 collect_elided_lifetimes: true,
1520 currently_bound_lifetimes: Vec::new(),
1521 already_defined_lifetimes: FxHashSet::default(),
1522 output_lifetimes: Vec::new(),
1523 output_lifetime_params: Vec::new(),
1526 for bound in bounds {
1527 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1531 lifetime_collector.output_lifetimes.into(),
1532 lifetime_collector.output_lifetime_params.into(),
1536 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1541 .map(|x| self.lower_foreign_item(x))
1546 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1553 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1555 node: hir::VariantKind {
1556 name: v.node.ident.name,
1557 attrs: self.lower_attrs(&v.node.attrs),
1558 data: self.lower_variant_data(&v.node.data),
1559 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1568 qself: &Option<QSelf>,
1570 param_mode: ParamMode,
1571 mut itctx: ImplTraitContext<'_>,
1573 let qself_position = qself.as_ref().map(|q| q.position);
1574 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1576 let resolution = self.resolver
1578 .unwrap_or(PathResolution::new(Def::Err));
1580 let proj_start = p.segments.len() - resolution.unresolved_segments();
1581 let path = P(hir::Path {
1582 def: resolution.base_def(),
1583 segments: p.segments[..proj_start]
1586 .map(|(i, segment)| {
1587 let param_mode = match (qself_position, param_mode) {
1588 (Some(j), ParamMode::Optional) if i < j => {
1589 // This segment is part of the trait path in a
1590 // qualified path - one of `a`, `b` or `Trait`
1591 // in `<X as a::b::Trait>::T::U::method`.
1597 // Figure out if this is a type/trait segment,
1598 // which may need lifetime elision performed.
1599 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1600 krate: def_id.krate,
1601 index: this.def_key(def_id).parent.expect("missing parent"),
1603 let type_def_id = match resolution.base_def() {
1604 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1605 Some(parent_def_id(self, def_id))
1607 Def::Variant(def_id) if i + 1 == proj_start => {
1608 Some(parent_def_id(self, def_id))
1611 | Def::Union(def_id)
1613 | Def::TyAlias(def_id)
1614 | Def::Trait(def_id) if i + 1 == proj_start =>
1620 let parenthesized_generic_args = match resolution.base_def() {
1621 // `a::b::Trait(Args)`
1622 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1623 // `a::b::Trait(Args)::TraitItem`
1624 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1625 if i + 2 == proj_start =>
1627 ParenthesizedGenericArgs::Ok
1629 // Avoid duplicated errors
1630 Def::Err => ParenthesizedGenericArgs::Ok,
1636 | Def::Variant(..) if i + 1 == proj_start =>
1638 ParenthesizedGenericArgs::Err
1640 // A warning for now, for compatibility reasons
1641 _ => ParenthesizedGenericArgs::Warn,
1644 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1645 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1648 assert!(!def_id.is_local());
1650 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1651 let n = item_generics.own_counts().lifetimes;
1652 self.type_def_lifetime_params.insert(def_id, n);
1655 self.lower_path_segment(
1660 parenthesized_generic_args,
1668 // Simple case, either no projections, or only fully-qualified.
1669 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1670 if resolution.unresolved_segments() == 0 {
1671 return hir::QPath::Resolved(qself, path);
1674 // Create the innermost type that we're projecting from.
1675 let mut ty = if path.segments.is_empty() {
1676 // If the base path is empty that means there exists a
1677 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1678 qself.expect("missing QSelf for <T>::...")
1680 // Otherwise, the base path is an implicit `Self` type path,
1681 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1682 // `<I as Iterator>::Item::default`.
1683 let new_id = self.next_id();
1684 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1687 // Anything after the base path are associated "extensions",
1688 // out of which all but the last one are associated types,
1689 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1690 // * base path is `std::vec::Vec<T>`
1691 // * "extensions" are `IntoIter`, `Item` and `clone`
1692 // * type nodes are:
1693 // 1. `std::vec::Vec<T>` (created above)
1694 // 2. `<std::vec::Vec<T>>::IntoIter`
1695 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1696 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1697 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1698 let segment = P(self.lower_path_segment(
1703 ParenthesizedGenericArgs::Warn,
1706 let qpath = hir::QPath::TypeRelative(ty, segment);
1708 // It's finished, return the extension of the right node type.
1709 if i == p.segments.len() - 1 {
1713 // Wrap the associated extension in another type node.
1714 let new_id = self.next_id();
1715 ty = P(self.ty_path(new_id, p.span, qpath));
1718 // Should've returned in the for loop above.
1721 "lower_qpath: no final extension segment in {}..{}",
1727 fn lower_path_extra(
1731 ident: Option<Ident>,
1732 param_mode: ParamMode,
1736 segments: p.segments
1739 self.lower_path_segment(
1744 ParenthesizedGenericArgs::Err,
1745 ImplTraitContext::Disallowed,
1748 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1754 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1755 let def = self.expect_full_def(id);
1756 self.lower_path_extra(def, p, None, param_mode)
1759 fn lower_path_segment(
1762 segment: &PathSegment,
1763 param_mode: ParamMode,
1764 expected_lifetimes: usize,
1765 parenthesized_generic_args: ParenthesizedGenericArgs,
1766 itctx: ImplTraitContext<'_>,
1767 ) -> hir::PathSegment {
1768 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1769 let msg = "parenthesized parameters may only be used with a trait";
1770 match **generic_args {
1771 GenericArgs::AngleBracketed(ref data) => {
1772 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1774 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1775 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1776 ParenthesizedGenericArgs::Warn => {
1777 self.sess.buffer_lint(
1778 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1783 (hir::GenericArgs::none(), true)
1785 ParenthesizedGenericArgs::Err => {
1786 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1787 .span_label(data.span, "only traits may use parentheses")
1789 (hir::GenericArgs::none(), true)
1794 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1797 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1798 GenericArg::Lifetime(_) => true,
1801 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1802 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1803 if !generic_args.parenthesized && !has_lifetimes {
1805 self.elided_path_lifetimes(path_span, expected_lifetimes)
1807 .map(|lt| GenericArg::Lifetime(lt))
1808 .chain(generic_args.args.into_iter())
1810 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1811 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1812 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1813 let no_bindings = generic_args.bindings.is_empty();
1814 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1815 // If there are no (non-implicit) generic args or associated-type
1816 // bindings, our suggestion includes the angle brackets
1817 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1819 // Otherwise—sorry, this is kind of gross—we need to infer the
1820 // place to splice in the `'_, ` from the generics that do exist
1821 let first_generic_span = first_generic_span
1822 .expect("already checked that type args or bindings exist");
1823 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1825 self.sess.buffer_lint_with_diagnostic(
1826 ELIDED_LIFETIMES_IN_PATHS,
1829 "hidden lifetime parameters in types are deprecated",
1830 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1831 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1837 hir::PathSegment::new(
1844 fn lower_angle_bracketed_parameter_data(
1846 data: &AngleBracketedArgs,
1847 param_mode: ParamMode,
1848 mut itctx: ImplTraitContext<'_>,
1849 ) -> (hir::GenericArgs, bool) {
1850 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1851 let has_types = args.iter().any(|arg| match arg {
1852 ast::GenericArg::Type(_) => true,
1856 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1857 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1858 parenthesized: false,
1860 !has_types && param_mode == ParamMode::Optional)
1863 fn lower_parenthesized_parameter_data(
1865 data: &ParenthesisedArgs,
1866 ) -> (hir::GenericArgs, bool) {
1867 // Switch to `PassThrough` mode for anonymous lifetimes: this
1868 // means that we permit things like `&Ref<T>`, where `Ref` has
1869 // a hidden lifetime parameter. This is needed for backwards
1870 // compatibility, even in contexts like an impl header where
1871 // we generally don't permit such things (see #51008).
1872 self.with_anonymous_lifetime_mode(
1873 AnonymousLifetimeMode::PassThrough,
1875 const DISALLOWED: ImplTraitContext<'_> = ImplTraitContext::Disallowed;
1876 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1877 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1878 let mk_tup = |this: &mut Self, tys, span| {
1879 let LoweredNodeId { node_id, hir_id } = this.next_id();
1880 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1885 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1888 id: this.next_id().node_id,
1889 ident: Ident::from_str(FN_OUTPUT_NAME),
1892 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1893 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1894 span: output.as_ref().map_or(span, |ty| ty.span),
1897 parenthesized: true,
1905 fn lower_local(&mut self, l: &Local) -> (P<hir::Local>, SmallVec<[hir::ItemId; 1]>) {
1906 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1907 let mut ids = SmallVec::<[hir::ItemId; 1]>::new();
1908 if self.sess.features_untracked().impl_trait_in_bindings {
1909 if let Some(ref ty) = l.ty {
1910 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1911 visitor.visit_ty(ty);
1914 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
1920 .map(|t| self.lower_ty(t,
1921 if self.sess.features_untracked().impl_trait_in_bindings {
1922 ImplTraitContext::Existential(Some(parent_def_id))
1924 ImplTraitContext::Disallowed
1927 pat: self.lower_pat(&l.pat),
1928 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1930 attrs: l.attrs.clone(),
1931 source: hir::LocalSource::Normal,
1935 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1937 Mutability::Mutable => hir::MutMutable,
1938 Mutability::Immutable => hir::MutImmutable,
1942 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1943 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1947 pat: self.lower_pat(&arg.pat),
1951 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1954 .map(|arg| match arg.pat.node {
1955 PatKind::Ident(_, ident, _) => ident,
1956 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1961 // Lowers a function declaration.
1963 // decl: the unlowered (ast) function declaration.
1964 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1965 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1966 // make_ret_async is also `Some`.
1967 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1968 // This guards against trait declarations and implementations where impl Trait is
1970 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1971 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1972 // return type impl Trait item.
1976 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
1977 impl_trait_return_allow: bool,
1978 make_ret_async: Option<NodeId>,
1979 ) -> P<hir::FnDecl> {
1980 let inputs = decl.inputs
1983 if let Some((_, ref mut ibty)) = in_band_ty_params {
1984 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
1986 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
1989 .collect::<HirVec<_>>();
1991 let output = if let Some(ret_id) = make_ret_async {
1992 self.lower_async_fn_ret_ty(
1995 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2000 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2001 Some((def_id, _)) if impl_trait_return_allow => {
2002 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(Some(def_id))))
2004 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2006 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2013 variadic: decl.variadic,
2014 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
2015 TyKind::ImplicitSelf => true,
2016 TyKind::Rptr(_, ref mt) => mt.ty.node.is_implicit_self(),
2022 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
2024 // fn_span: the span of the async function declaration. Used for error reporting.
2025 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2026 // output: unlowered output type (`T` in `-> T`)
2027 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2028 fn lower_async_fn_ret_ty(
2031 output: &FunctionRetTy,
2033 return_impl_trait_id: NodeId,
2034 ) -> hir::FunctionRetTy {
2035 // Get lifetimes used in the input arguments to the function. Our output type must also
2036 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
2037 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
2038 // is a subset of the other. We really want some new lifetime that is a subset of all input
2039 // lifetimes, but that doesn't exist at the moment.
2041 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
2042 context: &'r mut LoweringContext<'a>,
2043 // Lifetimes bound by HRTB
2044 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2045 // Whether to count elided lifetimes.
2046 // Disabled inside of `Fn` or `fn` syntax.
2047 collect_elided_lifetimes: bool,
2048 // The lifetime found.
2049 // Multiple different or elided lifetimes cannot appear in async fn for now.
2050 output_lifetime: Option<(hir::LifetimeName, Span)>,
2053 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2054 fn nested_visit_map<'this>(
2056 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2057 hir::intravisit::NestedVisitorMap::None
2060 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2061 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2062 if parameters.parenthesized {
2063 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2064 self.collect_elided_lifetimes = false;
2065 hir::intravisit::walk_generic_args(self, span, parameters);
2066 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2068 hir::intravisit::walk_generic_args(self, span, parameters);
2072 fn visit_ty(&mut self, t: &'v hir::Ty) {
2073 // Don't collect elided lifetimes used inside of `fn()` syntax
2074 if let &hir::TyKind::BareFn(_) = &t.node {
2075 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2076 self.collect_elided_lifetimes = false;
2078 // Record the "stack height" of `for<'a>` lifetime bindings
2079 // to be able to later fully undo their introduction.
2080 let old_len = self.currently_bound_lifetimes.len();
2081 hir::intravisit::walk_ty(self, t);
2082 self.currently_bound_lifetimes.truncate(old_len);
2084 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2086 hir::intravisit::walk_ty(self, t);
2090 fn visit_poly_trait_ref(
2092 trait_ref: &'v hir::PolyTraitRef,
2093 modifier: hir::TraitBoundModifier,
2095 // Record the "stack height" of `for<'a>` lifetime bindings
2096 // to be able to later fully undo their introduction.
2097 let old_len = self.currently_bound_lifetimes.len();
2098 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2099 self.currently_bound_lifetimes.truncate(old_len);
2102 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2103 // Record the introduction of 'a in `for<'a> ...`
2104 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2105 // Introduce lifetimes one at a time so that we can handle
2106 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2107 let lt_name = hir::LifetimeName::Param(param.name);
2108 self.currently_bound_lifetimes.push(lt_name);
2111 hir::intravisit::walk_generic_param(self, param);
2114 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2115 let name = match lifetime.name {
2116 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2117 if self.collect_elided_lifetimes {
2118 // Use `'_` for both implicit and underscore lifetimes in
2119 // `abstract type Foo<'_>: SomeTrait<'_>;`
2120 hir::LifetimeName::Underscore
2125 hir::LifetimeName::Param(_) => lifetime.name,
2126 hir::LifetimeName::Static => return,
2129 if !self.currently_bound_lifetimes.contains(&name) {
2130 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2131 // We don't currently have a reliable way to desugar `async fn` with
2132 // multiple potentially unrelated input lifetimes into
2133 // `-> impl Trait + 'lt`, so we report an error in this case.
2134 if current_lt_name != name {
2137 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2139 "multiple different lifetimes used in arguments of `async fn`",
2141 .span_label(current_lt_span, "first lifetime here")
2142 .span_label(lifetime.span, "different lifetime here")
2143 .help("`async fn` can only accept borrowed values \
2144 with identical lifetimes")
2146 } else if current_lt_name.is_elided() && name.is_elided() {
2149 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2151 "multiple elided lifetimes used in arguments of `async fn`",
2153 .span_label(current_lt_span, "first lifetime here")
2154 .span_label(lifetime.span, "different lifetime here")
2155 .help("consider giving these arguments named lifetimes")
2159 self.output_lifetime = Some((name, lifetime.span));
2165 let bound_lifetime = {
2166 let mut lifetime_collector = AsyncFnLifetimeCollector {
2168 currently_bound_lifetimes: Vec::new(),
2169 collect_elided_lifetimes: true,
2170 output_lifetime: None,
2174 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2176 lifetime_collector.output_lifetime
2179 let span = match output {
2180 FunctionRetTy::Ty(ty) => ty.span,
2181 FunctionRetTy::Default(span) => *span,
2184 let impl_trait_ty = self.lower_existential_impl_trait(
2185 span, Some(fn_def_id), return_impl_trait_id, |this| {
2186 let output_ty = match output {
2187 FunctionRetTy::Ty(ty) => {
2188 this.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2190 FunctionRetTy::Default(span) => {
2191 let LoweredNodeId { node_id, hir_id } = this.next_id();
2195 node: hir::TyKind::Tup(hir_vec![]),
2202 let future_params = P(hir::GenericArgs {
2204 bindings: hir_vec![hir::TypeBinding {
2205 ident: Ident::from_str(FN_OUTPUT_NAME),
2207 id: this.next_id().node_id,
2210 parenthesized: false,
2214 this.std_path(span, &["future", "Future"], Some(future_params), false);
2216 let LoweredNodeId { node_id, hir_id } = this.next_id();
2217 let mut bounds = vec![
2218 hir::GenericBound::Trait(
2220 trait_ref: hir::TraitRef {
2225 bound_generic_params: hir_vec![],
2228 hir::TraitBoundModifier::None
2232 if let Some((name, span)) = bound_lifetime {
2233 bounds.push(hir::GenericBound::Outlives(
2234 hir::Lifetime { id: this.next_id().node_id, name, span }));
2237 hir::HirVec::from(bounds)
2240 let LoweredNodeId { node_id, hir_id } = self.next_id();
2241 let impl_trait_ty = P(hir::Ty {
2243 node: impl_trait_ty,
2248 hir::FunctionRetTy::Return(impl_trait_ty)
2251 fn lower_param_bound(
2254 itctx: ImplTraitContext<'_>,
2255 ) -> hir::GenericBound {
2257 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2258 self.lower_poly_trait_ref(ty, itctx),
2259 self.lower_trait_bound_modifier(modifier),
2261 GenericBound::Outlives(ref lifetime) => {
2262 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2267 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2268 let span = l.ident.span;
2270 ident if ident.name == keywords::StaticLifetime.name() =>
2271 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2272 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2273 match self.anonymous_lifetime_mode {
2274 AnonymousLifetimeMode::CreateParameter => {
2275 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2276 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2279 AnonymousLifetimeMode::PassThrough => {
2280 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2284 self.maybe_collect_in_band_lifetime(ident);
2285 let param_name = ParamName::Plain(ident);
2286 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2291 fn new_named_lifetime(
2295 name: hir::LifetimeName,
2296 ) -> hir::Lifetime {
2298 id: self.lower_node_id(id).node_id,
2304 fn lower_generic_params(
2306 params: &[GenericParam],
2307 add_bounds: &NodeMap<Vec<GenericBound>>,
2308 mut itctx: ImplTraitContext<'_>,
2309 ) -> hir::HirVec<hir::GenericParam> {
2310 params.iter().map(|param| {
2311 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2315 fn lower_generic_param(&mut self,
2316 param: &GenericParam,
2317 add_bounds: &NodeMap<Vec<GenericBound>>,
2318 mut itctx: ImplTraitContext<'_>)
2319 -> hir::GenericParam {
2320 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx.reborrow());
2322 GenericParamKind::Lifetime => {
2323 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2324 self.is_collecting_in_band_lifetimes = false;
2326 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2327 let param_name = match lt.name {
2328 hir::LifetimeName::Param(param_name) => param_name,
2329 _ => hir::ParamName::Plain(lt.name.ident()),
2331 let param = hir::GenericParam {
2335 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2336 attrs: self.lower_attrs(¶m.attrs),
2338 kind: hir::GenericParamKind::Lifetime { in_band: false }
2341 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2345 GenericParamKind::Type { ref default, .. } => {
2346 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2347 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2348 // Instead, use gensym("Self") to create a distinct name that looks the same.
2349 let ident = if param.ident.name == keywords::SelfType.name() {
2350 param.ident.gensym()
2355 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2356 if !add_bounds.is_empty() {
2357 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2358 bounds = bounds.into_iter()
2364 id: self.lower_node_id(param.id).node_id,
2365 name: hir::ParamName::Plain(ident),
2366 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2367 attrs: self.lower_attrs(¶m.attrs),
2370 kind: hir::GenericParamKind::Type {
2371 default: default.as_ref().map(|x| {
2372 self.lower_ty(x, ImplTraitContext::Disallowed)
2374 synthetic: param.attrs.iter()
2375 .filter(|attr| attr.check_name("rustc_synthetic"))
2376 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2386 generics: &Generics,
2387 itctx: ImplTraitContext<'_>)
2390 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2391 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2392 // paths where report_error is called are also the only paths that advance to after
2393 // the match statement, so the error reporting could probably just be moved there.
2394 let mut add_bounds: NodeMap<Vec<_>> = NodeMap();
2395 for pred in &generics.where_clause.predicates {
2396 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2397 'next_bound: for bound in &bound_pred.bounds {
2398 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2399 let report_error = |this: &mut Self| {
2400 this.diagnostic().span_err(
2401 bound_pred.bounded_ty.span,
2402 "`?Trait` bounds are only permitted at the \
2403 point where a type parameter is declared",
2406 // Check if the where clause type is a plain type parameter.
2407 match bound_pred.bounded_ty.node {
2408 TyKind::Path(None, ref path)
2409 if path.segments.len() == 1
2410 && bound_pred.bound_generic_params.is_empty() =>
2412 if let Some(Def::TyParam(def_id)) = self.resolver
2413 .get_resolution(bound_pred.bounded_ty.id)
2414 .map(|d| d.base_def())
2416 if let Some(node_id) =
2417 self.resolver.definitions().as_local_node_id(def_id)
2419 for param in &generics.params {
2421 GenericParamKind::Type { .. } => {
2422 if node_id == param.id {
2423 add_bounds.entry(param.id)
2425 .push(bound.clone());
2426 continue 'next_bound;
2436 _ => report_error(self),
2444 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2445 where_clause: self.lower_where_clause(&generics.where_clause),
2446 span: generics.span,
2450 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2452 id: self.lower_node_id(wc.id).node_id,
2453 predicates: wc.predicates
2455 .map(|predicate| self.lower_where_predicate(predicate))
2460 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2462 WherePredicate::BoundPredicate(WhereBoundPredicate {
2463 ref bound_generic_params,
2468 self.with_in_scope_lifetime_defs(
2469 &bound_generic_params,
2471 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2472 bound_generic_params: this.lower_generic_params(
2473 bound_generic_params,
2475 ImplTraitContext::Disallowed,
2477 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2480 .filter_map(|bound| match *bound {
2481 // Ignore `?Trait` bounds.
2482 // Tthey were copied into type parameters already.
2483 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2484 _ => Some(this.lower_param_bound(
2486 ImplTraitContext::Disallowed,
2495 WherePredicate::RegionPredicate(WhereRegionPredicate {
2499 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2501 lifetime: self.lower_lifetime(lifetime),
2502 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2504 WherePredicate::EqPredicate(WhereEqPredicate {
2509 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2510 id: self.lower_node_id(id).node_id,
2511 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2512 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2518 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2520 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2524 .map(|f| self.lower_struct_field(f))
2526 self.lower_node_id(id).node_id,
2528 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2532 .map(|f| self.lower_struct_field(f))
2534 self.lower_node_id(id).node_id,
2536 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2540 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2541 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2542 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2543 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2545 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2553 fn lower_poly_trait_ref(
2556 mut itctx: ImplTraitContext<'_>,
2557 ) -> hir::PolyTraitRef {
2558 let bound_generic_params =
2559 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2560 let trait_ref = self.with_parent_impl_lifetime_defs(
2561 &bound_generic_params,
2562 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2566 bound_generic_params,
2572 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2575 id: self.lower_node_id(f.id).node_id,
2576 ident: match f.ident {
2577 Some(ident) => ident,
2578 // FIXME(jseyfried) positional field hygiene
2579 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2581 vis: self.lower_visibility(&f.vis, None),
2582 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2583 attrs: self.lower_attrs(&f.attrs),
2587 fn lower_field(&mut self, f: &Field) -> hir::Field {
2589 id: self.next_id().node_id,
2591 expr: P(self.lower_expr(&f.expr)),
2593 is_shorthand: f.is_shorthand,
2597 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2599 ty: self.lower_ty(&mt.ty, itctx),
2600 mutbl: self.lower_mutability(mt.mutbl),
2604 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2605 -> hir::GenericBounds {
2606 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2609 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2610 let mut expr = None;
2612 let mut stmts = vec![];
2614 for (index, stmt) in b.stmts.iter().enumerate() {
2615 if index == b.stmts.len() - 1 {
2616 if let StmtKind::Expr(ref e) = stmt.node {
2617 expr = Some(P(self.lower_expr(e)));
2619 stmts.extend(self.lower_stmt(stmt));
2622 stmts.extend(self.lower_stmt(stmt));
2626 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2631 stmts: stmts.into(),
2633 rules: self.lower_block_check_mode(&b.rules),
2636 recovered: b.recovered,
2640 fn lower_async_body(
2646 self.lower_body(Some(decl), |this| {
2647 if let IsAsync::Async { closure_id, .. } = asyncness {
2648 let async_expr = this.make_async_expr(
2649 CaptureBy::Value, closure_id, None,
2651 let body = this.lower_block(body, false);
2652 this.expr_block(body, ThinVec::new())
2654 this.expr(body.span, async_expr, ThinVec::new())
2656 let body = this.lower_block(body, false);
2657 this.expr_block(body, ThinVec::new())
2666 attrs: &hir::HirVec<Attribute>,
2667 vis: &mut hir::Visibility,
2669 ) -> hir::ItemKind {
2671 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2672 ItemKind::Use(ref use_tree) => {
2673 // Start with an empty prefix
2676 span: use_tree.span,
2679 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2681 ItemKind::Static(ref t, m, ref e) => {
2682 let value = self.lower_body(None, |this| this.lower_expr(e));
2683 hir::ItemKind::Static(
2686 if self.sess.features_untracked().impl_trait_in_bindings {
2687 ImplTraitContext::Existential(None)
2689 ImplTraitContext::Disallowed
2692 self.lower_mutability(m),
2696 ItemKind::Const(ref t, ref e) => {
2697 let value = self.lower_body(None, |this| this.lower_expr(e));
2698 hir::ItemKind::Const(
2701 if self.sess.features_untracked().impl_trait_in_bindings {
2702 ImplTraitContext::Existential(None)
2704 ImplTraitContext::Disallowed
2710 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2711 let fn_def_id = self.resolver.definitions().local_def_id(id);
2712 self.with_new_scopes(|this| {
2713 // Note: we don't need to change the return type from `T` to
2714 // `impl Future<Output = T>` here because lower_body
2715 // only cares about the input argument patterns in the function
2716 // declaration (decl), not the return types.
2717 let body_id = this.lower_async_body(decl, header.asyncness, body);
2719 let (generics, fn_decl) = this.add_in_band_defs(
2722 AnonymousLifetimeMode::PassThrough,
2723 |this, idty| this.lower_fn_decl(
2725 Some((fn_def_id, idty)),
2727 header.asyncness.opt_return_id()
2733 this.lower_fn_header(header),
2739 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2740 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2741 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2742 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2743 self.lower_ty(t, ImplTraitContext::Disallowed),
2744 self.lower_generics(generics, ImplTraitContext::Disallowed),
2746 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2747 generics: self.lower_generics(generics, ImplTraitContext::Disallowed),
2748 bounds: self.lower_param_bounds(b, ImplTraitContext::Disallowed),
2749 impl_trait_fn: None,
2751 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2753 variants: enum_definition
2756 .map(|x| self.lower_variant(x))
2759 self.lower_generics(generics, ImplTraitContext::Disallowed),
2761 ItemKind::Struct(ref struct_def, ref generics) => {
2762 let struct_def = self.lower_variant_data(struct_def);
2763 hir::ItemKind::Struct(
2765 self.lower_generics(generics, ImplTraitContext::Disallowed),
2768 ItemKind::Union(ref vdata, ref generics) => {
2769 let vdata = self.lower_variant_data(vdata);
2770 hir::ItemKind::Union(
2772 self.lower_generics(generics, ImplTraitContext::Disallowed),
2784 let def_id = self.resolver.definitions().local_def_id(id);
2786 // Lower the "impl header" first. This ordering is important
2787 // for in-band lifetimes! Consider `'a` here:
2789 // impl Foo<'a> for u32 {
2790 // fn method(&'a self) { .. }
2793 // Because we start by lowering the `Foo<'a> for u32`
2794 // part, we will add `'a` to the list of generics on
2795 // the impl. When we then encounter it later in the
2796 // method, it will not be considered an in-band
2797 // lifetime to be added, but rather a reference to a
2799 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2802 AnonymousLifetimeMode::CreateParameter,
2804 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2805 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2808 if let Some(ref trait_ref) = trait_ref {
2809 if let Def::Trait(def_id) = trait_ref.path.def {
2810 this.trait_impls.entry(def_id).or_default().push(id);
2814 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2816 (trait_ref, lowered_ty)
2820 let new_impl_items = self.with_in_scope_lifetime_defs(
2821 &ast_generics.params,
2825 .map(|item| this.lower_impl_item_ref(item))
2830 hir::ItemKind::Impl(
2831 self.lower_unsafety(unsafety),
2832 self.lower_impl_polarity(polarity),
2833 self.lower_defaultness(defaultness, true /* [1] */),
2840 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2841 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2844 .map(|item| self.lower_trait_item_ref(item))
2846 hir::ItemKind::Trait(
2847 self.lower_is_auto(is_auto),
2848 self.lower_unsafety(unsafety),
2849 self.lower_generics(generics, ImplTraitContext::Disallowed),
2854 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2855 self.lower_generics(generics, ImplTraitContext::Disallowed),
2856 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2858 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2861 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2862 // not cause an assertion failure inside the `lower_defaultness` function
2870 vis: &mut hir::Visibility,
2872 attrs: &hir::HirVec<Attribute>,
2873 ) -> hir::ItemKind {
2874 let path = &tree.prefix;
2877 UseTreeKind::Simple(rename, id1, id2) => {
2878 *name = tree.ident().name;
2880 // First apply the prefix to the path
2881 let mut path = Path {
2885 .chain(path.segments.iter())
2891 // Correctly resolve `self` imports
2892 if path.segments.len() > 1
2893 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2895 let _ = path.segments.pop();
2896 if rename.is_none() {
2897 *name = path.segments.last().unwrap().ident.name;
2901 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2902 let mut defs = self.expect_full_def_from_use(id);
2903 // we want to return *something* from this function, so hang onto the first item
2905 let ret_def = defs.next().unwrap_or(Def::Err);
2907 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2908 let vis = vis.clone();
2909 let name = name.clone();
2910 let span = path.span;
2911 self.resolver.definitions().create_def_with_parent(
2915 DefIndexAddressSpace::High,
2918 self.allocate_hir_id_counter(new_node_id, &path);
2920 self.with_hir_id_owner(new_node_id, |this| {
2921 let new_id = this.lower_node_id(new_node_id);
2922 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2923 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2924 let vis_kind = match vis.node {
2925 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2926 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2927 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2928 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2929 let id = this.next_id();
2930 hir::VisibilityKind::Restricted {
2932 // We are allocating a new NodeId here
2938 let vis = respan(vis.span, vis_kind);
2944 hir_id: new_id.hir_id,
2946 attrs: attrs.clone(),
2955 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2956 hir::ItemKind::Use(path, hir::UseKind::Single)
2958 UseTreeKind::Glob => {
2959 let path = P(self.lower_path(
2965 .chain(path.segments.iter())
2970 ParamMode::Explicit,
2972 hir::ItemKind::Use(path, hir::UseKind::Glob)
2974 UseTreeKind::Nested(ref trees) => {
2979 .chain(path.segments.iter())
2982 span: prefix.span.to(path.span),
2985 // Add all the nested PathListItems in the HIR
2986 for &(ref use_tree, id) in trees {
2987 self.allocate_hir_id_counter(id, &use_tree);
2991 } = self.lower_node_id(id);
2993 let mut vis = vis.clone();
2994 let mut name = name.clone();
2996 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2998 self.with_hir_id_owner(new_id, |this| {
2999 let vis_kind = match vis.node {
3000 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3001 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3002 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3003 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3004 let id = this.next_id();
3005 hir::VisibilityKind::Restricted {
3007 // We are allocating a new NodeId here
3013 let vis = respan(vis.span, vis_kind);
3021 attrs: attrs.clone(),
3024 span: use_tree.span,
3030 // Privatize the degenerate import base, used only to check
3031 // the stability of `use a::{};`, to avoid it showing up as
3032 // a re-export by accident when `pub`, e.g. in documentation.
3033 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
3034 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3035 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3040 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3041 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3042 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3044 let (generics, node) = match i.node {
3045 TraitItemKind::Const(ref ty, ref default) => (
3046 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3047 hir::TraitItemKind::Const(
3048 self.lower_ty(ty, ImplTraitContext::Disallowed),
3051 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3054 TraitItemKind::Method(ref sig, None) => {
3055 let names = self.lower_fn_args_to_names(&sig.decl);
3056 let (generics, sig) = self.lower_method_sig(
3063 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3065 TraitItemKind::Method(ref sig, Some(ref body)) => {
3066 let body_id = self.lower_body(Some(&sig.decl), |this| {
3067 let body = this.lower_block(body, false);
3068 this.expr_block(body, ThinVec::new())
3070 let (generics, sig) = self.lower_method_sig(
3077 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3079 TraitItemKind::Type(ref bounds, ref default) => (
3080 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3081 hir::TraitItemKind::Type(
3082 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3085 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
3088 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3095 attrs: self.lower_attrs(&i.attrs),
3102 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3103 let (kind, has_default) = match i.node {
3104 TraitItemKind::Const(_, ref default) => {
3105 (hir::AssociatedItemKind::Const, default.is_some())
3107 TraitItemKind::Type(_, ref default) => {
3108 (hir::AssociatedItemKind::Type, default.is_some())
3110 TraitItemKind::Method(ref sig, ref default) => (
3111 hir::AssociatedItemKind::Method {
3112 has_self: sig.decl.has_self(),
3116 TraitItemKind::Macro(..) => unimplemented!(),
3119 id: hir::TraitItemId { node_id: i.id },
3122 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3127 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3128 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3129 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3131 let (generics, node) = match i.node {
3132 ImplItemKind::Const(ref ty, ref expr) => {
3133 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3135 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3136 hir::ImplItemKind::Const(
3137 self.lower_ty(ty, ImplTraitContext::Disallowed),
3142 ImplItemKind::Method(ref sig, ref body) => {
3143 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3144 let impl_trait_return_allow = !self.is_in_trait_impl;
3145 let (generics, sig) = self.lower_method_sig(
3149 impl_trait_return_allow,
3150 sig.header.asyncness.opt_return_id(),
3152 (generics, hir::ImplItemKind::Method(sig, body_id))
3154 ImplItemKind::Type(ref ty) => (
3155 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3156 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3158 ImplItemKind::Existential(ref bounds) => (
3159 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3160 hir::ImplItemKind::Existential(
3161 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3164 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3171 attrs: self.lower_attrs(&i.attrs),
3173 vis: self.lower_visibility(&i.vis, None),
3174 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3179 // [1] since `default impl` is not yet implemented, this is always true in impls
3182 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3184 id: hir::ImplItemId { node_id: i.id },
3187 vis: self.lower_visibility(&i.vis, Some(i.id)),
3188 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3189 kind: match i.node {
3190 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3191 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3192 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3193 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3194 has_self: sig.decl.has_self(),
3196 ImplItemKind::Macro(..) => unimplemented!(),
3200 // [1] since `default impl` is not yet implemented, this is always true in impls
3203 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3206 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3210 /// Lowers `impl Trait` items for a function and appends them to the list
3211 fn lower_fn_impl_trait_ids(
3215 ids: &mut SmallVec<[hir::ItemId; 1]>,
3217 if let Some(id) = header.asyncness.opt_return_id() {
3218 ids.push(hir::ItemId { id });
3220 let mut visitor = ImplTraitTypeIdVisitor { ids };
3222 FunctionRetTy::Default(_) => {},
3223 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3227 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3229 ItemKind::Use(ref use_tree) => {
3230 let mut vec = smallvec![hir::ItemId { id: i.id }];
3231 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3234 ItemKind::MacroDef(..) => SmallVec::new(),
3235 ItemKind::Fn(ref decl, ref header, ..) => {
3236 let mut ids = smallvec![hir::ItemId { id: i.id }];
3237 self.lower_fn_impl_trait_ids(decl, header, &mut ids);
3240 ItemKind::Impl(.., None, _, ref items) => {
3241 let mut ids = smallvec![hir::ItemId { id: i.id }];
3243 if let ImplItemKind::Method(ref sig, _) = item.node {
3244 self.lower_fn_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3249 ItemKind::Static(ref ty, ..) => {
3250 let mut ids = smallvec![hir::ItemId { id: i.id }];
3251 if self.sess.features_untracked().impl_trait_in_bindings {
3252 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3253 visitor.visit_ty(ty);
3257 ItemKind::Const(ref ty, ..) => {
3258 let mut ids = smallvec![hir::ItemId { id: i.id }];
3259 if self.sess.features_untracked().impl_trait_in_bindings {
3260 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3261 visitor.visit_ty(ty);
3265 _ => smallvec![hir::ItemId { id: i.id }],
3269 fn lower_item_id_use_tree(&mut self,
3272 vec: &mut SmallVec<[hir::ItemId; 1]>)
3275 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3276 vec.push(hir::ItemId { id });
3277 self.lower_item_id_use_tree(nested, id, vec);
3279 UseTreeKind::Glob => {}
3280 UseTreeKind::Simple(_, id1, id2) => {
3281 for (_, &id) in self.expect_full_def_from_use(base_id)
3283 .zip([id1, id2].iter())
3285 vec.push(hir::ItemId { id });
3291 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3292 let mut name = i.ident.name;
3293 let mut vis = self.lower_visibility(&i.vis, None);
3294 let attrs = self.lower_attrs(&i.attrs);
3295 if let ItemKind::MacroDef(ref def) = i.node {
3296 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3297 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3298 let body = self.lower_token_stream(def.stream());
3299 self.exported_macros.push(hir::MacroDef {
3312 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3314 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3327 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3328 let node_id = self.lower_node_id(i.id).node_id;
3329 let def_id = self.resolver.definitions().local_def_id(node_id);
3333 attrs: self.lower_attrs(&i.attrs),
3334 node: match i.node {
3335 ForeignItemKind::Fn(ref fdec, ref generics) => {
3336 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3339 AnonymousLifetimeMode::PassThrough,
3342 // Disallow impl Trait in foreign items
3343 this.lower_fn_decl(fdec, None, false, None),
3344 this.lower_fn_args_to_names(fdec),
3349 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3351 ForeignItemKind::Static(ref t, m) => {
3352 hir::ForeignItemKind::Static(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3354 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3355 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3357 vis: self.lower_visibility(&i.vis, None),
3362 fn lower_method_sig(
3364 generics: &Generics,
3367 impl_trait_return_allow: bool,
3368 is_async: Option<NodeId>,
3369 ) -> (hir::Generics, hir::MethodSig) {
3370 let header = self.lower_fn_header(sig.header);
3371 let (generics, decl) = self.add_in_band_defs(
3374 AnonymousLifetimeMode::PassThrough,
3375 |this, idty| this.lower_fn_decl(
3377 Some((fn_def_id, idty)),
3378 impl_trait_return_allow,
3382 (generics, hir::MethodSig { header, decl })
3385 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3387 IsAuto::Yes => hir::IsAuto::Yes,
3388 IsAuto::No => hir::IsAuto::No,
3392 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3394 unsafety: self.lower_unsafety(h.unsafety),
3395 asyncness: self.lower_asyncness(h.asyncness),
3396 constness: self.lower_constness(h.constness),
3401 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3403 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3404 Unsafety::Normal => hir::Unsafety::Normal,
3408 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3410 Constness::Const => hir::Constness::Const,
3411 Constness::NotConst => hir::Constness::NotConst,
3415 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3417 IsAsync::Async { .. } => hir::IsAsync::Async,
3418 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3422 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3424 UnOp::Deref => hir::UnDeref,
3425 UnOp::Not => hir::UnNot,
3426 UnOp::Neg => hir::UnNeg,
3430 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3432 node: match b.node {
3433 BinOpKind::Add => hir::BinOpKind::Add,
3434 BinOpKind::Sub => hir::BinOpKind::Sub,
3435 BinOpKind::Mul => hir::BinOpKind::Mul,
3436 BinOpKind::Div => hir::BinOpKind::Div,
3437 BinOpKind::Rem => hir::BinOpKind::Rem,
3438 BinOpKind::And => hir::BinOpKind::And,
3439 BinOpKind::Or => hir::BinOpKind::Or,
3440 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3441 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3442 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3443 BinOpKind::Shl => hir::BinOpKind::Shl,
3444 BinOpKind::Shr => hir::BinOpKind::Shr,
3445 BinOpKind::Eq => hir::BinOpKind::Eq,
3446 BinOpKind::Lt => hir::BinOpKind::Lt,
3447 BinOpKind::Le => hir::BinOpKind::Le,
3448 BinOpKind::Ne => hir::BinOpKind::Ne,
3449 BinOpKind::Ge => hir::BinOpKind::Ge,
3450 BinOpKind::Gt => hir::BinOpKind::Gt,
3456 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3457 let node = match p.node {
3458 PatKind::Wild => hir::PatKind::Wild,
3459 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3460 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3461 // `None` can occur in body-less function signatures
3462 def @ None | def @ Some(Def::Local(_)) => {
3463 let canonical_id = match def {
3464 Some(Def::Local(id)) => id,
3467 hir::PatKind::Binding(
3468 self.lower_binding_mode(binding_mode),
3471 sub.as_ref().map(|x| self.lower_pat(x)),
3474 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3479 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3484 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3485 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3486 let qpath = self.lower_qpath(
3490 ParamMode::Optional,
3491 ImplTraitContext::Disallowed,
3493 self.check_self_struct_ctor_feature(&qpath);
3494 hir::PatKind::TupleStruct(
3496 pats.iter().map(|x| self.lower_pat(x)).collect(),
3500 PatKind::Path(ref qself, ref path) => {
3501 let qpath = self.lower_qpath(
3505 ParamMode::Optional,
3506 ImplTraitContext::Disallowed,
3508 self.check_self_struct_ctor_feature(&qpath);
3509 hir::PatKind::Path(qpath)
3511 PatKind::Struct(ref path, ref fields, etc) => {
3512 let qpath = self.lower_qpath(
3516 ParamMode::Optional,
3517 ImplTraitContext::Disallowed,
3524 node: hir::FieldPat {
3525 id: self.next_id().node_id,
3526 ident: f.node.ident,
3527 pat: self.lower_pat(&f.node.pat),
3528 is_shorthand: f.node.is_shorthand,
3532 hir::PatKind::Struct(qpath, fs, etc)
3534 PatKind::Tuple(ref elts, ddpos) => {
3535 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3537 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3538 PatKind::Ref(ref inner, mutbl) => {
3539 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3541 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3542 P(self.lower_expr(e1)),
3543 P(self.lower_expr(e2)),
3544 self.lower_range_end(end),
3546 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3547 before.iter().map(|x| self.lower_pat(x)).collect(),
3548 slice.as_ref().map(|x| self.lower_pat(x)),
3549 after.iter().map(|x| self.lower_pat(x)).collect(),
3551 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3552 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3555 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3564 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3566 RangeEnd::Included(_) => hir::RangeEnd::Included,
3567 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3571 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3572 self.with_new_scopes(|this| {
3573 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3577 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3582 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3583 let kind = match e.node {
3584 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3585 ExprKind::ObsoleteInPlace(..) => {
3586 self.sess.abort_if_errors();
3587 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3589 ExprKind::Array(ref exprs) => {
3590 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3592 ExprKind::Repeat(ref expr, ref count) => {
3593 let expr = P(self.lower_expr(expr));
3594 let count = self.lower_anon_const(count);
3595 hir::ExprKind::Repeat(expr, count)
3597 ExprKind::Tup(ref elts) => {
3598 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3600 ExprKind::Call(ref f, ref args) => {
3601 let f = P(self.lower_expr(f));
3602 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3604 ExprKind::MethodCall(ref seg, ref args) => {
3605 let hir_seg = self.lower_path_segment(
3608 ParamMode::Optional,
3610 ParenthesizedGenericArgs::Err,
3611 ImplTraitContext::Disallowed,
3613 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3614 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3616 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3617 let binop = self.lower_binop(binop);
3618 let lhs = P(self.lower_expr(lhs));
3619 let rhs = P(self.lower_expr(rhs));
3620 hir::ExprKind::Binary(binop, lhs, rhs)
3622 ExprKind::Unary(op, ref ohs) => {
3623 let op = self.lower_unop(op);
3624 let ohs = P(self.lower_expr(ohs));
3625 hir::ExprKind::Unary(op, ohs)
3627 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3628 ExprKind::Cast(ref expr, ref ty) => {
3629 let expr = P(self.lower_expr(expr));
3630 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3632 ExprKind::Type(ref expr, ref ty) => {
3633 let expr = P(self.lower_expr(expr));
3634 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3636 ExprKind::AddrOf(m, ref ohs) => {
3637 let m = self.lower_mutability(m);
3638 let ohs = P(self.lower_expr(ohs));
3639 hir::ExprKind::AddrOf(m, ohs)
3641 // More complicated than you might expect because the else branch
3642 // might be `if let`.
3643 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3644 let else_opt = else_opt.as_ref().map(|els| {
3646 ExprKind::IfLet(..) => {
3647 // wrap the if-let expr in a block
3648 let span = els.span;
3649 let els = P(self.lower_expr(els));
3650 let LoweredNodeId { node_id, hir_id } = self.next_id();
3651 let blk = P(hir::Block {
3656 rules: hir::DefaultBlock,
3658 targeted_by_break: false,
3659 recovered: blk.recovered,
3661 P(self.expr_block(blk, ThinVec::new()))
3663 _ => P(self.lower_expr(els)),
3667 let then_blk = self.lower_block(blk, false);
3668 let then_expr = self.expr_block(then_blk, ThinVec::new());
3670 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3672 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3673 hir::ExprKind::While(
3674 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3675 this.lower_block(body, false),
3676 this.lower_label(opt_label),
3679 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3680 hir::ExprKind::Loop(
3681 this.lower_block(body, false),
3682 this.lower_label(opt_label),
3683 hir::LoopSource::Loop,
3686 ExprKind::TryBlock(ref body) => {
3687 self.with_catch_scope(body.id, |this| {
3689 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3690 let mut block = this.lower_block(body, true).into_inner();
3691 let tail = block.expr.take().map_or_else(
3693 let LoweredNodeId { node_id, hir_id } = this.next_id();
3694 let span = this.sess.source_map().end_point(unstable_span);
3698 node: hir::ExprKind::Tup(hir_vec![]),
3699 attrs: ThinVec::new(),
3703 |x: P<hir::Expr>| x.into_inner(),
3705 block.expr = Some(this.wrap_in_try_constructor(
3706 "from_ok", tail, unstable_span));
3707 hir::ExprKind::Block(P(block), None)
3710 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3711 P(self.lower_expr(expr)),
3712 arms.iter().map(|x| self.lower_arm(x)).collect(),
3713 hir::MatchSource::Normal,
3715 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3716 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3717 this.with_new_scopes(|this| {
3718 let block = this.lower_block(block, false);
3719 this.expr_block(block, ThinVec::new())
3724 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3726 if let IsAsync::Async { closure_id, .. } = asyncness {
3727 let outer_decl = FnDecl {
3728 inputs: decl.inputs.clone(),
3729 output: FunctionRetTy::Default(fn_decl_span),
3732 // We need to lower the declaration outside the new scope, because we
3733 // have to conserve the state of being inside a loop condition for the
3734 // closure argument types.
3735 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3737 self.with_new_scopes(|this| {
3738 // FIXME(cramertj) allow `async` non-`move` closures with
3739 if capture_clause == CaptureBy::Ref &&
3740 !decl.inputs.is_empty()
3746 "`async` non-`move` closures with arguments \
3747 are not currently supported",
3749 .help("consider using `let` statements to manually capture \
3750 variables by reference before entering an \
3751 `async move` closure")
3755 // Transform `async |x: u8| -> X { ... }` into
3756 // `|x: u8| future_from_generator(|| -> X { ... })`
3757 let body_id = this.lower_body(Some(&outer_decl), |this| {
3758 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3761 let async_body = this.make_async_expr(
3762 capture_clause, closure_id, async_ret_ty,
3764 this.with_new_scopes(|this| this.lower_expr(body))
3766 this.expr(fn_decl_span, async_body, ThinVec::new())
3768 hir::ExprKind::Closure(
3769 this.lower_capture_clause(capture_clause),
3777 // Lower outside new scope to preserve `is_in_loop_condition`.
3778 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3780 self.with_new_scopes(|this| {
3781 let mut is_generator = false;
3782 let body_id = this.lower_body(Some(decl), |this| {
3783 let e = this.lower_expr(body);
3784 is_generator = this.is_generator;
3787 let generator_option = if is_generator {
3788 if !decl.inputs.is_empty() {
3793 "generators cannot have explicit arguments"
3795 this.sess.abort_if_errors();
3797 Some(match movability {
3798 Movability::Movable => hir::GeneratorMovability::Movable,
3799 Movability::Static => hir::GeneratorMovability::Static,
3802 if movability == Movability::Static {
3807 "closures cannot be static"
3812 hir::ExprKind::Closure(
3813 this.lower_capture_clause(capture_clause),
3822 ExprKind::Block(ref blk, opt_label) => {
3823 hir::ExprKind::Block(self.lower_block(blk,
3824 opt_label.is_some()),
3825 self.lower_label(opt_label))
3827 ExprKind::Assign(ref el, ref er) => {
3828 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3830 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3831 self.lower_binop(op),
3832 P(self.lower_expr(el)),
3833 P(self.lower_expr(er)),
3835 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3836 ExprKind::Index(ref el, ref er) => {
3837 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3839 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3840 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3841 let id = self.next_id();
3842 let e1 = self.lower_expr(e1);
3843 let e2 = self.lower_expr(e2);
3844 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3845 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3846 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3847 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3848 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3849 hir::ExprKind::Call(new, hir_vec![e1, e2])
3851 ExprKind::Range(ref e1, ref e2, lims) => {
3852 use syntax::ast::RangeLimits::*;
3854 let path = match (e1, e2, lims) {
3855 (&None, &None, HalfOpen) => "RangeFull",
3856 (&Some(..), &None, HalfOpen) => "RangeFrom",
3857 (&None, &Some(..), HalfOpen) => "RangeTo",
3858 (&Some(..), &Some(..), HalfOpen) => "Range",
3859 (&None, &Some(..), Closed) => "RangeToInclusive",
3860 (&Some(..), &Some(..), Closed) => unreachable!(),
3861 (_, &None, Closed) => self.diagnostic()
3862 .span_fatal(e.span, "inclusive range with no end")
3866 let fields = e1.iter()
3867 .map(|e| ("start", e))
3868 .chain(e2.iter().map(|e| ("end", e)))
3870 let expr = P(self.lower_expr(&e));
3871 let ident = Ident::new(Symbol::intern(s), e.span);
3872 self.field(ident, expr, e.span)
3874 .collect::<P<[hir::Field]>>();
3876 let is_unit = fields.is_empty();
3877 let struct_path = iter::once("ops")
3878 .chain(iter::once(path))
3879 .collect::<Vec<_>>();
3880 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
3881 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3883 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3889 hir::ExprKind::Path(struct_path)
3891 hir::ExprKind::Struct(struct_path, fields, None)
3894 attrs: e.attrs.clone(),
3897 ExprKind::Path(ref qself, ref path) => {
3898 let qpath = self.lower_qpath(
3902 ParamMode::Optional,
3903 ImplTraitContext::Disallowed,
3905 self.check_self_struct_ctor_feature(&qpath);
3906 hir::ExprKind::Path(qpath)
3908 ExprKind::Break(opt_label, ref opt_expr) => {
3909 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3912 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3915 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3917 hir::ExprKind::Break(
3919 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3922 ExprKind::Continue(opt_label) => {
3923 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3926 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3929 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3932 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3933 ExprKind::InlineAsm(ref asm) => {
3934 let hir_asm = hir::InlineAsm {
3935 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3936 outputs: asm.outputs
3938 .map(|out| hir::InlineAsmOutput {
3939 constraint: out.constraint.clone(),
3941 is_indirect: out.is_indirect,
3944 asm: asm.asm.clone(),
3945 asm_str_style: asm.asm_str_style,
3946 clobbers: asm.clobbers.clone().into(),
3947 volatile: asm.volatile,
3948 alignstack: asm.alignstack,
3949 dialect: asm.dialect,
3952 let outputs = asm.outputs
3954 .map(|out| self.lower_expr(&out.expr))
3956 let inputs = asm.inputs
3958 .map(|&(_, ref input)| self.lower_expr(input))
3960 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
3962 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
3967 ParamMode::Optional,
3968 ImplTraitContext::Disallowed,
3970 fields.iter().map(|x| self.lower_field(x)).collect(),
3971 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3973 ExprKind::Paren(ref ex) => {
3974 let mut ex = self.lower_expr(ex);
3975 // include parens in span, but only if it is a super-span.
3976 if e.span.contains(ex.span) {
3979 // merge attributes into the inner expression.
3980 let mut attrs = e.attrs.clone();
3981 attrs.extend::<Vec<_>>(ex.attrs.into());
3986 ExprKind::Yield(ref opt_expr) => {
3987 self.is_generator = true;
3990 .map(|x| self.lower_expr(x))
3992 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
3994 hir::ExprKind::Yield(P(expr))
3997 // Desugar ExprIfLet
3998 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3999 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4002 // match <sub_expr> {
4004 // _ => [<else_opt> | ()]
4007 let mut arms = vec![];
4009 // `<pat> => <body>`
4011 let body = self.lower_block(body, false);
4012 let body_expr = P(self.expr_block(body, ThinVec::new()));
4013 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4014 arms.push(self.arm(pats, body_expr));
4017 // _ => [<else_opt>|()]
4019 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4020 let wildcard_pattern = self.pat_wild(e.span);
4021 let body = if let Some(else_expr) = wildcard_arm {
4022 P(self.lower_expr(else_expr))
4024 self.expr_tuple(e.span, hir_vec![])
4026 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4029 let contains_else_clause = else_opt.is_some();
4031 let sub_expr = P(self.lower_expr(sub_expr));
4033 hir::ExprKind::Match(
4036 hir::MatchSource::IfLetDesugar {
4037 contains_else_clause,
4042 // Desugar ExprWhileLet
4043 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4044 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4047 // [opt_ident]: loop {
4048 // match <sub_expr> {
4054 // Note that the block AND the condition are evaluated in the loop scope.
4055 // This is done to allow `break` from inside the condition of the loop.
4056 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4058 this.lower_block(body, false),
4059 this.expr_break(e.span, ThinVec::new()),
4060 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4064 // `<pat> => <body>`
4066 let body_expr = P(self.expr_block(body, ThinVec::new()));
4067 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4068 self.arm(pats, body_expr)
4073 let pat_under = self.pat_wild(e.span);
4074 self.arm(hir_vec![pat_under], break_expr)
4077 // `match <sub_expr> { ... }`
4078 let arms = hir_vec![pat_arm, break_arm];
4079 let match_expr = self.expr(
4081 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4085 // `[opt_ident]: loop { ... }`
4086 let loop_block = P(self.block_expr(P(match_expr)));
4087 let loop_expr = hir::ExprKind::Loop(
4089 self.lower_label(opt_label),
4090 hir::LoopSource::WhileLet,
4092 // add attributes to the outer returned expr node
4096 // Desugar ExprForLoop
4097 // From: `[opt_ident]: for <pat> in <head> <body>`
4098 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4102 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4104 // [opt_ident]: loop {
4106 // match ::std::iter::Iterator::next(&mut iter) {
4107 // ::std::option::Option::Some(val) => __next = val,
4108 // ::std::option::Option::None => break
4110 // let <pat> = __next;
4111 // StmtKind::Expr(<body>);
4119 let head = self.lower_expr(head);
4120 let head_sp = head.span;
4122 let iter = self.str_to_ident("iter");
4124 let next_ident = self.str_to_ident("__next");
4125 let next_sp = self.allow_internal_unstable(
4126 CompilerDesugaringKind::ForLoop,
4129 let next_pat = self.pat_ident_binding_mode(
4132 hir::BindingAnnotation::Mutable,
4135 // `::std::option::Option::Some(val) => next = val`
4137 let val_ident = self.str_to_ident("val");
4138 let val_pat = self.pat_ident(pat.span, val_ident);
4139 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4140 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4141 let assign = P(self.expr(
4143 hir::ExprKind::Assign(next_expr, val_expr),
4146 let some_pat = self.pat_some(pat.span, val_pat);
4147 self.arm(hir_vec![some_pat], assign)
4150 // `::std::option::Option::None => break`
4153 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4154 let pat = self.pat_none(e.span);
4155 self.arm(hir_vec![pat], break_expr)
4160 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4162 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4164 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4165 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4166 let next_path = &["iter", "Iterator", "next"];
4167 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4168 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4169 let arms = hir_vec![pat_arm, break_arm];
4173 hir::ExprKind::Match(
4176 hir::MatchSource::ForLoopDesugar
4181 let match_stmt = respan(
4183 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4186 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4190 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4192 // `let <pat> = __next`
4193 let pat = self.lower_pat(pat);
4194 let pat_let = self.stmt_let_pat(
4198 hir::LocalSource::ForLoopDesugar,
4201 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4202 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4203 let body_stmt = respan(
4205 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4208 let loop_block = P(self.block_all(
4210 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4214 // `[opt_ident]: loop { ... }`
4215 let loop_expr = hir::ExprKind::Loop(
4217 self.lower_label(opt_label),
4218 hir::LoopSource::ForLoop,
4220 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4221 let loop_expr = P(hir::Expr {
4226 attrs: ThinVec::new(),
4229 // `mut iter => { ... }`
4230 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4232 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4233 let into_iter_expr = {
4234 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4235 let into_iter = P(self.expr_std_path(
4236 head_sp, into_iter_path, None, ThinVec::new()));
4237 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4240 let match_expr = P(self.expr_match(
4244 hir::MatchSource::ForLoopDesugar,
4247 // `{ let _result = ...; _result }`
4248 // underscore prevents an unused_variables lint if the head diverges
4249 let result_ident = self.str_to_ident("_result");
4250 let (let_stmt, let_stmt_binding) =
4251 self.stmt_let(e.span, false, result_ident, match_expr);
4253 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4254 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4255 // add the attributes to the outer returned expr node
4256 return self.expr_block(block, e.attrs.clone());
4259 // Desugar ExprKind::Try
4261 ExprKind::Try(ref sub_expr) => {
4264 // match Try::into_result(<expr>) {
4265 // Ok(val) => #[allow(unreachable_code)] val,
4266 // Err(err) => #[allow(unreachable_code)]
4267 // // If there is an enclosing `catch {...}`
4268 // break 'catch_target Try::from_error(From::from(err)),
4270 // return Try::from_error(From::from(err)),
4274 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4276 // Try::into_result(<expr>)
4279 let sub_expr = self.lower_expr(sub_expr);
4281 let path = &["ops", "Try", "into_result"];
4282 let path = P(self.expr_std_path(
4283 unstable_span, path, None, ThinVec::new()));
4284 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4287 // #[allow(unreachable_code)]
4289 // allow(unreachable_code)
4291 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4292 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4293 let uc_nested = attr::mk_nested_word_item(uc_ident);
4294 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4296 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4298 let attrs = vec![attr];
4300 // Ok(val) => #[allow(unreachable_code)] val,
4302 let val_ident = self.str_to_ident("val");
4303 let val_pat = self.pat_ident(e.span, val_ident);
4304 let val_expr = P(self.expr_ident_with_attrs(
4308 ThinVec::from(attrs.clone()),
4310 let ok_pat = self.pat_ok(e.span, val_pat);
4312 self.arm(hir_vec![ok_pat], val_expr)
4315 // Err(err) => #[allow(unreachable_code)]
4316 // return Try::from_error(From::from(err)),
4318 let err_ident = self.str_to_ident("err");
4319 let err_local = self.pat_ident(e.span, err_ident);
4321 let path = &["convert", "From", "from"];
4322 let from = P(self.expr_std_path(
4323 e.span, path, None, ThinVec::new()));
4324 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4326 self.expr_call(e.span, from, hir_vec![err_expr])
4329 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4330 let thin_attrs = ThinVec::from(attrs);
4331 let catch_scope = self.catch_scopes.last().map(|x| *x);
4332 let ret_expr = if let Some(catch_node) = catch_scope {
4335 hir::ExprKind::Break(
4338 target_id: Ok(catch_node),
4340 Some(from_err_expr),
4345 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4348 let err_pat = self.pat_err(e.span, err_local);
4349 self.arm(hir_vec![err_pat], ret_expr)
4352 hir::ExprKind::Match(
4354 hir_vec![err_arm, ok_arm],
4355 hir::MatchSource::TryDesugar,
4359 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4362 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4369 attrs: e.attrs.clone(),
4373 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4374 smallvec![match s.node {
4375 StmtKind::Local(ref l) => {
4376 let (l, item_ids) = self.lower_local(l);
4377 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4379 .map(|item_id| Spanned {
4380 node: hir::StmtKind::Decl(
4382 node: hir::DeclKind::Item(item_id),
4385 self.next_id().node_id,
4391 node: hir::StmtKind::Decl(
4393 node: hir::DeclKind::Local(l),
4396 self.lower_node_id(s.id).node_id,
4402 StmtKind::Item(ref it) => {
4403 // Can only use the ID once.
4404 let mut id = Some(s.id);
4405 return self.lower_item_id(it)
4407 .map(|item_id| Spanned {
4408 node: hir::StmtKind::Decl(
4410 node: hir::DeclKind::Item(item_id),
4414 .map(|id| self.lower_node_id(id).node_id)
4415 .unwrap_or_else(|| self.next_id().node_id),
4421 StmtKind::Expr(ref e) => Spanned {
4422 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4425 StmtKind::Semi(ref e) => Spanned {
4426 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4429 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4433 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4435 CaptureBy::Value => hir::CaptureByValue,
4436 CaptureBy::Ref => hir::CaptureByRef,
4440 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4441 /// the address space of that item instead of the item currently being
4442 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4443 /// lower a `Visibility` value although we haven't lowered the owning
4444 /// `ImplItem` in question yet.
4445 fn lower_visibility(
4448 explicit_owner: Option<NodeId>,
4449 ) -> hir::Visibility {
4450 let node = match v.node {
4451 VisibilityKind::Public => hir::VisibilityKind::Public,
4452 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4453 VisibilityKind::Restricted { ref path, id } => {
4454 let lowered_id = if let Some(owner) = explicit_owner {
4455 self.lower_node_id_with_owner(id, owner)
4457 self.lower_node_id(id)
4459 hir::VisibilityKind::Restricted {
4460 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4461 id: lowered_id.node_id,
4462 hir_id: lowered_id.hir_id,
4465 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4467 respan(v.span, node)
4470 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4472 Defaultness::Default => hir::Defaultness::Default {
4473 has_value: has_value,
4475 Defaultness::Final => {
4477 hir::Defaultness::Final
4482 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4484 BlockCheckMode::Default => hir::DefaultBlock,
4485 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4489 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4491 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4492 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4493 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4494 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4498 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4500 CompilerGenerated => hir::CompilerGenerated,
4501 UserProvided => hir::UserProvided,
4505 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4507 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4508 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4512 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4514 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4515 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4519 // Helper methods for building HIR.
4521 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4530 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4532 id: self.next_id().node_id,
4536 is_shorthand: false,
4540 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4541 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4542 P(self.expr(span, expr_break, attrs))
4549 args: hir::HirVec<hir::Expr>,
4551 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4554 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4555 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4558 fn expr_ident_with_attrs(
4563 attrs: ThinVec<Attribute>,
4565 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4569 def: Def::Local(binding),
4570 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4574 self.expr(span, expr_path, attrs)
4577 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4578 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4584 components: &[&str],
4585 params: Option<P<hir::GenericArgs>>,
4586 attrs: ThinVec<Attribute>,
4588 let path = self.std_path(span, components, params, true);
4591 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4600 arms: hir::HirVec<hir::Arm>,
4601 source: hir::MatchSource,
4603 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4606 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4607 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4610 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4611 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4614 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4615 let LoweredNodeId { node_id, hir_id } = self.next_id();
4628 ex: Option<P<hir::Expr>>,
4630 source: hir::LocalSource,
4632 let LoweredNodeId { node_id, hir_id } = self.next_id();
4634 let local = P(hir::Local {
4641 attrs: ThinVec::new(),
4644 let decl = respan(sp, hir::DeclKind::Local(local));
4645 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4654 ) -> (hir::Stmt, NodeId) {
4655 let pat = if mutbl {
4656 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4658 self.pat_ident(sp, ident)
4660 let pat_id = pat.id;
4662 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4667 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4668 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4674 stmts: hir::HirVec<hir::Stmt>,
4675 expr: Option<P<hir::Expr>>,
4677 let LoweredNodeId { node_id, hir_id } = self.next_id();
4684 rules: hir::DefaultBlock,
4686 targeted_by_break: false,
4691 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4692 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4695 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4696 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4699 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4700 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4703 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4704 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4710 components: &[&str],
4711 subpats: hir::HirVec<P<hir::Pat>>,
4713 let path = self.std_path(span, components, None, true);
4714 let qpath = hir::QPath::Resolved(None, P(path));
4715 let pt = if subpats.is_empty() {
4716 hir::PatKind::Path(qpath)
4718 hir::PatKind::TupleStruct(qpath, subpats, None)
4723 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4724 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4727 fn pat_ident_binding_mode(
4731 bm: hir::BindingAnnotation,
4733 let LoweredNodeId { node_id, hir_id } = self.next_id();
4738 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4743 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4744 self.pat(span, hir::PatKind::Wild)
4747 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4748 let LoweredNodeId { node_id, hir_id } = self.next_id();
4757 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4758 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4759 /// The path is also resolved according to `is_value`.
4763 components: &[&str],
4764 params: Option<P<hir::GenericArgs>>,
4768 .resolve_str_path(span, self.crate_root, components, params, is_value)
4771 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4773 let node = match qpath {
4774 hir::QPath::Resolved(None, path) => {
4775 // Turn trait object paths into `TyKind::TraitObject` instead.
4776 if let Def::Trait(_) = path.def {
4777 let principal = hir::PolyTraitRef {
4778 bound_generic_params: hir::HirVec::new(),
4779 trait_ref: hir::TraitRef {
4780 path: path.and_then(|path| path),
4782 hir_ref_id: id.hir_id,
4787 // The original ID is taken by the `PolyTraitRef`,
4788 // so the `Ty` itself needs a different one.
4789 id = self.next_id();
4790 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4792 hir::TyKind::Path(hir::QPath::Resolved(None, path))
4795 _ => hir::TyKind::Path(qpath),
4805 /// Invoked to create the lifetime argument for a type `&T`
4806 /// with no explicit lifetime.
4807 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4808 match self.anonymous_lifetime_mode {
4809 // Intercept when we are in an impl header and introduce an in-band lifetime.
4810 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4812 AnonymousLifetimeMode::CreateParameter => {
4813 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4815 id: self.next_id().node_id,
4817 name: hir::LifetimeName::Param(fresh_name),
4821 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4825 /// Invoked to create the lifetime argument(s) for a path like
4826 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4827 /// sorts of cases are deprecated. This may therefore report a warning or an
4828 /// error, depending on the mode.
4829 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4830 match self.anonymous_lifetime_mode {
4831 // NB. We intentionally ignore the create-parameter mode here
4832 // and instead "pass through" to resolve-lifetimes, which will then
4833 // report an error. This is because we don't want to support
4834 // impl elision for deprecated forms like
4836 // impl Foo for std::cell::Ref<u32> // note lack of '_
4837 AnonymousLifetimeMode::CreateParameter => {}
4839 // This is the normal case.
4840 AnonymousLifetimeMode::PassThrough => {}
4844 .map(|_| self.new_implicit_lifetime(span))
4848 /// Invoked to create the lifetime argument(s) for an elided trait object
4849 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4850 /// when the bound is written, even if it is written with `'_` like in
4851 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4852 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4853 match self.anonymous_lifetime_mode {
4854 // NB. We intentionally ignore the create-parameter mode here.
4855 // and instead "pass through" to resolve-lifetimes, which will apply
4856 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4857 // do not act like other elided lifetimes. In other words, given this:
4859 // impl Foo for Box<dyn Debug>
4861 // we do not introduce a fresh `'_` to serve as the bound, but instead
4862 // ultimately translate to the equivalent of:
4864 // impl Foo for Box<dyn Debug + 'static>
4866 // `resolve_lifetime` has the code to make that happen.
4867 AnonymousLifetimeMode::CreateParameter => {}
4869 // This is the normal case.
4870 AnonymousLifetimeMode::PassThrough => {}
4873 self.new_implicit_lifetime(span)
4876 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4878 id: self.next_id().node_id,
4880 name: hir::LifetimeName::Implicit,
4884 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4885 self.sess.buffer_lint_with_diagnostic(
4886 builtin::BARE_TRAIT_OBJECTS,
4889 "trait objects without an explicit `dyn` are deprecated",
4890 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4894 fn wrap_in_try_constructor(
4896 method: &'static str,
4898 unstable_span: Span,
4900 let path = &["ops", "Try", method];
4901 let from_err = P(self.expr_std_path(unstable_span, path, None,
4903 P(self.expr_call(e.span, from_err, hir_vec![e]))
4906 fn check_self_struct_ctor_feature(&self, qp: &hir::QPath) {
4907 if let hir::QPath::Resolved(_, ref p) = qp {
4908 if p.segments.len() == 1 &&
4909 p.segments[0].ident.name == keywords::SelfType.name() &&
4910 !self.sess.features_untracked().self_struct_ctor {
4911 emit_feature_err(&self.sess.parse_sess, "self_struct_ctor",
4912 p.span, GateIssue::Language,
4913 "`Self` struct constructors are unstable");
4919 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4920 // Sorting by span ensures that we get things in order within a
4921 // file, and also puts the files in a sensible order.
4922 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4923 body_ids.sort_by_key(|b| bodies[b].value.span);