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::small_vec::OneVector;
56 use rustc_data_structures::thin_vec::ThinVec;
58 use util::common::FN_OUTPUT_NAME;
59 use util::nodemap::{DefIdMap, NodeMap};
61 use std::collections::BTreeMap;
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 OneVector<hir::ItemId> }
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, itctx: ImplTraitContext) -> hir::TypeBinding {
1099 id: self.lower_node_id(b.id).node_id,
1101 ty: self.lower_ty(&b.ty, itctx),
1106 fn lower_generic_arg(&mut self,
1107 arg: &ast::GenericArg,
1108 itctx: ImplTraitContext)
1109 -> hir::GenericArg {
1111 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1112 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1116 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1117 P(self.lower_ty_direct(t, itctx))
1120 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext) -> hir::Ty {
1121 let kind = match t.node {
1122 TyKind::Infer => hir::TyKind::Infer,
1123 TyKind::Err => hir::TyKind::Err,
1124 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1125 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1126 TyKind::Rptr(ref region, ref mt) => {
1127 let span = t.span.shrink_to_lo();
1128 let lifetime = match *region {
1129 Some(ref lt) => self.lower_lifetime(lt),
1130 None => self.elided_ref_lifetime(span),
1132 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1134 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1137 this.with_anonymous_lifetime_mode(
1138 AnonymousLifetimeMode::PassThrough,
1140 hir::TyKind::BareFn(P(hir::BareFnTy {
1141 generic_params: this.lower_generic_params(
1144 ImplTraitContext::Disallowed,
1146 unsafety: this.lower_unsafety(f.unsafety),
1148 decl: this.lower_fn_decl(&f.decl, None, false, None),
1149 arg_names: this.lower_fn_args_to_names(&f.decl),
1155 TyKind::Never => hir::TyKind::Never,
1156 TyKind::Tup(ref tys) => {
1157 hir::TyKind::Tup(tys.iter().map(|ty| {
1158 self.lower_ty_direct(ty, itctx.reborrow())
1161 TyKind::Paren(ref ty) => {
1162 return self.lower_ty_direct(ty, itctx);
1164 TyKind::Path(ref qself, ref path) => {
1165 let id = self.lower_node_id(t.id);
1166 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1167 let ty = self.ty_path(id, t.span, qpath);
1168 if let hir::TyKind::TraitObject(..) = ty.node {
1169 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1173 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1176 def: self.expect_full_def(t.id),
1177 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1181 TyKind::Array(ref ty, ref length) => {
1182 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1184 TyKind::Typeof(ref expr) => {
1185 hir::TyKind::Typeof(self.lower_anon_const(expr))
1187 TyKind::TraitObject(ref bounds, kind) => {
1188 let mut lifetime_bound = None;
1191 .filter_map(|bound| match *bound {
1192 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1193 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1195 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1196 GenericBound::Outlives(ref lifetime) => {
1197 if lifetime_bound.is_none() {
1198 lifetime_bound = Some(self.lower_lifetime(lifetime));
1204 let lifetime_bound =
1205 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1206 if kind != TraitObjectSyntax::Dyn {
1207 self.maybe_lint_bare_trait(t.span, t.id, false);
1209 hir::TyKind::TraitObject(bounds, lifetime_bound)
1211 TyKind::ImplTrait(def_node_id, ref bounds) => {
1214 ImplTraitContext::Existential(fn_def_id) => {
1215 self.lower_existential_impl_trait(
1216 span, fn_def_id, def_node_id,
1217 |this| this.lower_param_bounds(bounds, itctx),
1220 ImplTraitContext::Universal(in_band_ty_params) => {
1221 self.lower_node_id(def_node_id);
1222 // Add a definition for the in-band Param
1223 let def_index = self
1226 .opt_def_index(def_node_id)
1229 let hir_bounds = self.lower_param_bounds(
1231 ImplTraitContext::Universal(in_band_ty_params),
1233 // Set the name to `impl Bound1 + Bound2`
1234 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1235 in_band_ty_params.push(hir::GenericParam {
1237 name: ParamName::Plain(ident),
1238 pure_wrt_drop: false,
1242 kind: hir::GenericParamKind::Type {
1244 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1248 hir::TyKind::Path(hir::QPath::Resolved(
1252 def: Def::TyParam(DefId::local(def_index)),
1253 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1257 ImplTraitContext::Disallowed => {
1258 let allowed_in = if self.sess.features_untracked()
1259 .impl_trait_in_bindings {
1260 "bindings or function and inherent method return types"
1262 "function and inherent method return types"
1268 "`impl Trait` not allowed outside of {}",
1275 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1278 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1287 fn lower_existential_impl_trait(
1290 fn_def_id: Option<DefId>,
1291 exist_ty_node_id: NodeId,
1292 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1294 // Make sure we know that some funky desugaring has been going on here.
1295 // This is a first: there is code in other places like for loop
1296 // desugaring that explicitly states that we don't want to track that.
1297 // Not tracking it makes lints in rustc and clippy very fragile as
1298 // frequently opened issues show.
1299 let exist_ty_span = self.allow_internal_unstable(
1300 CompilerDesugaringKind::ExistentialReturnType,
1304 let exist_ty_def_index = self
1307 .opt_def_index(exist_ty_node_id)
1310 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1312 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1314 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1320 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1321 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1322 generics: hir::Generics {
1323 params: lifetime_defs,
1324 where_clause: hir::WhereClause {
1325 id: lctx.next_id().node_id,
1326 predicates: Vec::new().into(),
1331 impl_trait_fn: fn_def_id,
1333 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1334 // Generate an `existential type Foo: Trait;` declaration
1335 trace!("creating existential type with id {:#?}", exist_ty_id);
1337 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1338 let exist_ty_item = hir::Item {
1339 id: exist_ty_id.node_id,
1340 hir_id: exist_ty_id.hir_id,
1341 name: keywords::Invalid.name(),
1342 attrs: Default::default(),
1343 node: exist_ty_item_kind,
1344 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1345 span: exist_ty_span,
1348 // Insert the item into the global list. This usually happens
1349 // automatically for all AST items. But this existential type item
1350 // does not actually exist in the AST.
1351 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1353 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1354 let path = P(hir::Path {
1355 span: exist_ty_span,
1356 def: Def::Existential(DefId::local(exist_ty_def_index)),
1357 segments: hir_vec![hir::PathSegment {
1359 ident: Ident::new(keywords::Invalid.name(), exist_ty_span),
1360 args: Some(P(hir::GenericArgs {
1361 parenthesized: false,
1362 bindings: HirVec::new(),
1367 hir::TyKind::Path(hir::QPath::Resolved(None, path))
1371 fn lifetimes_from_impl_trait_bounds(
1373 exist_ty_id: NodeId,
1374 parent_index: DefIndex,
1375 bounds: &hir::GenericBounds,
1376 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1377 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1378 // appear in the bounds, excluding lifetimes that are created within the bounds.
1379 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1380 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1381 context: &'r mut LoweringContext<'a>,
1383 exist_ty_id: NodeId,
1384 collect_elided_lifetimes: bool,
1385 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1386 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1387 output_lifetimes: Vec<hir::GenericArg>,
1388 output_lifetime_params: Vec<hir::GenericParam>,
1391 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1392 fn nested_visit_map<'this>(
1394 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1395 hir::intravisit::NestedVisitorMap::None
1398 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1399 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1400 if parameters.parenthesized {
1401 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1402 self.collect_elided_lifetimes = false;
1403 hir::intravisit::walk_generic_args(self, span, parameters);
1404 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1406 hir::intravisit::walk_generic_args(self, span, parameters);
1410 fn visit_ty(&mut self, t: &'v hir::Ty) {
1411 // Don't collect elided lifetimes used inside of `fn()` syntax
1412 if let hir::TyKind::BareFn(_) = t.node {
1413 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1414 self.collect_elided_lifetimes = false;
1416 // Record the "stack height" of `for<'a>` lifetime bindings
1417 // to be able to later fully undo their introduction.
1418 let old_len = self.currently_bound_lifetimes.len();
1419 hir::intravisit::walk_ty(self, t);
1420 self.currently_bound_lifetimes.truncate(old_len);
1422 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1424 hir::intravisit::walk_ty(self, t)
1428 fn visit_poly_trait_ref(
1430 trait_ref: &'v hir::PolyTraitRef,
1431 modifier: hir::TraitBoundModifier,
1433 // Record the "stack height" of `for<'a>` lifetime bindings
1434 // to be able to later fully undo their introduction.
1435 let old_len = self.currently_bound_lifetimes.len();
1436 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1437 self.currently_bound_lifetimes.truncate(old_len);
1440 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1441 // Record the introduction of 'a in `for<'a> ...`
1442 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1443 // Introduce lifetimes one at a time so that we can handle
1444 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1445 let lt_name = hir::LifetimeName::Param(param.name);
1446 self.currently_bound_lifetimes.push(lt_name);
1449 hir::intravisit::walk_generic_param(self, param);
1452 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1453 let name = match lifetime.name {
1454 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1455 if self.collect_elided_lifetimes {
1456 // Use `'_` for both implicit and underscore lifetimes in
1457 // `abstract type Foo<'_>: SomeTrait<'_>;`
1458 hir::LifetimeName::Underscore
1463 hir::LifetimeName::Param(_) => lifetime.name,
1464 hir::LifetimeName::Static => return,
1467 if !self.currently_bound_lifetimes.contains(&name)
1468 && !self.already_defined_lifetimes.contains(&name) {
1469 self.already_defined_lifetimes.insert(name);
1471 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1472 id: self.context.next_id().node_id,
1473 span: lifetime.span,
1477 // We need to manually create the ids here, because the
1478 // definitions will go into the explicit `existential type`
1479 // declaration and thus need to have their owner set to that item
1480 let def_node_id = self.context.sess.next_node_id();
1481 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1482 self.context.resolver.definitions().create_def_with_parent(
1485 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1486 DefIndexAddressSpace::High,
1491 let name = match name {
1492 hir::LifetimeName::Underscore => {
1493 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident())
1495 hir::LifetimeName::Param(param_name) => param_name,
1496 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1499 self.output_lifetime_params.push(hir::GenericParam {
1502 span: lifetime.span,
1503 pure_wrt_drop: false,
1506 kind: hir::GenericParamKind::Lifetime {
1514 let mut lifetime_collector = ImplTraitLifetimeCollector {
1516 parent: parent_index,
1518 collect_elided_lifetimes: true,
1519 currently_bound_lifetimes: Vec::new(),
1520 already_defined_lifetimes: FxHashSet::default(),
1521 output_lifetimes: Vec::new(),
1522 output_lifetime_params: Vec::new(),
1525 for bound in bounds {
1526 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1530 lifetime_collector.output_lifetimes.into(),
1531 lifetime_collector.output_lifetime_params.into(),
1535 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1540 .map(|x| self.lower_foreign_item(x))
1545 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1552 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1554 node: hir::VariantKind {
1555 name: v.node.ident.name,
1556 attrs: self.lower_attrs(&v.node.attrs),
1557 data: self.lower_variant_data(&v.node.data),
1558 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1567 qself: &Option<QSelf>,
1569 param_mode: ParamMode,
1570 mut itctx: ImplTraitContext,
1572 let qself_position = qself.as_ref().map(|q| q.position);
1573 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1575 let resolution = self.resolver
1577 .unwrap_or(PathResolution::new(Def::Err));
1579 let proj_start = p.segments.len() - resolution.unresolved_segments();
1580 let path = P(hir::Path {
1581 def: resolution.base_def(),
1582 segments: p.segments[..proj_start]
1585 .map(|(i, segment)| {
1586 let param_mode = match (qself_position, param_mode) {
1587 (Some(j), ParamMode::Optional) if i < j => {
1588 // This segment is part of the trait path in a
1589 // qualified path - one of `a`, `b` or `Trait`
1590 // in `<X as a::b::Trait>::T::U::method`.
1596 // Figure out if this is a type/trait segment,
1597 // which may need lifetime elision performed.
1598 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1599 krate: def_id.krate,
1600 index: this.def_key(def_id).parent.expect("missing parent"),
1602 let type_def_id = match resolution.base_def() {
1603 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1604 Some(parent_def_id(self, def_id))
1606 Def::Variant(def_id) if i + 1 == proj_start => {
1607 Some(parent_def_id(self, def_id))
1610 | Def::Union(def_id)
1612 | Def::TyAlias(def_id)
1613 | Def::Trait(def_id) if i + 1 == proj_start =>
1619 let parenthesized_generic_args = match resolution.base_def() {
1620 // `a::b::Trait(Args)`
1621 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1622 // `a::b::Trait(Args)::TraitItem`
1623 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1624 if i + 2 == proj_start =>
1626 ParenthesizedGenericArgs::Ok
1628 // Avoid duplicated errors
1629 Def::Err => ParenthesizedGenericArgs::Ok,
1635 | Def::Variant(..) if i + 1 == proj_start =>
1637 ParenthesizedGenericArgs::Err
1639 // A warning for now, for compatibility reasons
1640 _ => ParenthesizedGenericArgs::Warn,
1643 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1644 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1647 assert!(!def_id.is_local());
1649 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1650 let n = item_generics.own_counts().lifetimes;
1651 self.type_def_lifetime_params.insert(def_id, n);
1654 self.lower_path_segment(
1659 parenthesized_generic_args,
1667 // Simple case, either no projections, or only fully-qualified.
1668 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1669 if resolution.unresolved_segments() == 0 {
1670 return hir::QPath::Resolved(qself, path);
1673 // Create the innermost type that we're projecting from.
1674 let mut ty = if path.segments.is_empty() {
1675 // If the base path is empty that means there exists a
1676 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1677 qself.expect("missing QSelf for <T>::...")
1679 // Otherwise, the base path is an implicit `Self` type path,
1680 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1681 // `<I as Iterator>::Item::default`.
1682 let new_id = self.next_id();
1683 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1686 // Anything after the base path are associated "extensions",
1687 // out of which all but the last one are associated types,
1688 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1689 // * base path is `std::vec::Vec<T>`
1690 // * "extensions" are `IntoIter`, `Item` and `clone`
1691 // * type nodes are:
1692 // 1. `std::vec::Vec<T>` (created above)
1693 // 2. `<std::vec::Vec<T>>::IntoIter`
1694 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1695 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1696 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1697 let segment = P(self.lower_path_segment(
1702 ParenthesizedGenericArgs::Warn,
1705 let qpath = hir::QPath::TypeRelative(ty, segment);
1707 // It's finished, return the extension of the right node type.
1708 if i == p.segments.len() - 1 {
1712 // Wrap the associated extension in another type node.
1713 let new_id = self.next_id();
1714 ty = P(self.ty_path(new_id, p.span, qpath));
1717 // Should've returned in the for loop above.
1720 "lower_qpath: no final extension segment in {}..{}",
1726 fn lower_path_extra(
1730 ident: Option<Ident>,
1731 param_mode: ParamMode,
1735 segments: p.segments
1738 self.lower_path_segment(
1743 ParenthesizedGenericArgs::Err,
1744 ImplTraitContext::Disallowed,
1747 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1753 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1754 let def = self.expect_full_def(id);
1755 self.lower_path_extra(def, p, None, param_mode)
1758 fn lower_path_segment(
1761 segment: &PathSegment,
1762 param_mode: ParamMode,
1763 expected_lifetimes: usize,
1764 parenthesized_generic_args: ParenthesizedGenericArgs,
1765 itctx: ImplTraitContext,
1766 ) -> hir::PathSegment {
1767 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1768 let msg = "parenthesized parameters may only be used with a trait";
1769 match **generic_args {
1770 GenericArgs::AngleBracketed(ref data) => {
1771 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1773 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1774 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1775 ParenthesizedGenericArgs::Warn => {
1776 self.sess.buffer_lint(
1777 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1782 (hir::GenericArgs::none(), true)
1784 ParenthesizedGenericArgs::Err => {
1785 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1786 .span_label(data.span, "only traits may use parentheses")
1788 (hir::GenericArgs::none(), true)
1793 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1796 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1797 GenericArg::Lifetime(_) => true,
1800 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1801 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1802 if !generic_args.parenthesized && !has_lifetimes {
1804 self.elided_path_lifetimes(path_span, expected_lifetimes)
1806 .map(|lt| GenericArg::Lifetime(lt))
1807 .chain(generic_args.args.into_iter())
1809 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1810 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1811 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1812 let no_bindings = generic_args.bindings.is_empty();
1813 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1814 // If there are no (non-implicit) generic args or associated-type
1815 // bindings, our suggestion includes the angle brackets
1816 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1818 // Otherwise—sorry, this is kind of gross—we need to infer the
1819 // place to splice in the `'_, ` from the generics that do exist
1820 let first_generic_span = first_generic_span
1821 .expect("already checked that type args or bindings exist");
1822 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1824 self.sess.buffer_lint_with_diagnostic(
1825 ELIDED_LIFETIMES_IN_PATHS,
1828 "hidden lifetime parameters in types are deprecated",
1829 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1830 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1836 hir::PathSegment::new(
1843 fn lower_angle_bracketed_parameter_data(
1845 data: &AngleBracketedArgs,
1846 param_mode: ParamMode,
1847 mut itctx: ImplTraitContext,
1848 ) -> (hir::GenericArgs, bool) {
1849 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1850 let has_types = args.iter().any(|arg| match arg {
1851 ast::GenericArg::Type(_) => true,
1855 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1856 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1857 parenthesized: false,
1859 !has_types && param_mode == ParamMode::Optional)
1862 fn lower_parenthesized_parameter_data(
1864 data: &ParenthesisedArgs,
1865 ) -> (hir::GenericArgs, bool) {
1866 // Switch to `PassThrough` mode for anonymous lifetimes: this
1867 // means that we permit things like `&Ref<T>`, where `Ref` has
1868 // a hidden lifetime parameter. This is needed for backwards
1869 // compatibility, even in contexts like an impl header where
1870 // we generally don't permit such things (see #51008).
1871 self.with_anonymous_lifetime_mode(
1872 AnonymousLifetimeMode::PassThrough,
1874 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1875 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1876 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1877 let mk_tup = |this: &mut Self, tys, span| {
1878 let LoweredNodeId { node_id, hir_id } = this.next_id();
1879 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1884 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1887 id: this.next_id().node_id,
1888 ident: Ident::from_str(FN_OUTPUT_NAME),
1891 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1892 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1893 span: output.as_ref().map_or(span, |ty| ty.span),
1896 parenthesized: true,
1904 fn lower_local(&mut self, l: &Local) -> (P<hir::Local>, OneVector<hir::ItemId>) {
1905 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1906 let mut ids = OneVector::<hir::ItemId>::new();
1907 if self.sess.features_untracked().impl_trait_in_bindings {
1908 if let Some(ref ty) = l.ty {
1909 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1910 visitor.visit_ty(ty);
1913 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
1919 .map(|t| self.lower_ty(t,
1920 if self.sess.features_untracked().impl_trait_in_bindings {
1921 ImplTraitContext::Existential(Some(parent_def_id))
1923 ImplTraitContext::Disallowed
1926 pat: self.lower_pat(&l.pat),
1927 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1929 attrs: l.attrs.clone(),
1930 source: hir::LocalSource::Normal,
1934 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1936 Mutability::Mutable => hir::MutMutable,
1937 Mutability::Immutable => hir::MutImmutable,
1941 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1942 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1946 pat: self.lower_pat(&arg.pat),
1950 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1953 .map(|arg| match arg.pat.node {
1954 PatKind::Ident(_, ident, _) => ident,
1955 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1960 // Lowers a function declaration.
1962 // decl: the unlowered (ast) function declaration.
1963 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1964 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1965 // make_ret_async is also `Some`.
1966 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1967 // This guards against trait declarations and implementations where impl Trait is
1969 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1970 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1971 // return type impl Trait item.
1975 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
1976 impl_trait_return_allow: bool,
1977 make_ret_async: Option<NodeId>,
1978 ) -> P<hir::FnDecl> {
1979 let inputs = decl.inputs
1982 if let Some((_, ref mut ibty)) = in_band_ty_params {
1983 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
1985 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
1988 .collect::<HirVec<_>>();
1990 let output = if let Some(ret_id) = make_ret_async {
1991 self.lower_async_fn_ret_ty(
1994 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
1999 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2000 Some((def_id, _)) if impl_trait_return_allow => {
2001 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(Some(def_id))))
2003 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2005 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2012 variadic: decl.variadic,
2013 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
2014 TyKind::ImplicitSelf => true,
2015 TyKind::Rptr(_, ref mt) => mt.ty.node.is_implicit_self(),
2021 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
2023 // fn_span: the span of the async function declaration. Used for error reporting.
2024 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2025 // output: unlowered output type (`T` in `-> T`)
2026 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2027 fn lower_async_fn_ret_ty(
2030 output: &FunctionRetTy,
2032 return_impl_trait_id: NodeId,
2033 ) -> hir::FunctionRetTy {
2034 // Get lifetimes used in the input arguments to the function. Our output type must also
2035 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
2036 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
2037 // is a subset of the other. We really want some new lifetime that is a subset of all input
2038 // lifetimes, but that doesn't exist at the moment.
2040 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
2041 context: &'r mut LoweringContext<'a>,
2042 // Lifetimes bound by HRTB
2043 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2044 // Whether to count elided lifetimes.
2045 // Disabled inside of `Fn` or `fn` syntax.
2046 collect_elided_lifetimes: bool,
2047 // The lifetime found.
2048 // Multiple different or elided lifetimes cannot appear in async fn for now.
2049 output_lifetime: Option<(hir::LifetimeName, Span)>,
2052 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2053 fn nested_visit_map<'this>(
2055 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2056 hir::intravisit::NestedVisitorMap::None
2059 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2060 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2061 if parameters.parenthesized {
2062 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2063 self.collect_elided_lifetimes = false;
2064 hir::intravisit::walk_generic_args(self, span, parameters);
2065 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2067 hir::intravisit::walk_generic_args(self, span, parameters);
2071 fn visit_ty(&mut self, t: &'v hir::Ty) {
2072 // Don't collect elided lifetimes used inside of `fn()` syntax
2073 if let &hir::TyKind::BareFn(_) = &t.node {
2074 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2075 self.collect_elided_lifetimes = false;
2077 // Record the "stack height" of `for<'a>` lifetime bindings
2078 // to be able to later fully undo their introduction.
2079 let old_len = self.currently_bound_lifetimes.len();
2080 hir::intravisit::walk_ty(self, t);
2081 self.currently_bound_lifetimes.truncate(old_len);
2083 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2085 hir::intravisit::walk_ty(self, t);
2089 fn visit_poly_trait_ref(
2091 trait_ref: &'v hir::PolyTraitRef,
2092 modifier: hir::TraitBoundModifier,
2094 // Record the "stack height" of `for<'a>` lifetime bindings
2095 // to be able to later fully undo their introduction.
2096 let old_len = self.currently_bound_lifetimes.len();
2097 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2098 self.currently_bound_lifetimes.truncate(old_len);
2101 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2102 // Record the introduction of 'a in `for<'a> ...`
2103 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2104 // Introduce lifetimes one at a time so that we can handle
2105 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2106 let lt_name = hir::LifetimeName::Param(param.name);
2107 self.currently_bound_lifetimes.push(lt_name);
2110 hir::intravisit::walk_generic_param(self, param);
2113 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2114 let name = match lifetime.name {
2115 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2116 if self.collect_elided_lifetimes {
2117 // Use `'_` for both implicit and underscore lifetimes in
2118 // `abstract type Foo<'_>: SomeTrait<'_>;`
2119 hir::LifetimeName::Underscore
2124 hir::LifetimeName::Param(_) => lifetime.name,
2125 hir::LifetimeName::Static => return,
2128 if !self.currently_bound_lifetimes.contains(&name) {
2129 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2130 // We don't currently have a reliable way to desugar `async fn` with
2131 // multiple potentially unrelated input lifetimes into
2132 // `-> impl Trait + 'lt`, so we report an error in this case.
2133 if current_lt_name != name {
2136 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2138 "multiple different lifetimes used in arguments of `async fn`",
2140 .span_label(current_lt_span, "first lifetime here")
2141 .span_label(lifetime.span, "different lifetime here")
2142 .help("`async fn` can only accept borrowed values \
2143 with identical lifetimes")
2145 } else if current_lt_name.is_elided() && name.is_elided() {
2148 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2150 "multiple elided lifetimes used in arguments of `async fn`",
2152 .span_label(current_lt_span, "first lifetime here")
2153 .span_label(lifetime.span, "different lifetime here")
2154 .help("consider giving these arguments named lifetimes")
2158 self.output_lifetime = Some((name, lifetime.span));
2164 let bound_lifetime = {
2165 let mut lifetime_collector = AsyncFnLifetimeCollector {
2167 currently_bound_lifetimes: Vec::new(),
2168 collect_elided_lifetimes: true,
2169 output_lifetime: None,
2173 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2175 lifetime_collector.output_lifetime
2178 let span = match output {
2179 FunctionRetTy::Ty(ty) => ty.span,
2180 FunctionRetTy::Default(span) => *span,
2183 let impl_trait_ty = self.lower_existential_impl_trait(
2184 span, Some(fn_def_id), return_impl_trait_id, |this| {
2185 let output_ty = match output {
2186 FunctionRetTy::Ty(ty) => {
2187 this.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2189 FunctionRetTy::Default(span) => {
2190 let LoweredNodeId { node_id, hir_id } = this.next_id();
2194 node: hir::TyKind::Tup(hir_vec![]),
2201 let future_params = P(hir::GenericArgs {
2203 bindings: hir_vec![hir::TypeBinding {
2204 ident: Ident::from_str(FN_OUTPUT_NAME),
2206 id: this.next_id().node_id,
2209 parenthesized: false,
2213 this.std_path(span, &["future", "Future"], Some(future_params), false);
2215 let LoweredNodeId { node_id, hir_id } = this.next_id();
2216 let mut bounds = vec![
2217 hir::GenericBound::Trait(
2219 trait_ref: hir::TraitRef {
2224 bound_generic_params: hir_vec![],
2227 hir::TraitBoundModifier::None
2231 if let Some((name, span)) = bound_lifetime {
2232 bounds.push(hir::GenericBound::Outlives(
2233 hir::Lifetime { id: this.next_id().node_id, name, span }));
2236 hir::HirVec::from(bounds)
2239 let LoweredNodeId { node_id, hir_id } = self.next_id();
2240 let impl_trait_ty = P(hir::Ty {
2242 node: impl_trait_ty,
2247 hir::FunctionRetTy::Return(impl_trait_ty)
2250 fn lower_param_bound(
2253 itctx: ImplTraitContext,
2254 ) -> hir::GenericBound {
2256 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2257 self.lower_poly_trait_ref(ty, itctx),
2258 self.lower_trait_bound_modifier(modifier),
2260 GenericBound::Outlives(ref lifetime) => {
2261 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2266 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2267 let span = l.ident.span;
2269 ident if ident.name == keywords::StaticLifetime.name() =>
2270 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2271 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2272 match self.anonymous_lifetime_mode {
2273 AnonymousLifetimeMode::CreateParameter => {
2274 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2275 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2278 AnonymousLifetimeMode::PassThrough => {
2279 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2283 self.maybe_collect_in_band_lifetime(ident);
2284 let param_name = ParamName::Plain(ident);
2285 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2290 fn new_named_lifetime(
2294 name: hir::LifetimeName,
2295 ) -> hir::Lifetime {
2297 id: self.lower_node_id(id).node_id,
2303 fn lower_generic_params(
2305 params: &[GenericParam],
2306 add_bounds: &NodeMap<Vec<GenericBound>>,
2307 mut itctx: ImplTraitContext,
2308 ) -> hir::HirVec<hir::GenericParam> {
2309 params.iter().map(|param| {
2310 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2314 fn lower_generic_param(&mut self,
2315 param: &GenericParam,
2316 add_bounds: &NodeMap<Vec<GenericBound>>,
2317 mut itctx: ImplTraitContext)
2318 -> hir::GenericParam {
2319 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx.reborrow());
2321 GenericParamKind::Lifetime => {
2322 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2323 self.is_collecting_in_band_lifetimes = false;
2325 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2326 let param_name = match lt.name {
2327 hir::LifetimeName::Param(param_name) => param_name,
2328 _ => hir::ParamName::Plain(lt.name.ident()),
2330 let param = hir::GenericParam {
2334 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2335 attrs: self.lower_attrs(¶m.attrs),
2337 kind: hir::GenericParamKind::Lifetime { in_band: false }
2340 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2344 GenericParamKind::Type { ref default, .. } => {
2345 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2346 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2347 // Instead, use gensym("Self") to create a distinct name that looks the same.
2348 let ident = if param.ident.name == keywords::SelfType.name() {
2349 param.ident.gensym()
2354 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2355 if !add_bounds.is_empty() {
2356 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2357 bounds = bounds.into_iter()
2363 id: self.lower_node_id(param.id).node_id,
2364 name: hir::ParamName::Plain(ident),
2365 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2366 attrs: self.lower_attrs(¶m.attrs),
2369 kind: hir::GenericParamKind::Type {
2370 default: default.as_ref().map(|x| {
2371 self.lower_ty(x, ImplTraitContext::Disallowed)
2373 synthetic: param.attrs.iter()
2374 .filter(|attr| attr.check_name("rustc_synthetic"))
2375 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2385 generics: &Generics,
2386 itctx: ImplTraitContext)
2389 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2390 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2391 // paths where report_error is called are also the only paths that advance to after
2392 // the match statement, so the error reporting could probably just be moved there.
2393 let mut add_bounds: NodeMap<Vec<_>> = NodeMap();
2394 for pred in &generics.where_clause.predicates {
2395 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2396 'next_bound: for bound in &bound_pred.bounds {
2397 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2398 let report_error = |this: &mut Self| {
2399 this.diagnostic().span_err(
2400 bound_pred.bounded_ty.span,
2401 "`?Trait` bounds are only permitted at the \
2402 point where a type parameter is declared",
2405 // Check if the where clause type is a plain type parameter.
2406 match bound_pred.bounded_ty.node {
2407 TyKind::Path(None, ref path)
2408 if path.segments.len() == 1
2409 && bound_pred.bound_generic_params.is_empty() =>
2411 if let Some(Def::TyParam(def_id)) = self.resolver
2412 .get_resolution(bound_pred.bounded_ty.id)
2413 .map(|d| d.base_def())
2415 if let Some(node_id) =
2416 self.resolver.definitions().as_local_node_id(def_id)
2418 for param in &generics.params {
2420 GenericParamKind::Type { .. } => {
2421 if node_id == param.id {
2422 add_bounds.entry(param.id)
2424 .push(bound.clone());
2425 continue 'next_bound;
2435 _ => report_error(self),
2443 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2444 where_clause: self.lower_where_clause(&generics.where_clause),
2445 span: generics.span,
2449 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2451 id: self.lower_node_id(wc.id).node_id,
2452 predicates: wc.predicates
2454 .map(|predicate| self.lower_where_predicate(predicate))
2459 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2461 WherePredicate::BoundPredicate(WhereBoundPredicate {
2462 ref bound_generic_params,
2467 self.with_in_scope_lifetime_defs(
2468 &bound_generic_params,
2470 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2471 bound_generic_params: this.lower_generic_params(
2472 bound_generic_params,
2474 ImplTraitContext::Disallowed,
2476 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2479 .filter_map(|bound| match *bound {
2480 // Ignore `?Trait` bounds.
2481 // Tthey were copied into type parameters already.
2482 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2483 _ => Some(this.lower_param_bound(
2485 ImplTraitContext::Disallowed,
2494 WherePredicate::RegionPredicate(WhereRegionPredicate {
2498 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2500 lifetime: self.lower_lifetime(lifetime),
2501 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2503 WherePredicate::EqPredicate(WhereEqPredicate {
2508 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2509 id: self.lower_node_id(id).node_id,
2510 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2511 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2517 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2519 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2523 .map(|f| self.lower_struct_field(f))
2525 self.lower_node_id(id).node_id,
2527 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2531 .map(|f| self.lower_struct_field(f))
2533 self.lower_node_id(id).node_id,
2535 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2539 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2540 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2541 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2542 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2544 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2552 fn lower_poly_trait_ref(
2555 mut itctx: ImplTraitContext,
2556 ) -> hir::PolyTraitRef {
2557 let bound_generic_params =
2558 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2559 let trait_ref = self.with_parent_impl_lifetime_defs(
2560 &bound_generic_params,
2561 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2565 bound_generic_params,
2571 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2574 id: self.lower_node_id(f.id).node_id,
2575 ident: match f.ident {
2576 Some(ident) => ident,
2577 // FIXME(jseyfried) positional field hygiene
2578 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2580 vis: self.lower_visibility(&f.vis, None),
2581 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2582 attrs: self.lower_attrs(&f.attrs),
2586 fn lower_field(&mut self, f: &Field) -> hir::Field {
2588 id: self.next_id().node_id,
2590 expr: P(self.lower_expr(&f.expr)),
2592 is_shorthand: f.is_shorthand,
2596 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2598 ty: self.lower_ty(&mt.ty, itctx),
2599 mutbl: self.lower_mutability(mt.mutbl),
2603 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext)
2604 -> hir::GenericBounds {
2605 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2608 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2609 let mut expr = None;
2611 let mut stmts = vec![];
2613 for (index, stmt) in b.stmts.iter().enumerate() {
2614 if index == b.stmts.len() - 1 {
2615 if let StmtKind::Expr(ref e) = stmt.node {
2616 expr = Some(P(self.lower_expr(e)));
2618 stmts.extend(self.lower_stmt(stmt));
2621 stmts.extend(self.lower_stmt(stmt));
2625 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2630 stmts: stmts.into(),
2632 rules: self.lower_block_check_mode(&b.rules),
2635 recovered: b.recovered,
2639 fn lower_async_body(
2645 self.lower_body(Some(decl), |this| {
2646 if let IsAsync::Async { closure_id, .. } = asyncness {
2647 let async_expr = this.make_async_expr(
2648 CaptureBy::Value, closure_id, None,
2650 let body = this.lower_block(body, false);
2651 this.expr_block(body, ThinVec::new())
2653 this.expr(body.span, async_expr, ThinVec::new())
2655 let body = this.lower_block(body, false);
2656 this.expr_block(body, ThinVec::new())
2665 attrs: &hir::HirVec<Attribute>,
2666 vis: &mut hir::Visibility,
2668 ) -> hir::ItemKind {
2670 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2671 ItemKind::Use(ref use_tree) => {
2672 // Start with an empty prefix
2675 span: use_tree.span,
2678 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2680 ItemKind::Static(ref t, m, ref e) => {
2681 let value = self.lower_body(None, |this| this.lower_expr(e));
2682 hir::ItemKind::Static(
2685 if self.sess.features_untracked().impl_trait_in_bindings {
2686 ImplTraitContext::Existential(None)
2688 ImplTraitContext::Disallowed
2691 self.lower_mutability(m),
2695 ItemKind::Const(ref t, ref e) => {
2696 let value = self.lower_body(None, |this| this.lower_expr(e));
2697 hir::ItemKind::Const(
2700 if self.sess.features_untracked().impl_trait_in_bindings {
2701 ImplTraitContext::Existential(None)
2703 ImplTraitContext::Disallowed
2709 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2710 let fn_def_id = self.resolver.definitions().local_def_id(id);
2711 self.with_new_scopes(|this| {
2712 // Note: we don't need to change the return type from `T` to
2713 // `impl Future<Output = T>` here because lower_body
2714 // only cares about the input argument patterns in the function
2715 // declaration (decl), not the return types.
2716 let body_id = this.lower_async_body(decl, header.asyncness, body);
2718 let (generics, fn_decl) = this.add_in_band_defs(
2721 AnonymousLifetimeMode::PassThrough,
2722 |this, idty| this.lower_fn_decl(
2724 Some((fn_def_id, idty)),
2726 header.asyncness.opt_return_id()
2732 this.lower_fn_header(header),
2738 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2739 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2740 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2741 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2742 self.lower_ty(t, ImplTraitContext::Disallowed),
2743 self.lower_generics(generics, ImplTraitContext::Disallowed),
2745 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2746 generics: self.lower_generics(generics, ImplTraitContext::Disallowed),
2747 bounds: self.lower_param_bounds(b, ImplTraitContext::Disallowed),
2748 impl_trait_fn: None,
2750 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2752 variants: enum_definition
2755 .map(|x| self.lower_variant(x))
2758 self.lower_generics(generics, ImplTraitContext::Disallowed),
2760 ItemKind::Struct(ref struct_def, ref generics) => {
2761 let struct_def = self.lower_variant_data(struct_def);
2762 hir::ItemKind::Struct(
2764 self.lower_generics(generics, ImplTraitContext::Disallowed),
2767 ItemKind::Union(ref vdata, ref generics) => {
2768 let vdata = self.lower_variant_data(vdata);
2769 hir::ItemKind::Union(
2771 self.lower_generics(generics, ImplTraitContext::Disallowed),
2783 let def_id = self.resolver.definitions().local_def_id(id);
2785 // Lower the "impl header" first. This ordering is important
2786 // for in-band lifetimes! Consider `'a` here:
2788 // impl Foo<'a> for u32 {
2789 // fn method(&'a self) { .. }
2792 // Because we start by lowering the `Foo<'a> for u32`
2793 // part, we will add `'a` to the list of generics on
2794 // the impl. When we then encounter it later in the
2795 // method, it will not be considered an in-band
2796 // lifetime to be added, but rather a reference to a
2798 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2801 AnonymousLifetimeMode::CreateParameter,
2803 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2804 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2807 if let Some(ref trait_ref) = trait_ref {
2808 if let Def::Trait(def_id) = trait_ref.path.def {
2809 this.trait_impls.entry(def_id).or_default().push(id);
2813 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2815 (trait_ref, lowered_ty)
2819 let new_impl_items = self.with_in_scope_lifetime_defs(
2820 &ast_generics.params,
2824 .map(|item| this.lower_impl_item_ref(item))
2829 hir::ItemKind::Impl(
2830 self.lower_unsafety(unsafety),
2831 self.lower_impl_polarity(polarity),
2832 self.lower_defaultness(defaultness, true /* [1] */),
2839 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2840 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2843 .map(|item| self.lower_trait_item_ref(item))
2845 hir::ItemKind::Trait(
2846 self.lower_is_auto(is_auto),
2847 self.lower_unsafety(unsafety),
2848 self.lower_generics(generics, ImplTraitContext::Disallowed),
2853 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2854 self.lower_generics(generics, ImplTraitContext::Disallowed),
2855 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2857 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2860 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2861 // not cause an assertion failure inside the `lower_defaultness` function
2869 vis: &mut hir::Visibility,
2871 attrs: &hir::HirVec<Attribute>,
2872 ) -> hir::ItemKind {
2873 let path = &tree.prefix;
2876 UseTreeKind::Simple(rename, id1, id2) => {
2877 *name = tree.ident().name;
2879 // First apply the prefix to the path
2880 let mut path = Path {
2884 .chain(path.segments.iter())
2890 // Correctly resolve `self` imports
2891 if path.segments.len() > 1
2892 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2894 let _ = path.segments.pop();
2895 if rename.is_none() {
2896 *name = path.segments.last().unwrap().ident.name;
2900 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2901 let mut defs = self.expect_full_def_from_use(id);
2902 // we want to return *something* from this function, so hang onto the first item
2904 let ret_def = defs.next().unwrap_or(Def::Err);
2906 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2907 let vis = vis.clone();
2908 let name = name.clone();
2909 let span = path.span;
2910 self.resolver.definitions().create_def_with_parent(
2914 DefIndexAddressSpace::High,
2917 self.allocate_hir_id_counter(new_node_id, &path);
2919 self.with_hir_id_owner(new_node_id, |this| {
2920 let new_id = this.lower_node_id(new_node_id);
2921 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2922 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2923 let vis_kind = match vis.node {
2924 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2925 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2926 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2927 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2928 let id = this.next_id();
2929 hir::VisibilityKind::Restricted {
2931 // We are allocating a new NodeId here
2937 let vis = respan(vis.span, vis_kind);
2943 hir_id: new_id.hir_id,
2945 attrs: attrs.clone(),
2954 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2955 hir::ItemKind::Use(path, hir::UseKind::Single)
2957 UseTreeKind::Glob => {
2958 let path = P(self.lower_path(
2964 .chain(path.segments.iter())
2969 ParamMode::Explicit,
2971 hir::ItemKind::Use(path, hir::UseKind::Glob)
2973 UseTreeKind::Nested(ref trees) => {
2978 .chain(path.segments.iter())
2981 span: prefix.span.to(path.span),
2984 // Add all the nested PathListItems in the HIR
2985 for &(ref use_tree, id) in trees {
2986 self.allocate_hir_id_counter(id, &use_tree);
2990 } = self.lower_node_id(id);
2992 let mut vis = vis.clone();
2993 let mut name = name.clone();
2995 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2997 self.with_hir_id_owner(new_id, |this| {
2998 let vis_kind = match vis.node {
2999 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3000 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3001 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3002 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3003 let id = this.next_id();
3004 hir::VisibilityKind::Restricted {
3006 // We are allocating a new NodeId here
3012 let vis = respan(vis.span, vis_kind);
3020 attrs: attrs.clone(),
3023 span: use_tree.span,
3029 // Privatize the degenerate import base, used only to check
3030 // the stability of `use a::{};`, to avoid it showing up as
3031 // a re-export by accident when `pub`, e.g. in documentation.
3032 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
3033 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3034 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3039 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3040 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3041 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3043 let (generics, node) = match i.node {
3044 TraitItemKind::Const(ref ty, ref default) => (
3045 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3046 hir::TraitItemKind::Const(
3047 self.lower_ty(ty, ImplTraitContext::Disallowed),
3050 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3053 TraitItemKind::Method(ref sig, None) => {
3054 let names = self.lower_fn_args_to_names(&sig.decl);
3055 let (generics, sig) = self.lower_method_sig(
3062 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3064 TraitItemKind::Method(ref sig, Some(ref body)) => {
3065 let body_id = self.lower_body(Some(&sig.decl), |this| {
3066 let body = this.lower_block(body, false);
3067 this.expr_block(body, ThinVec::new())
3069 let (generics, sig) = self.lower_method_sig(
3076 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3078 TraitItemKind::Type(ref bounds, ref default) => (
3079 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3080 hir::TraitItemKind::Type(
3081 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3084 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
3087 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3094 attrs: self.lower_attrs(&i.attrs),
3101 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3102 let (kind, has_default) = match i.node {
3103 TraitItemKind::Const(_, ref default) => {
3104 (hir::AssociatedItemKind::Const, default.is_some())
3106 TraitItemKind::Type(_, ref default) => {
3107 (hir::AssociatedItemKind::Type, default.is_some())
3109 TraitItemKind::Method(ref sig, ref default) => (
3110 hir::AssociatedItemKind::Method {
3111 has_self: sig.decl.has_self(),
3115 TraitItemKind::Macro(..) => unimplemented!(),
3118 id: hir::TraitItemId { node_id: i.id },
3121 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3126 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3127 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3128 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3130 let (generics, node) = match i.node {
3131 ImplItemKind::Const(ref ty, ref expr) => {
3132 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3134 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3135 hir::ImplItemKind::Const(
3136 self.lower_ty(ty, ImplTraitContext::Disallowed),
3141 ImplItemKind::Method(ref sig, ref body) => {
3142 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3143 let impl_trait_return_allow = !self.is_in_trait_impl;
3144 let (generics, sig) = self.lower_method_sig(
3148 impl_trait_return_allow,
3149 sig.header.asyncness.opt_return_id(),
3151 (generics, hir::ImplItemKind::Method(sig, body_id))
3153 ImplItemKind::Type(ref ty) => (
3154 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3155 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3157 ImplItemKind::Existential(ref bounds) => (
3158 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3159 hir::ImplItemKind::Existential(
3160 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3163 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3170 attrs: self.lower_attrs(&i.attrs),
3172 vis: self.lower_visibility(&i.vis, None),
3173 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3178 // [1] since `default impl` is not yet implemented, this is always true in impls
3181 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3183 id: hir::ImplItemId { node_id: i.id },
3186 vis: self.lower_visibility(&i.vis, Some(i.id)),
3187 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3188 kind: match i.node {
3189 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3190 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3191 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3192 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3193 has_self: sig.decl.has_self(),
3195 ImplItemKind::Macro(..) => unimplemented!(),
3199 // [1] since `default impl` is not yet implemented, this is always true in impls
3202 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3205 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3209 /// Lowers `impl Trait` items for a function and appends them to the list
3210 fn lower_fn_impl_trait_ids(
3214 ids: &mut OneVector<hir::ItemId>,
3216 if let Some(id) = header.asyncness.opt_return_id() {
3217 ids.push(hir::ItemId { id });
3219 let mut visitor = ImplTraitTypeIdVisitor { ids };
3221 FunctionRetTy::Default(_) => {},
3222 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3226 fn lower_item_id(&mut self, i: &Item) -> OneVector<hir::ItemId> {
3228 ItemKind::Use(ref use_tree) => {
3229 let mut vec = smallvec![hir::ItemId { id: i.id }];
3230 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3233 ItemKind::MacroDef(..) => OneVector::new(),
3234 ItemKind::Fn(ref decl, ref header, ..) => {
3235 let mut ids = smallvec![hir::ItemId { id: i.id }];
3236 self.lower_fn_impl_trait_ids(decl, header, &mut ids);
3239 ItemKind::Impl(.., None, _, ref items) => {
3240 let mut ids = smallvec![hir::ItemId { id: i.id }];
3242 if let ImplItemKind::Method(ref sig, _) = item.node {
3243 self.lower_fn_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3248 ItemKind::Static(ref ty, ..) => {
3249 let mut ids = smallvec![hir::ItemId { id: i.id }];
3250 if self.sess.features_untracked().impl_trait_in_bindings {
3251 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3252 visitor.visit_ty(ty);
3256 ItemKind::Const(ref ty, ..) => {
3257 let mut ids = smallvec![hir::ItemId { id: i.id }];
3258 if self.sess.features_untracked().impl_trait_in_bindings {
3259 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3260 visitor.visit_ty(ty);
3264 _ => smallvec![hir::ItemId { id: i.id }],
3268 fn lower_item_id_use_tree(&mut self,
3271 vec: &mut OneVector<hir::ItemId>)
3274 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3275 vec.push(hir::ItemId { id });
3276 self.lower_item_id_use_tree(nested, id, vec);
3278 UseTreeKind::Glob => {}
3279 UseTreeKind::Simple(_, id1, id2) => {
3280 for (_, &id) in self.expect_full_def_from_use(base_id)
3282 .zip([id1, id2].iter())
3284 vec.push(hir::ItemId { id });
3290 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3291 let mut name = i.ident.name;
3292 let mut vis = self.lower_visibility(&i.vis, None);
3293 let attrs = self.lower_attrs(&i.attrs);
3294 if let ItemKind::MacroDef(ref def) = i.node {
3295 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3296 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3297 let body = self.lower_token_stream(def.stream());
3298 self.exported_macros.push(hir::MacroDef {
3311 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3313 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3326 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3327 let node_id = self.lower_node_id(i.id).node_id;
3328 let def_id = self.resolver.definitions().local_def_id(node_id);
3332 attrs: self.lower_attrs(&i.attrs),
3333 node: match i.node {
3334 ForeignItemKind::Fn(ref fdec, ref generics) => {
3335 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3338 AnonymousLifetimeMode::PassThrough,
3341 // Disallow impl Trait in foreign items
3342 this.lower_fn_decl(fdec, None, false, None),
3343 this.lower_fn_args_to_names(fdec),
3348 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3350 ForeignItemKind::Static(ref t, m) => {
3351 hir::ForeignItemKind::Static(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3353 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3354 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3356 vis: self.lower_visibility(&i.vis, None),
3361 fn lower_method_sig(
3363 generics: &Generics,
3366 impl_trait_return_allow: bool,
3367 is_async: Option<NodeId>,
3368 ) -> (hir::Generics, hir::MethodSig) {
3369 let header = self.lower_fn_header(sig.header);
3370 let (generics, decl) = self.add_in_band_defs(
3373 AnonymousLifetimeMode::PassThrough,
3374 |this, idty| this.lower_fn_decl(
3376 Some((fn_def_id, idty)),
3377 impl_trait_return_allow,
3381 (generics, hir::MethodSig { header, decl })
3384 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3386 IsAuto::Yes => hir::IsAuto::Yes,
3387 IsAuto::No => hir::IsAuto::No,
3391 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3393 unsafety: self.lower_unsafety(h.unsafety),
3394 asyncness: self.lower_asyncness(h.asyncness),
3395 constness: self.lower_constness(h.constness),
3400 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3402 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3403 Unsafety::Normal => hir::Unsafety::Normal,
3407 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3409 Constness::Const => hir::Constness::Const,
3410 Constness::NotConst => hir::Constness::NotConst,
3414 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3416 IsAsync::Async { .. } => hir::IsAsync::Async,
3417 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3421 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3423 UnOp::Deref => hir::UnDeref,
3424 UnOp::Not => hir::UnNot,
3425 UnOp::Neg => hir::UnNeg,
3429 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3431 node: match b.node {
3432 BinOpKind::Add => hir::BinOpKind::Add,
3433 BinOpKind::Sub => hir::BinOpKind::Sub,
3434 BinOpKind::Mul => hir::BinOpKind::Mul,
3435 BinOpKind::Div => hir::BinOpKind::Div,
3436 BinOpKind::Rem => hir::BinOpKind::Rem,
3437 BinOpKind::And => hir::BinOpKind::And,
3438 BinOpKind::Or => hir::BinOpKind::Or,
3439 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3440 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3441 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3442 BinOpKind::Shl => hir::BinOpKind::Shl,
3443 BinOpKind::Shr => hir::BinOpKind::Shr,
3444 BinOpKind::Eq => hir::BinOpKind::Eq,
3445 BinOpKind::Lt => hir::BinOpKind::Lt,
3446 BinOpKind::Le => hir::BinOpKind::Le,
3447 BinOpKind::Ne => hir::BinOpKind::Ne,
3448 BinOpKind::Ge => hir::BinOpKind::Ge,
3449 BinOpKind::Gt => hir::BinOpKind::Gt,
3455 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3456 let node = match p.node {
3457 PatKind::Wild => hir::PatKind::Wild,
3458 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3459 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3460 // `None` can occur in body-less function signatures
3461 def @ None | def @ Some(Def::Local(_)) => {
3462 let canonical_id = match def {
3463 Some(Def::Local(id)) => id,
3466 hir::PatKind::Binding(
3467 self.lower_binding_mode(binding_mode),
3470 sub.as_ref().map(|x| self.lower_pat(x)),
3473 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3478 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3483 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3484 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3485 let qpath = self.lower_qpath(
3489 ParamMode::Optional,
3490 ImplTraitContext::Disallowed,
3492 self.check_self_struct_ctor_feature(&qpath);
3493 hir::PatKind::TupleStruct(
3495 pats.iter().map(|x| self.lower_pat(x)).collect(),
3499 PatKind::Path(ref qself, ref path) => {
3500 let qpath = self.lower_qpath(
3504 ParamMode::Optional,
3505 ImplTraitContext::Disallowed,
3507 self.check_self_struct_ctor_feature(&qpath);
3508 hir::PatKind::Path(qpath)
3510 PatKind::Struct(ref path, ref fields, etc) => {
3511 let qpath = self.lower_qpath(
3515 ParamMode::Optional,
3516 ImplTraitContext::Disallowed,
3523 node: hir::FieldPat {
3524 id: self.next_id().node_id,
3525 ident: f.node.ident,
3526 pat: self.lower_pat(&f.node.pat),
3527 is_shorthand: f.node.is_shorthand,
3531 hir::PatKind::Struct(qpath, fs, etc)
3533 PatKind::Tuple(ref elts, ddpos) => {
3534 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3536 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3537 PatKind::Ref(ref inner, mutbl) => {
3538 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3540 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3541 P(self.lower_expr(e1)),
3542 P(self.lower_expr(e2)),
3543 self.lower_range_end(end),
3545 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3546 before.iter().map(|x| self.lower_pat(x)).collect(),
3547 slice.as_ref().map(|x| self.lower_pat(x)),
3548 after.iter().map(|x| self.lower_pat(x)).collect(),
3550 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3551 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3554 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3563 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3565 RangeEnd::Included(_) => hir::RangeEnd::Included,
3566 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3570 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3571 self.with_new_scopes(|this| {
3572 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3576 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3581 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3582 let kind = match e.node {
3583 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3584 ExprKind::ObsoleteInPlace(..) => {
3585 self.sess.abort_if_errors();
3586 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3588 ExprKind::Array(ref exprs) => {
3589 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3591 ExprKind::Repeat(ref expr, ref count) => {
3592 let expr = P(self.lower_expr(expr));
3593 let count = self.lower_anon_const(count);
3594 hir::ExprKind::Repeat(expr, count)
3596 ExprKind::Tup(ref elts) => {
3597 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3599 ExprKind::Call(ref f, ref args) => {
3600 let f = P(self.lower_expr(f));
3601 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3603 ExprKind::MethodCall(ref seg, ref args) => {
3604 let hir_seg = self.lower_path_segment(
3607 ParamMode::Optional,
3609 ParenthesizedGenericArgs::Err,
3610 ImplTraitContext::Disallowed,
3612 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3613 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3615 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3616 let binop = self.lower_binop(binop);
3617 let lhs = P(self.lower_expr(lhs));
3618 let rhs = P(self.lower_expr(rhs));
3619 hir::ExprKind::Binary(binop, lhs, rhs)
3621 ExprKind::Unary(op, ref ohs) => {
3622 let op = self.lower_unop(op);
3623 let ohs = P(self.lower_expr(ohs));
3624 hir::ExprKind::Unary(op, ohs)
3626 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3627 ExprKind::Cast(ref expr, ref ty) => {
3628 let expr = P(self.lower_expr(expr));
3629 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3631 ExprKind::Type(ref expr, ref ty) => {
3632 let expr = P(self.lower_expr(expr));
3633 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3635 ExprKind::AddrOf(m, ref ohs) => {
3636 let m = self.lower_mutability(m);
3637 let ohs = P(self.lower_expr(ohs));
3638 hir::ExprKind::AddrOf(m, ohs)
3640 // More complicated than you might expect because the else branch
3641 // might be `if let`.
3642 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3643 let else_opt = else_opt.as_ref().map(|els| {
3645 ExprKind::IfLet(..) => {
3646 // wrap the if-let expr in a block
3647 let span = els.span;
3648 let els = P(self.lower_expr(els));
3649 let LoweredNodeId { node_id, hir_id } = self.next_id();
3650 let blk = P(hir::Block {
3655 rules: hir::DefaultBlock,
3657 targeted_by_break: false,
3658 recovered: blk.recovered,
3660 P(self.expr_block(blk, ThinVec::new()))
3662 _ => P(self.lower_expr(els)),
3666 let then_blk = self.lower_block(blk, false);
3667 let then_expr = self.expr_block(then_blk, ThinVec::new());
3669 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3671 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3672 hir::ExprKind::While(
3673 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3674 this.lower_block(body, false),
3675 this.lower_label(opt_label),
3678 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3679 hir::ExprKind::Loop(
3680 this.lower_block(body, false),
3681 this.lower_label(opt_label),
3682 hir::LoopSource::Loop,
3685 ExprKind::TryBlock(ref body) => {
3686 self.with_catch_scope(body.id, |this| {
3688 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3689 let mut block = this.lower_block(body, true).into_inner();
3690 let tail = block.expr.take().map_or_else(
3692 let LoweredNodeId { node_id, hir_id } = this.next_id();
3693 let span = this.sess.source_map().end_point(unstable_span);
3697 node: hir::ExprKind::Tup(hir_vec![]),
3698 attrs: ThinVec::new(),
3702 |x: P<hir::Expr>| x.into_inner(),
3704 block.expr = Some(this.wrap_in_try_constructor(
3705 "from_ok", tail, unstable_span));
3706 hir::ExprKind::Block(P(block), None)
3709 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3710 P(self.lower_expr(expr)),
3711 arms.iter().map(|x| self.lower_arm(x)).collect(),
3712 hir::MatchSource::Normal,
3714 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3715 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3716 this.with_new_scopes(|this| {
3717 let block = this.lower_block(block, false);
3718 this.expr_block(block, ThinVec::new())
3723 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3725 if let IsAsync::Async { closure_id, .. } = asyncness {
3726 let outer_decl = FnDecl {
3727 inputs: decl.inputs.clone(),
3728 output: FunctionRetTy::Default(fn_decl_span),
3731 // We need to lower the declaration outside the new scope, because we
3732 // have to conserve the state of being inside a loop condition for the
3733 // closure argument types.
3734 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3736 self.with_new_scopes(|this| {
3737 // FIXME(cramertj) allow `async` non-`move` closures with
3738 if capture_clause == CaptureBy::Ref &&
3739 !decl.inputs.is_empty()
3745 "`async` non-`move` closures with arguments \
3746 are not currently supported",
3748 .help("consider using `let` statements to manually capture \
3749 variables by reference before entering an \
3750 `async move` closure")
3754 // Transform `async |x: u8| -> X { ... }` into
3755 // `|x: u8| future_from_generator(|| -> X { ... })`
3756 let body_id = this.lower_body(Some(&outer_decl), |this| {
3757 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3760 let async_body = this.make_async_expr(
3761 capture_clause, closure_id, async_ret_ty,
3763 this.with_new_scopes(|this| this.lower_expr(body))
3765 this.expr(fn_decl_span, async_body, ThinVec::new())
3767 hir::ExprKind::Closure(
3768 this.lower_capture_clause(capture_clause),
3776 // Lower outside new scope to preserve `is_in_loop_condition`.
3777 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3779 self.with_new_scopes(|this| {
3780 let mut is_generator = false;
3781 let body_id = this.lower_body(Some(decl), |this| {
3782 let e = this.lower_expr(body);
3783 is_generator = this.is_generator;
3786 let generator_option = if is_generator {
3787 if !decl.inputs.is_empty() {
3792 "generators cannot have explicit arguments"
3794 this.sess.abort_if_errors();
3796 Some(match movability {
3797 Movability::Movable => hir::GeneratorMovability::Movable,
3798 Movability::Static => hir::GeneratorMovability::Static,
3801 if movability == Movability::Static {
3806 "closures cannot be static"
3811 hir::ExprKind::Closure(
3812 this.lower_capture_clause(capture_clause),
3821 ExprKind::Block(ref blk, opt_label) => {
3822 hir::ExprKind::Block(self.lower_block(blk,
3823 opt_label.is_some()),
3824 self.lower_label(opt_label))
3826 ExprKind::Assign(ref el, ref er) => {
3827 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3829 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3830 self.lower_binop(op),
3831 P(self.lower_expr(el)),
3832 P(self.lower_expr(er)),
3834 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3835 ExprKind::Index(ref el, ref er) => {
3836 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3838 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3839 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3840 let id = self.next_id();
3841 let e1 = self.lower_expr(e1);
3842 let e2 = self.lower_expr(e2);
3843 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3844 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3845 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3846 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3847 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3848 hir::ExprKind::Call(new, hir_vec![e1, e2])
3850 ExprKind::Range(ref e1, ref e2, lims) => {
3851 use syntax::ast::RangeLimits::*;
3853 let path = match (e1, e2, lims) {
3854 (&None, &None, HalfOpen) => "RangeFull",
3855 (&Some(..), &None, HalfOpen) => "RangeFrom",
3856 (&None, &Some(..), HalfOpen) => "RangeTo",
3857 (&Some(..), &Some(..), HalfOpen) => "Range",
3858 (&None, &Some(..), Closed) => "RangeToInclusive",
3859 (&Some(..), &Some(..), Closed) => unreachable!(),
3860 (_, &None, Closed) => self.diagnostic()
3861 .span_fatal(e.span, "inclusive range with no end")
3865 let fields = e1.iter()
3866 .map(|e| ("start", e))
3867 .chain(e2.iter().map(|e| ("end", e)))
3869 let expr = P(self.lower_expr(&e));
3870 let ident = Ident::new(Symbol::intern(s), e.span);
3871 self.field(ident, expr, e.span)
3873 .collect::<P<[hir::Field]>>();
3875 let is_unit = fields.is_empty();
3876 let struct_path = iter::once("ops")
3877 .chain(iter::once(path))
3878 .collect::<Vec<_>>();
3879 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
3880 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3882 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3888 hir::ExprKind::Path(struct_path)
3890 hir::ExprKind::Struct(struct_path, fields, None)
3893 attrs: e.attrs.clone(),
3896 ExprKind::Path(ref qself, ref path) => {
3897 let qpath = self.lower_qpath(
3901 ParamMode::Optional,
3902 ImplTraitContext::Disallowed,
3904 self.check_self_struct_ctor_feature(&qpath);
3905 hir::ExprKind::Path(qpath)
3907 ExprKind::Break(opt_label, ref opt_expr) => {
3908 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3911 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3914 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3916 hir::ExprKind::Break(
3918 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3921 ExprKind::Continue(opt_label) => {
3922 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3925 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3928 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3931 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3932 ExprKind::InlineAsm(ref asm) => {
3933 let hir_asm = hir::InlineAsm {
3934 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3935 outputs: asm.outputs
3937 .map(|out| hir::InlineAsmOutput {
3938 constraint: out.constraint.clone(),
3940 is_indirect: out.is_indirect,
3943 asm: asm.asm.clone(),
3944 asm_str_style: asm.asm_str_style,
3945 clobbers: asm.clobbers.clone().into(),
3946 volatile: asm.volatile,
3947 alignstack: asm.alignstack,
3948 dialect: asm.dialect,
3951 let outputs = asm.outputs
3953 .map(|out| self.lower_expr(&out.expr))
3955 let inputs = asm.inputs
3957 .map(|&(_, ref input)| self.lower_expr(input))
3959 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
3961 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
3966 ParamMode::Optional,
3967 ImplTraitContext::Disallowed,
3969 fields.iter().map(|x| self.lower_field(x)).collect(),
3970 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3972 ExprKind::Paren(ref ex) => {
3973 let mut ex = self.lower_expr(ex);
3974 // include parens in span, but only if it is a super-span.
3975 if e.span.contains(ex.span) {
3978 // merge attributes into the inner expression.
3979 let mut attrs = e.attrs.clone();
3980 attrs.extend::<Vec<_>>(ex.attrs.into());
3985 ExprKind::Yield(ref opt_expr) => {
3986 self.is_generator = true;
3989 .map(|x| self.lower_expr(x))
3991 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
3993 hir::ExprKind::Yield(P(expr))
3996 // Desugar ExprIfLet
3997 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3998 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4001 // match <sub_expr> {
4003 // _ => [<else_opt> | ()]
4006 let mut arms = vec![];
4008 // `<pat> => <body>`
4010 let body = self.lower_block(body, false);
4011 let body_expr = P(self.expr_block(body, ThinVec::new()));
4012 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4013 arms.push(self.arm(pats, body_expr));
4016 // _ => [<else_opt>|()]
4018 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4019 let wildcard_pattern = self.pat_wild(e.span);
4020 let body = if let Some(else_expr) = wildcard_arm {
4021 P(self.lower_expr(else_expr))
4023 self.expr_tuple(e.span, hir_vec![])
4025 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4028 let contains_else_clause = else_opt.is_some();
4030 let sub_expr = P(self.lower_expr(sub_expr));
4032 hir::ExprKind::Match(
4035 hir::MatchSource::IfLetDesugar {
4036 contains_else_clause,
4041 // Desugar ExprWhileLet
4042 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4043 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4046 // [opt_ident]: loop {
4047 // match <sub_expr> {
4053 // Note that the block AND the condition are evaluated in the loop scope.
4054 // This is done to allow `break` from inside the condition of the loop.
4055 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4057 this.lower_block(body, false),
4058 this.expr_break(e.span, ThinVec::new()),
4059 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4063 // `<pat> => <body>`
4065 let body_expr = P(self.expr_block(body, ThinVec::new()));
4066 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4067 self.arm(pats, body_expr)
4072 let pat_under = self.pat_wild(e.span);
4073 self.arm(hir_vec![pat_under], break_expr)
4076 // `match <sub_expr> { ... }`
4077 let arms = hir_vec![pat_arm, break_arm];
4078 let match_expr = self.expr(
4080 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4084 // `[opt_ident]: loop { ... }`
4085 let loop_block = P(self.block_expr(P(match_expr)));
4086 let loop_expr = hir::ExprKind::Loop(
4088 self.lower_label(opt_label),
4089 hir::LoopSource::WhileLet,
4091 // add attributes to the outer returned expr node
4095 // Desugar ExprForLoop
4096 // From: `[opt_ident]: for <pat> in <head> <body>`
4097 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4101 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4103 // [opt_ident]: loop {
4105 // match ::std::iter::Iterator::next(&mut iter) {
4106 // ::std::option::Option::Some(val) => __next = val,
4107 // ::std::option::Option::None => break
4109 // let <pat> = __next;
4110 // StmtKind::Expr(<body>);
4118 let head = self.lower_expr(head);
4119 let head_sp = head.span;
4121 let iter = self.str_to_ident("iter");
4123 let next_ident = self.str_to_ident("__next");
4124 let next_sp = self.allow_internal_unstable(
4125 CompilerDesugaringKind::ForLoop,
4128 let next_pat = self.pat_ident_binding_mode(
4131 hir::BindingAnnotation::Mutable,
4134 // `::std::option::Option::Some(val) => next = val`
4136 let val_ident = self.str_to_ident("val");
4137 let val_pat = self.pat_ident(pat.span, val_ident);
4138 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4139 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4140 let assign = P(self.expr(
4142 hir::ExprKind::Assign(next_expr, val_expr),
4145 let some_pat = self.pat_some(pat.span, val_pat);
4146 self.arm(hir_vec![some_pat], assign)
4149 // `::std::option::Option::None => break`
4152 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4153 let pat = self.pat_none(e.span);
4154 self.arm(hir_vec![pat], break_expr)
4159 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4161 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4163 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4164 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4165 let next_path = &["iter", "Iterator", "next"];
4166 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4167 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4168 let arms = hir_vec![pat_arm, break_arm];
4172 hir::ExprKind::Match(
4175 hir::MatchSource::ForLoopDesugar
4180 let match_stmt = respan(
4182 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4185 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4189 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4191 // `let <pat> = __next`
4192 let pat = self.lower_pat(pat);
4193 let pat_let = self.stmt_let_pat(
4197 hir::LocalSource::ForLoopDesugar,
4200 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4201 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4202 let body_stmt = respan(
4204 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4207 let loop_block = P(self.block_all(
4209 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4213 // `[opt_ident]: loop { ... }`
4214 let loop_expr = hir::ExprKind::Loop(
4216 self.lower_label(opt_label),
4217 hir::LoopSource::ForLoop,
4219 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4220 let loop_expr = P(hir::Expr {
4225 attrs: ThinVec::new(),
4228 // `mut iter => { ... }`
4229 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4231 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4232 let into_iter_expr = {
4233 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4234 let into_iter = P(self.expr_std_path(
4235 head_sp, into_iter_path, None, ThinVec::new()));
4236 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4239 let match_expr = P(self.expr_match(
4243 hir::MatchSource::ForLoopDesugar,
4246 // `{ let _result = ...; _result }`
4247 // underscore prevents an unused_variables lint if the head diverges
4248 let result_ident = self.str_to_ident("_result");
4249 let (let_stmt, let_stmt_binding) =
4250 self.stmt_let(e.span, false, result_ident, match_expr);
4252 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4253 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4254 // add the attributes to the outer returned expr node
4255 return self.expr_block(block, e.attrs.clone());
4258 // Desugar ExprKind::Try
4260 ExprKind::Try(ref sub_expr) => {
4263 // match Try::into_result(<expr>) {
4264 // Ok(val) => #[allow(unreachable_code)] val,
4265 // Err(err) => #[allow(unreachable_code)]
4266 // // If there is an enclosing `catch {...}`
4267 // break 'catch_target Try::from_error(From::from(err)),
4269 // return Try::from_error(From::from(err)),
4273 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4275 // Try::into_result(<expr>)
4278 let sub_expr = self.lower_expr(sub_expr);
4280 let path = &["ops", "Try", "into_result"];
4281 let path = P(self.expr_std_path(
4282 unstable_span, path, None, ThinVec::new()));
4283 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4286 // #[allow(unreachable_code)]
4288 // allow(unreachable_code)
4290 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4291 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4292 let uc_nested = attr::mk_nested_word_item(uc_ident);
4293 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4295 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4297 let attrs = vec![attr];
4299 // Ok(val) => #[allow(unreachable_code)] val,
4301 let val_ident = self.str_to_ident("val");
4302 let val_pat = self.pat_ident(e.span, val_ident);
4303 let val_expr = P(self.expr_ident_with_attrs(
4307 ThinVec::from(attrs.clone()),
4309 let ok_pat = self.pat_ok(e.span, val_pat);
4311 self.arm(hir_vec![ok_pat], val_expr)
4314 // Err(err) => #[allow(unreachable_code)]
4315 // return Try::from_error(From::from(err)),
4317 let err_ident = self.str_to_ident("err");
4318 let err_local = self.pat_ident(e.span, err_ident);
4320 let path = &["convert", "From", "from"];
4321 let from = P(self.expr_std_path(
4322 e.span, path, None, ThinVec::new()));
4323 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4325 self.expr_call(e.span, from, hir_vec![err_expr])
4328 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4329 let thin_attrs = ThinVec::from(attrs);
4330 let catch_scope = self.catch_scopes.last().map(|x| *x);
4331 let ret_expr = if let Some(catch_node) = catch_scope {
4334 hir::ExprKind::Break(
4337 target_id: Ok(catch_node),
4339 Some(from_err_expr),
4344 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4347 let err_pat = self.pat_err(e.span, err_local);
4348 self.arm(hir_vec![err_pat], ret_expr)
4351 hir::ExprKind::Match(
4353 hir_vec![err_arm, ok_arm],
4354 hir::MatchSource::TryDesugar,
4358 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4361 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4368 attrs: e.attrs.clone(),
4372 fn lower_stmt(&mut self, s: &Stmt) -> OneVector<hir::Stmt> {
4373 smallvec![match s.node {
4374 StmtKind::Local(ref l) => {
4375 let (l, item_ids) = self.lower_local(l);
4376 let mut ids: OneVector<hir::Stmt> = item_ids
4378 .map(|item_id| Spanned {
4379 node: hir::StmtKind::Decl(
4381 node: hir::DeclKind::Item(item_id),
4384 self.next_id().node_id,
4390 node: hir::StmtKind::Decl(
4392 node: hir::DeclKind::Local(l),
4395 self.lower_node_id(s.id).node_id,
4401 StmtKind::Item(ref it) => {
4402 // Can only use the ID once.
4403 let mut id = Some(s.id);
4404 return self.lower_item_id(it)
4406 .map(|item_id| Spanned {
4407 node: hir::StmtKind::Decl(
4409 node: hir::DeclKind::Item(item_id),
4413 .map(|id| self.lower_node_id(id).node_id)
4414 .unwrap_or_else(|| self.next_id().node_id),
4420 StmtKind::Expr(ref e) => Spanned {
4421 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4424 StmtKind::Semi(ref e) => Spanned {
4425 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4428 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4432 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4434 CaptureBy::Value => hir::CaptureByValue,
4435 CaptureBy::Ref => hir::CaptureByRef,
4439 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4440 /// the address space of that item instead of the item currently being
4441 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4442 /// lower a `Visibility` value although we haven't lowered the owning
4443 /// `ImplItem` in question yet.
4444 fn lower_visibility(
4447 explicit_owner: Option<NodeId>,
4448 ) -> hir::Visibility {
4449 let node = match v.node {
4450 VisibilityKind::Public => hir::VisibilityKind::Public,
4451 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4452 VisibilityKind::Restricted { ref path, id } => {
4453 let lowered_id = if let Some(owner) = explicit_owner {
4454 self.lower_node_id_with_owner(id, owner)
4456 self.lower_node_id(id)
4458 hir::VisibilityKind::Restricted {
4459 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4460 id: lowered_id.node_id,
4461 hir_id: lowered_id.hir_id,
4464 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4466 respan(v.span, node)
4469 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4471 Defaultness::Default => hir::Defaultness::Default {
4472 has_value: has_value,
4474 Defaultness::Final => {
4476 hir::Defaultness::Final
4481 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4483 BlockCheckMode::Default => hir::DefaultBlock,
4484 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4488 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4490 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4491 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4492 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4493 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4497 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4499 CompilerGenerated => hir::CompilerGenerated,
4500 UserProvided => hir::UserProvided,
4504 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4506 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4507 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4511 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4513 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4514 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4518 // Helper methods for building HIR.
4520 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4529 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4531 id: self.next_id().node_id,
4535 is_shorthand: false,
4539 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4540 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4541 P(self.expr(span, expr_break, attrs))
4548 args: hir::HirVec<hir::Expr>,
4550 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4553 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4554 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4557 fn expr_ident_with_attrs(
4562 attrs: ThinVec<Attribute>,
4564 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4568 def: Def::Local(binding),
4569 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4573 self.expr(span, expr_path, attrs)
4576 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4577 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4583 components: &[&str],
4584 params: Option<P<hir::GenericArgs>>,
4585 attrs: ThinVec<Attribute>,
4587 let path = self.std_path(span, components, params, true);
4590 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4599 arms: hir::HirVec<hir::Arm>,
4600 source: hir::MatchSource,
4602 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4605 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4606 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4609 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4610 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4613 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4614 let LoweredNodeId { node_id, hir_id } = self.next_id();
4627 ex: Option<P<hir::Expr>>,
4629 source: hir::LocalSource,
4631 let LoweredNodeId { node_id, hir_id } = self.next_id();
4633 let local = P(hir::Local {
4640 attrs: ThinVec::new(),
4643 let decl = respan(sp, hir::DeclKind::Local(local));
4644 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4653 ) -> (hir::Stmt, NodeId) {
4654 let pat = if mutbl {
4655 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4657 self.pat_ident(sp, ident)
4659 let pat_id = pat.id;
4661 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4666 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4667 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4673 stmts: hir::HirVec<hir::Stmt>,
4674 expr: Option<P<hir::Expr>>,
4676 let LoweredNodeId { node_id, hir_id } = self.next_id();
4683 rules: hir::DefaultBlock,
4685 targeted_by_break: false,
4690 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4691 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4694 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4695 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4698 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4699 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4702 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4703 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4709 components: &[&str],
4710 subpats: hir::HirVec<P<hir::Pat>>,
4712 let path = self.std_path(span, components, None, true);
4713 let qpath = hir::QPath::Resolved(None, P(path));
4714 let pt = if subpats.is_empty() {
4715 hir::PatKind::Path(qpath)
4717 hir::PatKind::TupleStruct(qpath, subpats, None)
4722 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4723 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4726 fn pat_ident_binding_mode(
4730 bm: hir::BindingAnnotation,
4732 let LoweredNodeId { node_id, hir_id } = self.next_id();
4737 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4742 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4743 self.pat(span, hir::PatKind::Wild)
4746 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4747 let LoweredNodeId { node_id, hir_id } = self.next_id();
4756 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4757 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4758 /// The path is also resolved according to `is_value`.
4762 components: &[&str],
4763 params: Option<P<hir::GenericArgs>>,
4767 .resolve_str_path(span, self.crate_root, components, params, is_value)
4770 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4772 let node = match qpath {
4773 hir::QPath::Resolved(None, path) => {
4774 // Turn trait object paths into `TyKind::TraitObject` instead.
4775 if let Def::Trait(_) = path.def {
4776 let principal = hir::PolyTraitRef {
4777 bound_generic_params: hir::HirVec::new(),
4778 trait_ref: hir::TraitRef {
4779 path: path.and_then(|path| path),
4781 hir_ref_id: id.hir_id,
4786 // The original ID is taken by the `PolyTraitRef`,
4787 // so the `Ty` itself needs a different one.
4788 id = self.next_id();
4789 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4791 hir::TyKind::Path(hir::QPath::Resolved(None, path))
4794 _ => hir::TyKind::Path(qpath),
4804 /// Invoked to create the lifetime argument for a type `&T`
4805 /// with no explicit lifetime.
4806 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4807 match self.anonymous_lifetime_mode {
4808 // Intercept when we are in an impl header and introduce an in-band lifetime.
4809 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4811 AnonymousLifetimeMode::CreateParameter => {
4812 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4814 id: self.next_id().node_id,
4816 name: hir::LifetimeName::Param(fresh_name),
4820 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4824 /// Invoked to create the lifetime argument(s) for a path like
4825 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4826 /// sorts of cases are deprecated. This may therefore report a warning or an
4827 /// error, depending on the mode.
4828 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4829 match self.anonymous_lifetime_mode {
4830 // NB. We intentionally ignore the create-parameter mode here
4831 // and instead "pass through" to resolve-lifetimes, which will then
4832 // report an error. This is because we don't want to support
4833 // impl elision for deprecated forms like
4835 // impl Foo for std::cell::Ref<u32> // note lack of '_
4836 AnonymousLifetimeMode::CreateParameter => {}
4838 // This is the normal case.
4839 AnonymousLifetimeMode::PassThrough => {}
4843 .map(|_| self.new_implicit_lifetime(span))
4847 /// Invoked to create the lifetime argument(s) for an elided trait object
4848 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4849 /// when the bound is written, even if it is written with `'_` like in
4850 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4851 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4852 match self.anonymous_lifetime_mode {
4853 // NB. We intentionally ignore the create-parameter mode here.
4854 // and instead "pass through" to resolve-lifetimes, which will apply
4855 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4856 // do not act like other elided lifetimes. In other words, given this:
4858 // impl Foo for Box<dyn Debug>
4860 // we do not introduce a fresh `'_` to serve as the bound, but instead
4861 // ultimately translate to the equivalent of:
4863 // impl Foo for Box<dyn Debug + 'static>
4865 // `resolve_lifetime` has the code to make that happen.
4866 AnonymousLifetimeMode::CreateParameter => {}
4868 // This is the normal case.
4869 AnonymousLifetimeMode::PassThrough => {}
4872 self.new_implicit_lifetime(span)
4875 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4877 id: self.next_id().node_id,
4879 name: hir::LifetimeName::Implicit,
4883 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4884 self.sess.buffer_lint_with_diagnostic(
4885 builtin::BARE_TRAIT_OBJECTS,
4888 "trait objects without an explicit `dyn` are deprecated",
4889 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4893 fn wrap_in_try_constructor(
4895 method: &'static str,
4897 unstable_span: Span,
4899 let path = &["ops", "Try", method];
4900 let from_err = P(self.expr_std_path(unstable_span, path, None,
4902 P(self.expr_call(e.span, from_err, hir_vec![e]))
4905 fn check_self_struct_ctor_feature(&self, qp: &hir::QPath) {
4906 if let hir::QPath::Resolved(_, ref p) = qp {
4907 if p.segments.len() == 1 &&
4908 p.segments[0].ident.name == keywords::SelfType.name() &&
4909 !self.sess.features_untracked().self_struct_ctor {
4910 emit_feature_err(&self.sess.parse_sess, "self_struct_ctor",
4911 p.span, GateIssue::Language,
4912 "`Self` struct constructors are unstable");
4918 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4919 // Sorting by span ensures that we get things in order within a
4920 // file, and also puts the files in a sensible order.
4921 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4922 body_ids.sort_by_key(|b| bodies[b].value.span);