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;
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 use middle::cstore::CrateStore;
52 use rustc_data_structures::indexed_vec::IndexVec;
54 use util::common::FN_OUTPUT_NAME;
55 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
57 use std::collections::{BTreeMap, HashSet};
64 use syntax::ext::hygiene::{Mark, SyntaxContext};
65 use syntax::print::pprust;
67 use syntax::codemap::{self, respan, CompilerDesugaringKind, Spanned};
68 use syntax::std_inject;
69 use syntax::symbol::{keywords, Symbol};
70 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
71 use syntax::parse::token::Token;
72 use syntax::util::small_vector::SmallVector;
73 use syntax::visit::{self, Visitor};
76 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
78 pub struct LoweringContext<'a> {
79 crate_root: Option<&'static str>,
81 // Use to assign ids to hir nodes that do not directly correspond to an ast node
84 cstore: &'a CrateStore,
86 resolver: &'a mut Resolver,
87 name_map: FxHashMap<Ident, Name>,
89 /// The items being lowered are collected here.
90 items: BTreeMap<NodeId, hir::Item>,
92 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
93 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
94 bodies: BTreeMap<hir::BodyId, hir::Body>,
95 exported_macros: Vec<hir::MacroDef>,
97 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
98 trait_auto_impl: BTreeMap<DefId, NodeId>,
102 catch_scopes: Vec<NodeId>,
103 loop_scopes: Vec<NodeId>,
104 is_in_loop_condition: bool,
105 is_in_trait_impl: bool,
107 /// What to do when we encounter either an "anonymous lifetime
108 /// reference". The term "anonymous" is meant to encompass both
109 /// `'_` lifetimes as well as fully elided cases where nothing is
110 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
111 anonymous_lifetime_mode: AnonymousLifetimeMode,
113 // This is a list of in-band type definitions being generated by
114 // Argument-position `impl Trait`.
115 // When traversing a signature such as `fn foo(x: impl Trait)`,
116 // we record `impl Trait` as a new type parameter, then later
117 // add it on to `foo`s generics.
118 in_band_ty_params: Vec<hir::TyParam>,
120 // Used to create lifetime definitions from in-band lifetime usages.
121 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
122 // When a named lifetime is encountered in a function or impl header and
123 // has not been defined
124 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
125 // to this list. The results of this list are then added to the list of
126 // lifetime definitions in the corresponding impl or function generics.
127 lifetimes_to_define: Vec<(Span, hir::LifetimeName)>,
129 // Whether or not in-band lifetimes are being collected. This is used to
130 // indicate whether or not we're in a place where new lifetimes will result
131 // in in-band lifetime definitions, such a function or an impl header.
132 // This will always be false unless the `in_band_lifetimes` feature is
134 is_collecting_in_band_lifetimes: bool,
136 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
137 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
138 // against this list to see if it is already in-scope, or if a definition
139 // needs to be created for it.
140 in_scope_lifetimes: Vec<Name>,
142 type_def_lifetime_params: DefIdMap<usize>,
144 current_hir_id_owner: Vec<(DefIndex, u32)>,
145 item_local_id_counters: NodeMap<u32>,
146 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
150 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
151 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
153 /// Obtain the resolution for a node id
154 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
156 /// Obtain the possible resolutions for the given `use` statement.
157 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
159 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
160 /// This should only return `None` during testing.
161 fn definitions(&mut self) -> &mut Definitions;
163 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
164 /// it based on `is_value`.
168 crate_root: Option<&str>,
174 #[derive(Clone, Copy, Debug)]
175 enum ImplTraitContext {
176 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
177 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
178 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
180 /// We store a DefId here so we can look up necessary information later
183 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
184 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
185 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
187 /// We store a DefId here so we can look up necessary information later
190 /// `impl Trait` is not accepted in this position.
197 dep_graph: &DepGraph,
199 resolver: &mut Resolver,
201 // We're constructing the HIR here; we don't care what we will
202 // read, since we haven't even constructed the *input* to
204 dep_graph.assert_ignored();
207 crate_root: std_inject::injected_crate_name(),
211 name_map: FxHashMap(),
212 items: BTreeMap::new(),
213 trait_items: BTreeMap::new(),
214 impl_items: BTreeMap::new(),
215 bodies: BTreeMap::new(),
216 trait_impls: BTreeMap::new(),
217 trait_auto_impl: BTreeMap::new(),
218 exported_macros: Vec::new(),
219 catch_scopes: Vec::new(),
220 loop_scopes: Vec::new(),
221 is_in_loop_condition: false,
222 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
223 type_def_lifetime_params: DefIdMap(),
224 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
225 item_local_id_counters: NodeMap(),
226 node_id_to_hir_id: IndexVec::new(),
228 is_in_trait_impl: false,
229 in_band_ty_params: Vec::new(),
230 lifetimes_to_define: Vec::new(),
231 is_collecting_in_band_lifetimes: false,
232 in_scope_lifetimes: Vec::new(),
236 #[derive(Copy, Clone, PartialEq, Eq)]
238 /// Any path in a type context.
240 /// The `module::Type` in `module::Type::method` in an expression.
245 struct LoweredNodeId {
250 enum ParenthesizedGenericArgs {
256 /// What to do when we encounter an **anonymous** lifetime
257 /// reference. Anonymous lifetime references come in two flavors. You
258 /// have implicit, or fully elided, references to lifetimes, like the
259 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
260 /// or `Ref<'_, T>`. These often behave the same, but not always:
262 /// - certain usages of implicit references are deprecated, like
263 /// `Ref<T>`, and we sometimes just give hard errors in those cases
265 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
266 /// the same as `Box<dyn Foo + '_>`.
268 /// We describe the effects of the various modes in terms of three cases:
270 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
271 /// of a `&` (e.g., the missing lifetime in something like `&T`)
272 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
273 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
274 /// elided bounds follow special rules. Note that this only covers
275 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
276 /// '_>` is a case of "modern" elision.
277 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
278 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
279 /// non-deprecated equivalent.
281 /// Currently, the handling of lifetime elision is somewhat spread out
282 /// between HIR lowering and -- as described below -- the
283 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
284 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
285 /// everything into HIR lowering.
286 #[derive(Copy, Clone)]
287 enum AnonymousLifetimeMode {
288 /// For **Modern** cases, create a new anonymous region parameter
289 /// and reference that.
291 /// For **Dyn Bound** cases, pass responsibility to
292 /// `resolve_lifetime` code.
294 /// For **Deprecated** cases, report an error.
297 /// Pass responsibility to `resolve_lifetime` code for all cases.
301 impl<'a> LoweringContext<'a> {
302 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
303 /// Full-crate AST visitor that inserts into a fresh
304 /// `LoweringContext` any information that may be
305 /// needed from arbitrary locations in the crate.
306 /// E.g. The number of lifetime generic parameters
307 /// declared for every type and trait definition.
308 struct MiscCollector<'lcx, 'interner: 'lcx> {
309 lctx: &'lcx mut LoweringContext<'interner>,
312 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
313 fn visit_item(&mut self, item: &'lcx Item) {
314 self.lctx.allocate_hir_id_counter(item.id, item);
317 ItemKind::Struct(_, ref generics)
318 | ItemKind::Union(_, ref generics)
319 | ItemKind::Enum(_, ref generics)
320 | ItemKind::Ty(_, ref generics)
321 | ItemKind::Trait(_, _, ref generics, ..) => {
322 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
326 .filter(|param| param.is_lifetime_param())
328 self.lctx.type_def_lifetime_params.insert(def_id, count);
332 visit::walk_item(self, item);
335 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
336 self.lctx.allocate_hir_id_counter(item.id, item);
337 visit::walk_trait_item(self, item);
340 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
341 self.lctx.allocate_hir_id_counter(item.id, item);
342 visit::walk_impl_item(self, item);
346 struct ItemLowerer<'lcx, 'interner: 'lcx> {
347 lctx: &'lcx mut LoweringContext<'interner>,
350 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
351 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
353 F: FnOnce(&mut Self),
355 let old = self.lctx.is_in_trait_impl;
356 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
362 self.lctx.is_in_trait_impl = old;
366 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
367 fn visit_item(&mut self, item: &'lcx Item) {
368 let mut item_lowered = true;
369 self.lctx.with_hir_id_owner(item.id, |lctx| {
370 if let Some(hir_item) = lctx.lower_item(item) {
371 lctx.items.insert(item.id, hir_item);
373 item_lowered = false;
378 let item_lifetimes = match self.lctx.items.get(&item.id).unwrap().node {
379 hir::Item_::ItemImpl(_, _, _, ref generics, ..)
380 | hir::Item_::ItemTrait(_, _, ref generics, ..) => {
381 generics.lifetimes().cloned().collect::<Vec<_>>()
387 .with_parent_impl_lifetime_defs(&item_lifetimes, |this| {
388 let this = &mut ItemLowerer { lctx: this };
389 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
390 this.with_trait_impl_ref(opt_trait_ref, |this| {
391 visit::walk_item(this, item)
394 visit::walk_item(this, item);
400 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
401 self.lctx.with_hir_id_owner(item.id, |lctx| {
402 let id = hir::TraitItemId { node_id: item.id };
403 let hir_item = lctx.lower_trait_item(item);
404 lctx.trait_items.insert(id, hir_item);
407 visit::walk_trait_item(self, item);
410 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
411 self.lctx.with_hir_id_owner(item.id, |lctx| {
412 let id = hir::ImplItemId { node_id: item.id };
413 let hir_item = lctx.lower_impl_item(item);
414 lctx.impl_items.insert(id, hir_item);
416 visit::walk_impl_item(self, item);
420 self.lower_node_id(CRATE_NODE_ID);
421 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
423 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
424 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
426 let module = self.lower_mod(&c.module);
427 let attrs = self.lower_attrs(&c.attrs);
428 let body_ids = body_ids(&self.bodies);
432 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
438 exported_macros: hir::HirVec::from(self.exported_macros),
440 trait_items: self.trait_items,
441 impl_items: self.impl_items,
444 trait_impls: self.trait_impls,
445 trait_auto_impl: self.trait_auto_impl,
449 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) {
450 if self.item_local_id_counters.insert(owner, 0).is_some() {
452 "Tried to allocate item_local_id_counter for {:?} twice",
456 // Always allocate the first HirId for the owner itself
457 self.lower_node_id_with_owner(owner, owner);
460 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
462 F: FnOnce(&mut Self) -> hir::HirId,
464 if ast_node_id == DUMMY_NODE_ID {
465 return LoweredNodeId {
466 node_id: DUMMY_NODE_ID,
467 hir_id: hir::DUMMY_HIR_ID,
471 let min_size = ast_node_id.as_usize() + 1;
473 if min_size > self.node_id_to_hir_id.len() {
474 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
477 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
479 if existing_hir_id == hir::DUMMY_HIR_ID {
480 // Generate a new HirId
481 let hir_id = alloc_hir_id(self);
482 self.node_id_to_hir_id[ast_node_id] = hir_id;
484 node_id: ast_node_id,
489 node_id: ast_node_id,
490 hir_id: existing_hir_id,
495 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
497 F: FnOnce(&mut Self) -> T,
499 let counter = self.item_local_id_counters
500 .insert(owner, HIR_ID_COUNTER_LOCKED)
502 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
503 self.current_hir_id_owner.push((def_index, counter));
505 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
507 debug_assert!(def_index == new_def_index);
508 debug_assert!(new_counter >= counter);
510 let prev = self.item_local_id_counters
511 .insert(owner, new_counter)
513 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
517 /// This method allocates a new HirId for the given NodeId and stores it in
518 /// the LoweringContext's NodeId => HirId map.
519 /// Take care not to call this method if the resulting HirId is then not
520 /// actually used in the HIR, as that would trigger an assertion in the
521 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
522 /// properly. Calling the method twice with the same NodeId is fine though.
523 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
524 self.lower_node_id_generic(ast_node_id, |this| {
525 let &mut (def_index, ref mut local_id_counter) =
526 this.current_hir_id_owner.last_mut().unwrap();
527 let local_id = *local_id_counter;
528 *local_id_counter += 1;
531 local_id: hir::ItemLocalId(local_id),
536 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
537 self.lower_node_id_generic(ast_node_id, |this| {
538 let local_id_counter = this
539 .item_local_id_counters
541 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
542 let local_id = *local_id_counter;
544 // We want to be sure not to modify the counter in the map while it
545 // is also on the stack. Otherwise we'll get lost updates when writing
546 // back from the stack to the map.
547 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
549 *local_id_counter += 1;
553 .opt_def_index(owner)
554 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
555 that do not belong to the current owner");
559 local_id: hir::ItemLocalId(local_id),
564 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
565 let body = hir::Body {
566 arguments: decl.map_or(hir_vec![], |decl| {
567 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
569 is_generator: self.is_generator,
573 self.bodies.insert(id, body);
577 fn next_id(&mut self) -> LoweredNodeId {
578 self.lower_node_id(self.sess.next_node_id())
581 fn expect_full_def(&mut self, id: NodeId) -> Def {
582 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
583 if pr.unresolved_segments() != 0 {
584 bug!("path not fully resolved: {:?}", pr);
590 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
591 self.resolver.get_import(id).present_items().map(|pr| {
592 if pr.unresolved_segments() != 0 {
593 bug!("path not fully resolved: {:?}", pr);
599 fn diagnostic(&self) -> &errors::Handler {
600 self.sess.diagnostic()
603 fn str_to_ident(&self, s: &'static str) -> Name {
607 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
608 let mark = Mark::fresh(Mark::root());
609 mark.set_expn_info(codemap::ExpnInfo {
611 callee: codemap::NameAndSpan {
612 format: codemap::CompilerDesugaring(reason),
614 allow_internal_unstable: true,
615 allow_internal_unsafe: false,
616 edition: codemap::hygiene::default_edition(),
619 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
622 fn with_anonymous_lifetime_mode<R>(
624 anonymous_lifetime_mode: AnonymousLifetimeMode,
625 op: impl FnOnce(&mut Self) -> R,
627 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
628 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
629 let result = op(self);
630 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
634 /// Creates a new hir::GenericParam for every new lifetime and
635 /// type parameter encountered while evaluating `f`. Definitions
636 /// are created with the parent provided. If no `parent_id` is
637 /// provided, no definitions will be returned.
639 /// Presuming that in-band lifetimes are enabled, then
640 /// `self.anonymous_lifetime_mode` will be updated to match the
641 /// argument while `f` is running (and restored afterwards).
642 fn collect_in_band_defs<T, F>(
645 anonymous_lifetime_mode: AnonymousLifetimeMode,
647 ) -> (Vec<hir::GenericParam>, T)
649 F: FnOnce(&mut LoweringContext) -> T,
651 assert!(!self.is_collecting_in_band_lifetimes);
652 assert!(self.lifetimes_to_define.is_empty());
653 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
655 self.is_collecting_in_band_lifetimes = self.sess.features_untracked().in_band_lifetimes;
656 if self.is_collecting_in_band_lifetimes {
657 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
660 assert!(self.in_band_ty_params.is_empty());
663 self.is_collecting_in_band_lifetimes = false;
664 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
666 let in_band_ty_params = self.in_band_ty_params.split_off(0);
667 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
669 let params = lifetimes_to_define
671 .map(|(span, hir_name)| {
672 let def_node_id = self.next_id().node_id;
674 // Get the name we'll use to make the def-path. Note
675 // that collisions are ok here and this shouldn't
676 // really show up for end-user.
677 let str_name = match hir_name {
678 hir::LifetimeName::Name(n) => n.as_str(),
679 hir::LifetimeName::Fresh(_) => keywords::UnderscoreLifetime.name().as_str(),
680 hir::LifetimeName::Implicit
681 | hir::LifetimeName::Underscore
682 | hir::LifetimeName::Static => {
683 span_bug!(span, "unexpected in-band lifetime name: {:?}", hir_name)
687 // Add a definition for the in-band lifetime def
688 self.resolver.definitions().create_def_with_parent(
691 DefPathData::LifetimeDef(str_name.as_interned_str()),
692 DefIndexAddressSpace::High,
697 hir::GenericParam::Lifetime(hir::LifetimeDef {
698 lifetime: hir::Lifetime {
703 bounds: Vec::new().into(),
704 pure_wrt_drop: false,
711 .map(|tp| hir::GenericParam::Type(tp)),
718 /// When there is a reference to some lifetime `'a`, and in-band
719 /// lifetimes are enabled, then we want to push that lifetime into
720 /// the vector of names to define later. In that case, it will get
721 /// added to the appropriate generics.
722 fn maybe_collect_in_band_lifetime(&mut self, span: Span, name: Name) {
723 if !self.is_collecting_in_band_lifetimes {
727 if self.in_scope_lifetimes.contains(&name) {
731 let hir_name = hir::LifetimeName::Name(name);
733 if self.lifetimes_to_define
735 .any(|(_, lt_name)| *lt_name == hir_name)
740 self.lifetimes_to_define.push((span, hir_name));
743 /// When we have either an elided or `'_` lifetime in an impl
744 /// header, we convert it to
745 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> hir::LifetimeName {
746 assert!(self.is_collecting_in_band_lifetimes);
747 let index = self.lifetimes_to_define.len();
748 let hir_name = hir::LifetimeName::Fresh(index);
749 self.lifetimes_to_define.push((span, hir_name));
753 // Evaluates `f` with the lifetimes in `lt_defs` in-scope.
754 // This is used to track which lifetimes have already been defined, and
755 // which are new in-band lifetimes that need to have a definition created
757 fn with_in_scope_lifetime_defs<'l, T, F>(
759 lt_defs: impl Iterator<Item = &'l LifetimeDef>,
763 F: FnOnce(&mut LoweringContext) -> T,
765 let old_len = self.in_scope_lifetimes.len();
766 let lt_def_names = lt_defs.map(|lt_def| lt_def.lifetime.ident.name);
767 self.in_scope_lifetimes.extend(lt_def_names);
771 self.in_scope_lifetimes.truncate(old_len);
775 // Same as the method above, but accepts `hir::LifetimeDef`s
776 // instead of `ast::LifetimeDef`s.
777 // This should only be used with generics that have already had their
778 // in-band lifetimes added. In practice, this means that this function is
779 // only used when lowering a child item of a trait or impl.
780 fn with_parent_impl_lifetime_defs<T, F>(&mut self, lt_defs: &[hir::LifetimeDef], f: F) -> T
782 F: FnOnce(&mut LoweringContext) -> T,
784 let old_len = self.in_scope_lifetimes.len();
785 let lt_def_names = lt_defs.iter().map(|lt_def| lt_def.lifetime.name.name());
786 self.in_scope_lifetimes.extend(lt_def_names);
790 self.in_scope_lifetimes.truncate(old_len);
794 /// Appends in-band lifetime defs and argument-position `impl
795 /// Trait` defs to the existing set of generics.
797 /// Presuming that in-band lifetimes are enabled, then
798 /// `self.anonymous_lifetime_mode` will be updated to match the
799 /// argument while `f` is running (and restored afterwards).
800 fn add_in_band_defs<F, T>(
804 anonymous_lifetime_mode: AnonymousLifetimeMode,
806 ) -> (hir::Generics, T)
808 F: FnOnce(&mut LoweringContext) -> T,
810 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
811 generics.params.iter().filter_map(|p| match p {
812 GenericParam::Lifetime(ld) => Some(ld),
816 let itctx = ImplTraitContext::Universal(parent_id);
817 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
818 (this.lower_generics(generics, itctx), f(this))
823 lowered_generics.params = lowered_generics
830 (lowered_generics, res)
833 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
835 F: FnOnce(&mut LoweringContext) -> T,
837 let len = self.catch_scopes.len();
838 self.catch_scopes.push(catch_id);
840 let result = f(self);
843 self.catch_scopes.len(),
844 "catch scopes should be added and removed in stack order"
847 self.catch_scopes.pop().unwrap();
852 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
854 F: FnOnce(&mut LoweringContext) -> hir::Expr,
856 let prev = mem::replace(&mut self.is_generator, false);
857 let result = f(self);
858 let r = self.record_body(result, decl);
859 self.is_generator = prev;
863 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
865 F: FnOnce(&mut LoweringContext) -> T,
867 // We're no longer in the base loop's condition; we're in another loop.
868 let was_in_loop_condition = self.is_in_loop_condition;
869 self.is_in_loop_condition = false;
871 let len = self.loop_scopes.len();
872 self.loop_scopes.push(loop_id);
874 let result = f(self);
877 self.loop_scopes.len(),
878 "Loop scopes should be added and removed in stack order"
881 self.loop_scopes.pop().unwrap();
883 self.is_in_loop_condition = was_in_loop_condition;
888 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
890 F: FnOnce(&mut LoweringContext) -> T,
892 let was_in_loop_condition = self.is_in_loop_condition;
893 self.is_in_loop_condition = true;
895 let result = f(self);
897 self.is_in_loop_condition = was_in_loop_condition;
902 fn with_new_scopes<T, F>(&mut self, f: F) -> T
904 F: FnOnce(&mut LoweringContext) -> T,
906 let was_in_loop_condition = self.is_in_loop_condition;
907 self.is_in_loop_condition = false;
909 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
910 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
911 let result = f(self);
912 self.catch_scopes = catch_scopes;
913 self.loop_scopes = loop_scopes;
915 self.is_in_loop_condition = was_in_loop_condition;
920 fn def_key(&mut self, id: DefId) -> DefKey {
922 self.resolver.definitions().def_key(id.index)
924 self.cstore.def_key(id)
928 fn lower_ident(&mut self, ident: Ident) -> Name {
929 let ident = ident.modern();
930 if ident.span.ctxt() == SyntaxContext::empty() {
935 .or_insert_with(|| Symbol::from_ident(ident))
938 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
939 label.map(|label| hir::Label {
940 name: label.ident.name,
941 span: label.ident.span,
945 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
947 Some((id, label)) => {
948 let target_id = if let Def::Label(loop_id) = self.expect_full_def(id) {
949 Ok(self.lower_node_id(loop_id).node_id)
951 Err(hir::LoopIdError::UnresolvedLabel)
954 label: self.lower_label(Some(label)),
959 let target_id = self.loop_scopes
961 .map(|innermost_loop_id| *innermost_loop_id)
962 .map(|id| Ok(self.lower_node_id(id).node_id))
963 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
974 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
977 .map(|a| self.lower_attr(a))
982 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
986 path: attr.path.clone(),
987 tokens: self.lower_token_stream(attr.tokens.clone()),
988 is_sugared_doc: attr.is_sugared_doc,
993 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
996 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1000 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1002 TokenTree::Token(span, token) => self.lower_token(token, span),
1003 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1006 delim: delimited.delim,
1007 tts: self.lower_token_stream(delimited.tts.into()).into(),
1013 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1015 Token::Interpolated(_) => {}
1016 other => return TokenTree::Token(span, other).into(),
1019 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1020 self.lower_token_stream(tts)
1023 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1025 attrs: self.lower_attrs(&arm.attrs),
1026 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1027 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1028 body: P(self.lower_expr(&arm.body)),
1032 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1034 id: self.lower_node_id(b.id).node_id,
1035 name: self.lower_ident(b.ident),
1036 ty: self.lower_ty(&b.ty, itctx),
1041 fn lower_generic_arg(&mut self,
1042 p: &AngleBracketedParam,
1043 itctx: ImplTraitContext)
1046 AngleBracketedParam::Lifetime(lt) => {
1047 GenericArg::Lifetime(self.lower_lifetime(<))
1049 AngleBracketedParam::Type(ty) => {
1050 GenericArg::Type(self.lower_ty(&ty, itctx))
1055 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1056 let kind = match t.node {
1057 TyKind::Infer => hir::TyInfer,
1058 TyKind::Err => hir::TyErr,
1059 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1060 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1061 TyKind::Rptr(ref region, ref mt) => {
1062 let span = t.span.shrink_to_lo();
1063 let lifetime = match *region {
1064 Some(ref lt) => self.lower_lifetime(lt),
1065 None => self.elided_ref_lifetime(span),
1067 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1069 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1070 f.generic_params.iter().filter_map(|p| match p {
1071 GenericParam::Lifetime(ld) => Some(ld),
1075 this.with_anonymous_lifetime_mode(
1076 AnonymousLifetimeMode::PassThrough,
1078 hir::TyBareFn(P(hir::BareFnTy {
1079 generic_params: this.lower_generic_params(
1082 ImplTraitContext::Disallowed,
1084 unsafety: this.lower_unsafety(f.unsafety),
1086 decl: this.lower_fn_decl(&f.decl, None, false),
1087 arg_names: this.lower_fn_args_to_names(&f.decl),
1093 TyKind::Never => hir::TyNever,
1094 TyKind::Tup(ref tys) => {
1095 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty, itctx)).collect())
1097 TyKind::Paren(ref ty) => {
1098 return self.lower_ty(ty, itctx);
1100 TyKind::Path(ref qself, ref path) => {
1101 let id = self.lower_node_id(t.id);
1102 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1103 let ty = self.ty_path(id, t.span, qpath);
1104 if let hir::TyTraitObject(..) = ty.node {
1105 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1109 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1112 def: self.expect_full_def(t.id),
1113 segments: hir_vec![hir::PathSegment::from_name(keywords::SelfType.name())],
1117 TyKind::Array(ref ty, ref length) => {
1118 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1120 TyKind::Typeof(ref expr) => {
1121 hir::TyTypeof(self.lower_anon_const(expr))
1123 TyKind::TraitObject(ref bounds, kind) => {
1124 let mut lifetime_bound = None;
1127 .filter_map(|bound| match *bound {
1128 TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
1129 Some(self.lower_poly_trait_ref(ty, itctx))
1131 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1132 RegionTyParamBound(ref lifetime) => {
1133 if lifetime_bound.is_none() {
1134 lifetime_bound = Some(self.lower_lifetime(lifetime));
1140 let lifetime_bound =
1141 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1142 if kind != TraitObjectSyntax::Dyn {
1143 self.maybe_lint_bare_trait(t.span, t.id, false);
1145 hir::TyTraitObject(bounds, lifetime_bound)
1147 TyKind::ImplTrait(ref bounds) => {
1150 ImplTraitContext::Existential(fn_def_id) => {
1152 // We need to manually repeat the code of `next_id` because the lowering
1153 // needs to happen while the owner_id is pointing to the item itself,
1154 // because items are their own owners
1155 let exist_ty_node_id = self.sess.next_node_id();
1157 // Make sure we know that some funky desugaring has been going on here.
1158 // This is a first: there is code in other places like for loop
1159 // desugaring that explicitly states that we don't want to track that.
1160 // Not tracking it makes lints in rustc and clippy very fragile as
1161 // frequently opened issues show.
1162 let exist_ty_span = self.allow_internal_unstable(
1163 CompilerDesugaringKind::ExistentialReturnType,
1167 // Pull a new definition from the ether
1168 let exist_ty_def_index = self
1171 .create_def_with_parent(
1174 DefPathData::ExistentialImplTrait,
1175 DefIndexAddressSpace::High,
1180 // the `t` is just for printing debug messages
1181 self.allocate_hir_id_counter(exist_ty_node_id, t);
1183 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1184 lctx.lower_bounds(bounds, itctx)
1187 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1193 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1194 let exist_ty_item_kind = hir::ItemExistential(hir::ExistTy {
1195 generics: hir::Generics {
1196 params: lifetime_defs,
1197 where_clause: hir::WhereClause {
1198 id: lctx.next_id().node_id,
1199 predicates: Vec::new().into(),
1204 impl_trait_fn: Some(fn_def_id),
1206 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1207 // Generate an `existential type Foo: Trait;` declaration
1208 trace!("creating existential type with id {:#?}", exist_ty_id);
1209 // Set the name to `impl Bound1 + Bound2`
1210 let exist_ty_name = Symbol::intern(&pprust::ty_to_string(t));
1212 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1213 let exist_ty_item = hir::Item {
1214 id: exist_ty_id.node_id,
1215 hir_id: exist_ty_id.hir_id,
1216 name: exist_ty_name,
1217 attrs: Default::default(),
1218 node: exist_ty_item_kind,
1219 vis: hir::Visibility::Inherited,
1220 span: exist_ty_span,
1223 // Insert the item into the global list. This usually happens
1224 // automatically for all AST items. But this existential type item
1225 // does not actually exist in the AST.
1226 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1228 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1229 hir::TyImplTraitExistential(
1231 id: exist_ty_id.node_id
1233 DefId::local(exist_ty_def_index),
1238 ImplTraitContext::Universal(def_id) => {
1239 let def_node_id = self.next_id().node_id;
1241 // Add a definition for the in-band TyParam
1242 let def_index = self.resolver.definitions().create_def_with_parent(
1245 DefPathData::UniversalImplTrait,
1246 DefIndexAddressSpace::High,
1251 let hir_bounds = self.lower_bounds(bounds, itctx);
1252 // Set the name to `impl Bound1 + Bound2`
1253 let name = Symbol::intern(&pprust::ty_to_string(t));
1254 self.in_band_ty_params.push(hir::TyParam {
1260 pure_wrt_drop: false,
1261 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1265 hir::TyPath(hir::QPath::Resolved(
1269 def: Def::TyParam(DefId::local(def_index)),
1270 segments: hir_vec![hir::PathSegment::from_name(name)],
1274 ImplTraitContext::Disallowed => {
1279 "`impl Trait` not allowed outside of function \
1280 and inherent method return types"
1286 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1289 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1298 fn lifetimes_from_impl_trait_bounds(
1300 exist_ty_id: NodeId,
1301 parent_index: DefIndex,
1302 bounds: &hir::TyParamBounds,
1303 ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1304 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1305 // appear in the bounds, excluding lifetimes that are created within the bounds.
1306 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1307 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1308 context: &'r mut LoweringContext<'a>,
1310 exist_ty_id: NodeId,
1311 collect_elided_lifetimes: bool,
1312 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1313 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1314 output_lifetimes: Vec<hir::Lifetime>,
1315 output_lifetime_params: Vec<hir::GenericParam>,
1318 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1319 fn nested_visit_map<'this>(
1321 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1322 hir::intravisit::NestedVisitorMap::None
1325 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1326 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1327 if parameters.parenthesized {
1328 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1329 self.collect_elided_lifetimes = false;
1330 hir::intravisit::walk_generic_args(self, span, parameters);
1331 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1333 hir::intravisit::walk_generic_args(self, span, parameters);
1337 fn visit_ty(&mut self, t: &'v hir::Ty) {
1338 // Don't collect elided lifetimes used inside of `fn()` syntax
1339 if let &hir::Ty_::TyBareFn(_) = &t.node {
1340 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1341 self.collect_elided_lifetimes = false;
1343 // Record the "stack height" of `for<'a>` lifetime bindings
1344 // to be able to later fully undo their introduction.
1345 let old_len = self.currently_bound_lifetimes.len();
1346 hir::intravisit::walk_ty(self, t);
1347 self.currently_bound_lifetimes.truncate(old_len);
1349 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1351 hir::intravisit::walk_ty(self, t);
1355 fn visit_poly_trait_ref(
1357 trait_ref: &'v hir::PolyTraitRef,
1358 modifier: hir::TraitBoundModifier,
1360 // Record the "stack height" of `for<'a>` lifetime bindings
1361 // to be able to later fully undo their introduction.
1362 let old_len = self.currently_bound_lifetimes.len();
1363 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1364 self.currently_bound_lifetimes.truncate(old_len);
1367 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1368 // Record the introduction of 'a in `for<'a> ...`
1369 if let hir::GenericParam::Lifetime(ref lt_def) = *param {
1370 // Introduce lifetimes one at a time so that we can handle
1371 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1372 self.currently_bound_lifetimes.push(lt_def.lifetime.name);
1375 hir::intravisit::walk_generic_param(self, param);
1378 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1379 let name = match lifetime.name {
1380 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1381 if self.collect_elided_lifetimes {
1382 // Use `'_` for both implicit and underscore lifetimes in
1383 // `abstract type Foo<'_>: SomeTrait<'_>;`
1384 hir::LifetimeName::Underscore
1389 name @ hir::LifetimeName::Fresh(_) => name,
1390 name @ hir::LifetimeName::Name(_) => name,
1391 hir::LifetimeName::Static => return,
1394 if !self.currently_bound_lifetimes.contains(&name)
1395 && !self.already_defined_lifetimes.contains(&name)
1397 self.already_defined_lifetimes.insert(name);
1399 self.output_lifetimes.push(hir::Lifetime {
1400 id: self.context.next_id().node_id,
1401 span: lifetime.span,
1405 // We need to manually create the ids here, because the
1406 // definitions will go into the explicit `existential type`
1407 // declaration and thus need to have their owner set to that item
1408 let def_node_id = self.context.sess.next_node_id();
1409 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1410 self.context.resolver.definitions().create_def_with_parent(
1413 DefPathData::LifetimeDef(name.name().as_interned_str()),
1414 DefIndexAddressSpace::High,
1418 let def_lifetime = hir::Lifetime {
1420 span: lifetime.span,
1423 self.output_lifetime_params
1424 .push(hir::GenericParam::Lifetime(hir::LifetimeDef {
1425 lifetime: def_lifetime,
1426 bounds: Vec::new().into(),
1427 pure_wrt_drop: false,
1434 let mut lifetime_collector = ImplTraitLifetimeCollector {
1436 parent: parent_index,
1438 collect_elided_lifetimes: true,
1439 currently_bound_lifetimes: Vec::new(),
1440 already_defined_lifetimes: HashSet::new(),
1441 output_lifetimes: Vec::new(),
1442 output_lifetime_params: Vec::new(),
1445 for bound in bounds {
1446 hir::intravisit::walk_ty_param_bound(&mut lifetime_collector, &bound);
1450 lifetime_collector.output_lifetimes.into(),
1451 lifetime_collector.output_lifetime_params.into(),
1455 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1460 .map(|x| self.lower_foreign_item(x))
1465 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1472 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1474 node: hir::Variant_ {
1475 name: v.node.ident.name,
1476 attrs: self.lower_attrs(&v.node.attrs),
1477 data: self.lower_variant_data(&v.node.data),
1478 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1487 qself: &Option<QSelf>,
1489 param_mode: ParamMode,
1490 itctx: ImplTraitContext,
1492 let qself_position = qself.as_ref().map(|q| q.position);
1493 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx));
1495 let resolution = self.resolver
1497 .unwrap_or(PathResolution::new(Def::Err));
1499 let proj_start = p.segments.len() - resolution.unresolved_segments();
1500 let path = P(hir::Path {
1501 def: resolution.base_def(),
1502 segments: p.segments[..proj_start]
1505 .map(|(i, segment)| {
1506 let param_mode = match (qself_position, param_mode) {
1507 (Some(j), ParamMode::Optional) if i < j => {
1508 // This segment is part of the trait path in a
1509 // qualified path - one of `a`, `b` or `Trait`
1510 // in `<X as a::b::Trait>::T::U::method`.
1516 // Figure out if this is a type/trait segment,
1517 // which may need lifetime elision performed.
1518 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1519 krate: def_id.krate,
1520 index: this.def_key(def_id).parent.expect("missing parent"),
1522 let type_def_id = match resolution.base_def() {
1523 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1524 Some(parent_def_id(self, def_id))
1526 Def::Variant(def_id) if i + 1 == proj_start => {
1527 Some(parent_def_id(self, def_id))
1530 | Def::Union(def_id)
1532 | Def::TyAlias(def_id)
1533 | Def::Trait(def_id) if i + 1 == proj_start =>
1539 let parenthesized_generic_args = match resolution.base_def() {
1540 // `a::b::Trait(Args)`
1541 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1542 // `a::b::Trait(Args)::TraitItem`
1543 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1544 if i + 2 == proj_start =>
1546 ParenthesizedGenericArgs::Ok
1548 // Avoid duplicated errors
1549 Def::Err => ParenthesizedGenericArgs::Ok,
1555 | Def::Variant(..) if i + 1 == proj_start =>
1557 ParenthesizedGenericArgs::Err
1559 // A warning for now, for compatibility reasons
1560 _ => ParenthesizedGenericArgs::Warn,
1563 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1564 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1567 assert!(!def_id.is_local());
1569 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1570 let n = item_generics.own_counts().lifetimes;
1571 self.type_def_lifetime_params.insert(def_id, n);
1574 self.lower_path_segment(
1579 parenthesized_generic_args,
1587 // Simple case, either no projections, or only fully-qualified.
1588 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1589 if resolution.unresolved_segments() == 0 {
1590 return hir::QPath::Resolved(qself, path);
1593 // Create the innermost type that we're projecting from.
1594 let mut ty = if path.segments.is_empty() {
1595 // If the base path is empty that means there exists a
1596 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1597 qself.expect("missing QSelf for <T>::...")
1599 // Otherwise, the base path is an implicit `Self` type path,
1600 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1601 // `<I as Iterator>::Item::default`.
1602 let new_id = self.next_id();
1603 self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
1606 // Anything after the base path are associated "extensions",
1607 // out of which all but the last one are associated types,
1608 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1609 // * base path is `std::vec::Vec<T>`
1610 // * "extensions" are `IntoIter`, `Item` and `clone`
1611 // * type nodes are:
1612 // 1. `std::vec::Vec<T>` (created above)
1613 // 2. `<std::vec::Vec<T>>::IntoIter`
1614 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1615 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1616 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1617 let segment = P(self.lower_path_segment(
1622 ParenthesizedGenericArgs::Warn,
1625 let qpath = hir::QPath::TypeRelative(ty, segment);
1627 // It's finished, return the extension of the right node type.
1628 if i == p.segments.len() - 1 {
1632 // Wrap the associated extension in another type node.
1633 let new_id = self.next_id();
1634 ty = self.ty_path(new_id, p.span, qpath);
1637 // Should've returned in the for loop above.
1640 "lower_qpath: no final extension segment in {}..{}",
1646 fn lower_path_extra(
1651 param_mode: ParamMode,
1655 segments: p.segments
1658 self.lower_path_segment(
1663 ParenthesizedGenericArgs::Err,
1664 ImplTraitContext::Disallowed,
1667 .chain(name.map(|name| hir::PathSegment::from_name(name)))
1673 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1674 let def = self.expect_full_def(id);
1675 self.lower_path_extra(def, p, None, param_mode)
1678 fn lower_path_segment(
1681 segment: &PathSegment,
1682 param_mode: ParamMode,
1683 expected_lifetimes: usize,
1684 parenthesized_generic_args: ParenthesizedGenericArgs,
1685 itctx: ImplTraitContext,
1686 ) -> hir::PathSegment {
1687 let (mut generic_args, infer_types) =
1688 if let Some(ref generic_args) = segment.parameters {
1689 let msg = "parenthesized parameters may only be used with a trait";
1690 match **generic_args {
1691 GenericArgs::AngleBracketed(ref data) => {
1692 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1694 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1695 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1696 ParenthesizedGenericArgs::Warn => {
1697 self.sess.buffer_lint(
1698 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1703 (hir::GenericArgs::none(), true)
1705 ParenthesizedGenericArgs::Err => {
1706 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1707 .span_label(data.span, "only traits may use parentheses")
1709 (hir::GenericArgs::none(), true)
1714 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1717 if !generic_args.parenthesized && generic_args.lifetimes().count() == 0 {
1718 generic_args.parameters = (0..expected_lifetimes).map(|_| {
1719 GenericArg::Lifetime(self.elided_lifetime(path_span))
1720 }).chain(generic_args.parameters.into_iter()).collect();
1723 hir::PathSegment::new(
1724 self.lower_ident(segment.identifier),
1730 fn lower_angle_bracketed_parameter_data(
1732 data: &AngleBracketedParameterData,
1733 param_mode: ParamMode,
1734 itctx: ImplTraitContext,
1735 ) -> (hir::GenericArgs, bool) {
1736 let &AngleBracketedParameterData { ref parameters, ref bindings, .. } = data;
1738 parameters: parameters.iter().map(|p| self.lower_generic_arg(p, itctx)).collect(),
1739 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1740 parenthesized: false,
1742 data.types().count() == 0 && param_mode == ParamMode::Optional)
1745 fn lower_parenthesized_parameter_data(
1747 data: &ParenthesizedParameterData,
1748 ) -> (hir::PathParameters, bool) {
1749 // Switch to `PassThrough` mode for anonymous lifetimes: this
1750 // means that we permit things like `&Ref<T>`, where `Ref` has
1751 // a hidden lifetime parameter. This is needed for backwards
1752 // compatibility, even in contexts like an impl header where
1753 // we generally don't permit such things (see #51008).
1754 self.with_anonymous_lifetime_mode(
1755 AnonymousLifetimeMode::PassThrough,
1757 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1758 let &ParenthesizedParameterData {
1765 .map(|ty| this.lower_ty(ty, DISALLOWED))
1767 let mk_tup = |this: &mut Self, tys, span| {
1768 let LoweredNodeId { node_id, hir_id } = this.next_id();
1770 node: hir::TyTup(tys),
1779 parameters: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1782 id: this.next_id().node_id,
1783 name: Symbol::intern(FN_OUTPUT_NAME),
1786 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1787 .unwrap_or_else(|| mk_tup(this, hir::HirVec::new(), span)),
1788 span: output.as_ref().map_or(span, |ty| ty.span),
1791 parenthesized: true,
1799 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1800 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1806 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1807 pat: self.lower_pat(&l.pat),
1808 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1810 attrs: l.attrs.clone(),
1811 source: hir::LocalSource::Normal,
1815 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1817 Mutability::Mutable => hir::MutMutable,
1818 Mutability::Immutable => hir::MutImmutable,
1822 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1823 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1827 pat: self.lower_pat(&arg.pat),
1831 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1834 .map(|arg| match arg.pat.node {
1835 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1836 _ => respan(arg.pat.span, keywords::Invalid.name()),
1844 fn_def_id: Option<DefId>,
1845 impl_trait_return_allow: bool,
1846 ) -> P<hir::FnDecl> {
1847 // NOTE: The two last parameters here have to do with impl Trait. If fn_def_id is Some,
1848 // then impl Trait arguments are lowered into generic parameters on the given
1849 // fn_def_id, otherwise impl Trait is disallowed. (for now)
1851 // Furthermore, if impl_trait_return_allow is true, then impl Trait may be used in
1852 // return positions as well. This guards against trait declarations and their impls
1853 // where impl Trait is disallowed. (again for now)
1858 if let Some(def_id) = fn_def_id {
1859 self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1861 self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1865 output: match decl.output {
1866 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1867 Some(def_id) if impl_trait_return_allow => {
1868 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1870 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1872 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1874 variadic: decl.variadic,
1875 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1876 TyKind::ImplicitSelf => true,
1877 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1883 fn lower_ty_param_bound(
1886 itctx: ImplTraitContext,
1887 ) -> hir::TyParamBound {
1889 TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound(
1890 self.lower_poly_trait_ref(ty, itctx),
1891 self.lower_trait_bound_modifier(modifier),
1893 RegionTyParamBound(ref lifetime) => {
1894 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
1902 add_bounds: &[TyParamBound],
1903 itctx: ImplTraitContext,
1905 let mut name = self.lower_ident(tp.ident);
1907 // Don't expose `Self` (recovered "keyword used as ident" parse error).
1908 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1909 // Instead, use gensym("Self") to create a distinct name that looks the same.
1910 if name == keywords::SelfType.name() {
1911 name = Symbol::gensym("Self");
1914 let mut bounds = self.lower_bounds(&tp.bounds, itctx);
1915 if !add_bounds.is_empty() {
1918 .chain(self.lower_bounds(add_bounds, itctx).into_iter())
1923 id: self.lower_node_id(tp.id).node_id,
1928 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
1929 span: tp.ident.span,
1930 pure_wrt_drop: attr::contains_name(&tp.attrs, "may_dangle"),
1933 .filter(|attr| attr.check_name("rustc_synthetic"))
1934 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
1936 attrs: self.lower_attrs(&tp.attrs),
1940 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1941 let span = l.ident.span;
1942 match self.lower_ident(l.ident) {
1943 x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
1944 x if x == "'_" => match self.anonymous_lifetime_mode {
1945 AnonymousLifetimeMode::CreateParameter => {
1946 let fresh_name = self.collect_fresh_in_band_lifetime(span);
1947 self.new_named_lifetime(l.id, span, fresh_name)
1950 AnonymousLifetimeMode::PassThrough => {
1951 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1955 self.maybe_collect_in_band_lifetime(span, name);
1956 self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name))
1961 fn new_named_lifetime(
1965 name: hir::LifetimeName,
1966 ) -> hir::Lifetime {
1968 id: self.lower_node_id(id).node_id,
1974 fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef {
1975 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1976 self.is_collecting_in_band_lifetimes = false;
1978 let def = hir::LifetimeDef {
1979 lifetime: self.lower_lifetime(&l.lifetime),
1980 bounds: l.bounds.iter().map(|l| self.lower_lifetime(l)).collect(),
1981 pure_wrt_drop: attr::contains_name(&l.attrs, "may_dangle"),
1985 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1990 fn lower_generic_params(
1992 params: &Vec<GenericParam>,
1993 add_bounds: &NodeMap<Vec<TyParamBound>>,
1994 itctx: ImplTraitContext,
1995 ) -> hir::HirVec<hir::GenericParam> {
1998 .map(|param| match *param {
1999 GenericParam::Lifetime(ref lifetime_def) => {
2000 hir::GenericParam::Lifetime(self.lower_lifetime_def(lifetime_def))
2002 GenericParam::Type(ref ty_param) => hir::GenericParam::Type(self.lower_ty_param(
2004 add_bounds.get(&ty_param.id).map_or(&[][..], |x| &x),
2011 fn lower_generics(&mut self, g: &Generics, itctx: ImplTraitContext) -> hir::Generics {
2012 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2013 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2014 // paths where report_error is called are also the only paths that advance to after
2015 // the match statement, so the error reporting could probably just be moved there.
2016 let mut add_bounds = NodeMap();
2017 for pred in &g.where_clause.predicates {
2018 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2019 'next_bound: for bound in &bound_pred.bounds {
2020 if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
2021 let report_error = |this: &mut Self| {
2022 this.diagnostic().span_err(
2023 bound_pred.bounded_ty.span,
2024 "`?Trait` bounds are only permitted at the \
2025 point where a type parameter is declared",
2028 // Check if the where clause type is a plain type parameter.
2029 match bound_pred.bounded_ty.node {
2030 TyKind::Path(None, ref path)
2031 if path.segments.len() == 1
2032 && bound_pred.bound_generic_params.is_empty() =>
2034 if let Some(Def::TyParam(def_id)) = self.resolver
2035 .get_resolution(bound_pred.bounded_ty.id)
2036 .map(|d| d.base_def())
2038 if let Some(node_id) =
2039 self.resolver.definitions().as_local_node_id(def_id)
2041 for param in &g.params {
2042 if let GenericParam::Type(ref ty_param) = *param {
2043 if node_id == ty_param.id {
2046 .or_insert(Vec::new())
2047 .push(bound.clone());
2048 continue 'next_bound;
2056 _ => report_error(self),
2064 params: self.lower_generic_params(&g.params, &add_bounds, itctx),
2065 where_clause: self.lower_where_clause(&g.where_clause),
2070 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2072 id: self.lower_node_id(wc.id).node_id,
2073 predicates: wc.predicates
2075 .map(|predicate| self.lower_where_predicate(predicate))
2080 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2082 WherePredicate::BoundPredicate(WhereBoundPredicate {
2083 ref bound_generic_params,
2088 self.with_in_scope_lifetime_defs(
2089 bound_generic_params.iter().filter_map(|p| match p {
2090 GenericParam::Lifetime(ld) => Some(ld),
2094 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2095 bound_generic_params: this.lower_generic_params(
2096 bound_generic_params,
2098 ImplTraitContext::Disallowed,
2100 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2103 .filter_map(|bound| match *bound {
2104 // Ignore `?Trait` bounds.
2105 // Tthey were copied into type parameters already.
2106 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
2107 _ => Some(this.lower_ty_param_bound(
2109 ImplTraitContext::Disallowed,
2118 WherePredicate::RegionPredicate(WhereRegionPredicate {
2122 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2124 lifetime: self.lower_lifetime(lifetime),
2127 .map(|bound| self.lower_lifetime(bound))
2130 WherePredicate::EqPredicate(WhereEqPredicate {
2135 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2136 id: self.lower_node_id(id).node_id,
2137 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2138 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2144 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2146 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2150 .map(|f| self.lower_struct_field(f))
2152 self.lower_node_id(id).node_id,
2154 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2158 .map(|f| self.lower_struct_field(f))
2160 self.lower_node_id(id).node_id,
2162 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2166 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2167 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2168 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2169 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2173 ref_id: self.lower_node_id(p.ref_id).node_id,
2177 fn lower_poly_trait_ref(
2180 itctx: ImplTraitContext,
2181 ) -> hir::PolyTraitRef {
2182 let bound_generic_params =
2183 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2184 let trait_ref = self.with_parent_impl_lifetime_defs(
2185 &bound_generic_params
2187 .filter_map(|p| match *p {
2188 hir::GenericParam::Lifetime(ref ld) => Some(ld.clone()),
2191 .collect::<Vec<_>>(),
2192 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2196 bound_generic_params,
2202 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2205 id: self.lower_node_id(f.id).node_id,
2206 ident: match f.ident {
2207 Some(ident) => ident,
2208 // FIXME(jseyfried) positional field hygiene
2209 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2211 vis: self.lower_visibility(&f.vis, None),
2212 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2213 attrs: self.lower_attrs(&f.attrs),
2217 fn lower_field(&mut self, f: &Field) -> hir::Field {
2219 id: self.next_id().node_id,
2221 expr: P(self.lower_expr(&f.expr)),
2223 is_shorthand: f.is_shorthand,
2227 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2229 ty: self.lower_ty(&mt.ty, itctx),
2230 mutbl: self.lower_mutability(mt.mutbl),
2236 bounds: &[TyParamBound],
2237 itctx: ImplTraitContext,
2238 ) -> hir::TyParamBounds {
2241 .map(|bound| self.lower_ty_param_bound(bound, itctx))
2245 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2246 let mut expr = None;
2248 let mut stmts = vec![];
2250 for (index, stmt) in b.stmts.iter().enumerate() {
2251 if index == b.stmts.len() - 1 {
2252 if let StmtKind::Expr(ref e) = stmt.node {
2253 expr = Some(P(self.lower_expr(e)));
2255 stmts.extend(self.lower_stmt(stmt));
2258 stmts.extend(self.lower_stmt(stmt));
2262 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2267 stmts: stmts.into(),
2269 rules: self.lower_block_check_mode(&b.rules),
2272 recovered: b.recovered,
2280 attrs: &hir::HirVec<Attribute>,
2281 vis: &mut hir::Visibility,
2285 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2286 ItemKind::Use(ref use_tree) => {
2287 // Start with an empty prefix
2290 span: use_tree.span,
2293 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2295 ItemKind::Static(ref t, m, ref e) => {
2296 let value = self.lower_body(None, |this| this.lower_expr(e));
2298 self.lower_ty(t, ImplTraitContext::Disallowed),
2299 self.lower_mutability(m),
2303 ItemKind::Const(ref t, ref e) => {
2304 let value = self.lower_body(None, |this| this.lower_expr(e));
2305 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2307 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
2308 let fn_def_id = self.resolver.definitions().local_def_id(id);
2309 self.with_new_scopes(|this| {
2310 let body_id = this.lower_body(Some(decl), |this| {
2311 let body = this.lower_block(body, false);
2312 this.expr_block(body, ThinVec::new())
2314 let (generics, fn_decl) = this.add_in_band_defs(
2317 AnonymousLifetimeMode::PassThrough,
2318 |this| this.lower_fn_decl(decl, Some(fn_def_id), true),
2323 this.lower_unsafety(unsafety),
2324 this.lower_constness(constness),
2331 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2332 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2333 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2334 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2335 self.lower_ty(t, ImplTraitContext::Disallowed),
2336 self.lower_generics(generics, ImplTraitContext::Disallowed),
2338 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2340 variants: enum_definition
2343 .map(|x| self.lower_variant(x))
2346 self.lower_generics(generics, ImplTraitContext::Disallowed),
2348 ItemKind::Struct(ref struct_def, ref generics) => {
2349 let struct_def = self.lower_variant_data(struct_def);
2352 self.lower_generics(generics, ImplTraitContext::Disallowed),
2355 ItemKind::Union(ref vdata, ref generics) => {
2356 let vdata = self.lower_variant_data(vdata);
2359 self.lower_generics(generics, ImplTraitContext::Disallowed),
2371 let def_id = self.resolver.definitions().local_def_id(id);
2373 // Lower the "impl header" first. This ordering is important
2374 // for in-band lifetimes! Consider `'a` here:
2376 // impl Foo<'a> for u32 {
2377 // fn method(&'a self) { .. }
2380 // Because we start by lowering the `Foo<'a> for u32`
2381 // part, we will add `'a` to the list of generics on
2382 // the impl. When we then encounter it later in the
2383 // method, it will not be considered an in-band
2384 // lifetime to be added, but rather a reference to a
2386 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2389 AnonymousLifetimeMode::CreateParameter,
2391 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2392 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2395 if let Some(ref trait_ref) = trait_ref {
2396 if let Def::Trait(def_id) = trait_ref.path.def {
2397 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2401 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2403 (trait_ref, lowered_ty)
2407 let new_impl_items = self.with_in_scope_lifetime_defs(
2408 ast_generics.params.iter().filter_map(|p| match p {
2409 GenericParam::Lifetime(ld) => Some(ld),
2415 .map(|item| this.lower_impl_item_ref(item))
2421 self.lower_unsafety(unsafety),
2422 self.lower_impl_polarity(polarity),
2423 self.lower_defaultness(defaultness, true /* [1] */),
2430 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2431 let bounds = self.lower_bounds(bounds, ImplTraitContext::Disallowed);
2434 .map(|item| self.lower_trait_item_ref(item))
2437 self.lower_is_auto(is_auto),
2438 self.lower_unsafety(unsafety),
2439 self.lower_generics(generics, ImplTraitContext::Disallowed),
2444 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2445 self.lower_generics(generics, ImplTraitContext::Disallowed),
2446 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2448 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2451 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2452 // not cause an assertion failure inside the `lower_defaultness` function
2460 vis: &mut hir::Visibility,
2462 attrs: &hir::HirVec<Attribute>,
2464 let path = &tree.prefix;
2467 UseTreeKind::Simple(rename, id1, id2) => {
2468 *name = tree.ident().name;
2470 // First apply the prefix to the path
2471 let mut path = Path {
2475 .chain(path.segments.iter())
2481 // Correctly resolve `self` imports
2482 if path.segments.len() > 1
2483 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2485 let _ = path.segments.pop();
2486 if rename.is_none() {
2487 *name = path.segments.last().unwrap().ident.name;
2491 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2492 let mut defs = self.expect_full_def_from_use(id);
2493 // we want to return *something* from this function, so hang onto the first item
2495 let mut ret_def = defs.next().unwrap_or(Def::Err);
2497 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2498 let vis = vis.clone();
2499 let name = name.clone();
2500 let span = path.span;
2501 self.resolver.definitions().create_def_with_parent(
2505 DefIndexAddressSpace::High,
2508 self.allocate_hir_id_counter(new_node_id, &path);
2510 self.with_hir_id_owner(new_node_id, |this| {
2511 let new_id = this.lower_node_id(new_node_id);
2512 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2513 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2514 let vis = match vis {
2515 hir::Visibility::Public => hir::Visibility::Public,
2516 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2517 hir::Visibility::Inherited => hir::Visibility::Inherited,
2518 hir::Visibility::Restricted { ref path, id: _ } => {
2519 hir::Visibility::Restricted {
2521 // We are allocating a new NodeId here
2522 id: this.next_id().node_id,
2531 hir_id: new_id.hir_id,
2533 attrs: attrs.clone(),
2542 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2543 hir::ItemUse(path, hir::UseKind::Single)
2545 UseTreeKind::Glob => {
2546 let path = P(self.lower_path(
2552 .chain(path.segments.iter())
2557 ParamMode::Explicit,
2559 hir::ItemUse(path, hir::UseKind::Glob)
2561 UseTreeKind::Nested(ref trees) => {
2566 .chain(path.segments.iter())
2569 span: prefix.span.to(path.span),
2572 // Add all the nested PathListItems in the HIR
2573 for &(ref use_tree, id) in trees {
2574 self.allocate_hir_id_counter(id, &use_tree);
2578 } = self.lower_node_id(id);
2580 let mut vis = vis.clone();
2581 let mut name = name.clone();
2583 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2585 self.with_hir_id_owner(new_id, |this| {
2586 let vis = match vis {
2587 hir::Visibility::Public => hir::Visibility::Public,
2588 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2589 hir::Visibility::Inherited => hir::Visibility::Inherited,
2590 hir::Visibility::Restricted { ref path, id: _ } => {
2591 hir::Visibility::Restricted {
2593 // We are allocating a new NodeId here
2594 id: this.next_id().node_id,
2605 attrs: attrs.clone(),
2608 span: use_tree.span,
2614 // Privatize the degenerate import base, used only to check
2615 // the stability of `use a::{};`, to avoid it showing up as
2616 // a re-export by accident when `pub`, e.g. in documentation.
2617 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2618 *vis = hir::Inherited;
2619 hir::ItemUse(path, hir::UseKind::ListStem)
2624 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2625 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2626 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2628 let (generics, node) = match i.node {
2629 TraitItemKind::Const(ref ty, ref default) => (
2630 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2631 hir::TraitItemKind::Const(
2632 self.lower_ty(ty, ImplTraitContext::Disallowed),
2635 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2638 TraitItemKind::Method(ref sig, None) => {
2639 let names = self.lower_fn_args_to_names(&sig.decl);
2640 self.add_in_band_defs(
2643 AnonymousLifetimeMode::PassThrough,
2645 hir::TraitItemKind::Method(
2646 this.lower_method_sig(sig, trait_item_def_id, false),
2647 hir::TraitMethod::Required(names),
2652 TraitItemKind::Method(ref sig, Some(ref body)) => {
2653 let body_id = self.lower_body(Some(&sig.decl), |this| {
2654 let body = this.lower_block(body, false);
2655 this.expr_block(body, ThinVec::new())
2658 self.add_in_band_defs(
2661 AnonymousLifetimeMode::PassThrough,
2663 hir::TraitItemKind::Method(
2664 this.lower_method_sig(sig, trait_item_def_id, false),
2665 hir::TraitMethod::Provided(body_id),
2670 TraitItemKind::Type(ref bounds, ref default) => (
2671 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2672 hir::TraitItemKind::Type(
2673 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2676 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2679 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2685 name: self.lower_ident(i.ident),
2686 attrs: self.lower_attrs(&i.attrs),
2693 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2694 let (kind, has_default) = match i.node {
2695 TraitItemKind::Const(_, ref default) => {
2696 (hir::AssociatedItemKind::Const, default.is_some())
2698 TraitItemKind::Type(_, ref default) => {
2699 (hir::AssociatedItemKind::Type, default.is_some())
2701 TraitItemKind::Method(ref sig, ref default) => (
2702 hir::AssociatedItemKind::Method {
2703 has_self: sig.decl.has_self(),
2707 TraitItemKind::Macro(..) => unimplemented!(),
2710 id: hir::TraitItemId { node_id: i.id },
2711 name: self.lower_ident(i.ident),
2713 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2718 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2719 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2720 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2722 let (generics, node) = match i.node {
2723 ImplItemKind::Const(ref ty, ref expr) => {
2724 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
2726 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2727 hir::ImplItemKind::Const(
2728 self.lower_ty(ty, ImplTraitContext::Disallowed),
2733 ImplItemKind::Method(ref sig, ref body) => {
2734 let body_id = self.lower_body(Some(&sig.decl), |this| {
2735 let body = this.lower_block(body, false);
2736 this.expr_block(body, ThinVec::new())
2738 let impl_trait_return_allow = !self.is_in_trait_impl;
2740 self.add_in_band_defs(
2743 AnonymousLifetimeMode::PassThrough,
2745 hir::ImplItemKind::Method(
2746 this.lower_method_sig(
2749 impl_trait_return_allow,
2756 ImplItemKind::Type(ref ty) => (
2757 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2758 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2760 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2766 name: self.lower_ident(i.ident),
2767 attrs: self.lower_attrs(&i.attrs),
2769 vis: self.lower_visibility(&i.vis, None),
2770 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2775 // [1] since `default impl` is not yet implemented, this is always true in impls
2778 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
2780 id: hir::ImplItemId { node_id: i.id },
2781 name: self.lower_ident(i.ident),
2783 vis: self.lower_visibility(&i.vis, Some(i.id)),
2784 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2785 kind: match i.node {
2786 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
2787 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
2788 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
2789 has_self: sig.decl.has_self(),
2791 ImplItemKind::Macro(..) => unimplemented!(),
2795 // [1] since `default impl` is not yet implemented, this is always true in impls
2798 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
2801 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
2805 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
2807 ItemKind::Use(ref use_tree) => {
2808 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
2809 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
2812 ItemKind::MacroDef(..) => return SmallVector::new(),
2815 SmallVector::one(hir::ItemId { id: i.id })
2818 fn lower_item_id_use_tree(&mut self,
2821 vec: &mut SmallVector<hir::ItemId>)
2824 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
2825 vec.push(hir::ItemId { id });
2826 self.lower_item_id_use_tree(nested, id, vec);
2828 UseTreeKind::Glob => {}
2829 UseTreeKind::Simple(_, id1, id2) => {
2830 for (_, &id) in self.expect_full_def_from_use(base_id)
2832 .zip([id1, id2].iter())
2834 vec.push(hir::ItemId { id });
2840 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
2841 let mut name = i.ident.name;
2842 let mut vis = self.lower_visibility(&i.vis, None);
2843 let attrs = self.lower_attrs(&i.attrs);
2844 if let ItemKind::MacroDef(ref def) = i.node {
2845 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
2846 let body = self.lower_token_stream(def.stream());
2847 self.exported_macros.push(hir::MacroDef {
2860 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
2862 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2875 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
2876 let node_id = self.lower_node_id(i.id).node_id;
2877 let def_id = self.resolver.definitions().local_def_id(node_id);
2881 attrs: self.lower_attrs(&i.attrs),
2882 node: match i.node {
2883 ForeignItemKind::Fn(ref fdec, ref generics) => {
2884 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
2887 AnonymousLifetimeMode::PassThrough,
2890 // Disallow impl Trait in foreign items
2891 this.lower_fn_decl(fdec, None, false),
2892 this.lower_fn_args_to_names(fdec),
2897 hir::ForeignItemFn(fn_dec, fn_args, generics)
2899 ForeignItemKind::Static(ref t, m) => {
2900 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
2902 ForeignItemKind::Ty => hir::ForeignItemType,
2903 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
2905 vis: self.lower_visibility(&i.vis, None),
2910 fn lower_method_sig(
2914 impl_trait_return_allow: bool,
2915 ) -> hir::MethodSig {
2918 unsafety: self.lower_unsafety(sig.unsafety),
2919 constness: self.lower_constness(sig.constness),
2920 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow),
2924 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
2926 IsAuto::Yes => hir::IsAuto::Yes,
2927 IsAuto::No => hir::IsAuto::No,
2931 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
2933 Unsafety::Unsafe => hir::Unsafety::Unsafe,
2934 Unsafety::Normal => hir::Unsafety::Normal,
2938 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
2940 Constness::Const => hir::Constness::Const,
2941 Constness::NotConst => hir::Constness::NotConst,
2945 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
2947 UnOp::Deref => hir::UnDeref,
2948 UnOp::Not => hir::UnNot,
2949 UnOp::Neg => hir::UnNeg,
2953 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
2955 node: match b.node {
2956 BinOpKind::Add => hir::BiAdd,
2957 BinOpKind::Sub => hir::BiSub,
2958 BinOpKind::Mul => hir::BiMul,
2959 BinOpKind::Div => hir::BiDiv,
2960 BinOpKind::Rem => hir::BiRem,
2961 BinOpKind::And => hir::BiAnd,
2962 BinOpKind::Or => hir::BiOr,
2963 BinOpKind::BitXor => hir::BiBitXor,
2964 BinOpKind::BitAnd => hir::BiBitAnd,
2965 BinOpKind::BitOr => hir::BiBitOr,
2966 BinOpKind::Shl => hir::BiShl,
2967 BinOpKind::Shr => hir::BiShr,
2968 BinOpKind::Eq => hir::BiEq,
2969 BinOpKind::Lt => hir::BiLt,
2970 BinOpKind::Le => hir::BiLe,
2971 BinOpKind::Ne => hir::BiNe,
2972 BinOpKind::Ge => hir::BiGe,
2973 BinOpKind::Gt => hir::BiGt,
2979 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2980 let node = match p.node {
2981 PatKind::Wild => hir::PatKind::Wild,
2982 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2983 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
2984 // `None` can occur in body-less function signatures
2985 def @ None | def @ Some(Def::Local(_)) => {
2986 let canonical_id = match def {
2987 Some(Def::Local(id)) => id,
2990 hir::PatKind::Binding(
2991 self.lower_binding_mode(binding_mode),
2993 respan(ident.span, ident.name),
2994 sub.as_ref().map(|x| self.lower_pat(x)),
2997 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3002 segments: hir_vec![hir::PathSegment::from_name(ident.name)],
3007 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3008 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3009 let qpath = self.lower_qpath(
3013 ParamMode::Optional,
3014 ImplTraitContext::Disallowed,
3016 hir::PatKind::TupleStruct(
3018 pats.iter().map(|x| self.lower_pat(x)).collect(),
3022 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3026 ParamMode::Optional,
3027 ImplTraitContext::Disallowed,
3029 PatKind::Struct(ref path, ref fields, etc) => {
3030 let qpath = self.lower_qpath(
3034 ParamMode::Optional,
3035 ImplTraitContext::Disallowed,
3042 node: hir::FieldPat {
3043 id: self.next_id().node_id,
3044 ident: f.node.ident,
3045 pat: self.lower_pat(&f.node.pat),
3046 is_shorthand: f.node.is_shorthand,
3050 hir::PatKind::Struct(qpath, fs, etc)
3052 PatKind::Tuple(ref elts, ddpos) => {
3053 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3055 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3056 PatKind::Ref(ref inner, mutbl) => {
3057 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3059 PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
3060 P(self.lower_expr(e1)),
3061 P(self.lower_expr(e2)),
3062 self.lower_range_end(end),
3064 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3065 before.iter().map(|x| self.lower_pat(x)).collect(),
3066 slice.as_ref().map(|x| self.lower_pat(x)),
3067 after.iter().map(|x| self.lower_pat(x)).collect(),
3069 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3070 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3073 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3082 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3084 RangeEnd::Included(_) => hir::RangeEnd::Included,
3085 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3089 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3090 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3095 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3099 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3100 let kind = match e.node {
3101 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3102 ExprKind::ObsoleteInPlace(..) => {
3103 self.sess.abort_if_errors();
3104 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3106 ExprKind::Array(ref exprs) => {
3107 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3109 ExprKind::Repeat(ref expr, ref count) => {
3110 let expr = P(self.lower_expr(expr));
3111 let count = self.lower_anon_const(count);
3112 hir::ExprRepeat(expr, count)
3114 ExprKind::Tup(ref elts) => {
3115 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3117 ExprKind::Call(ref f, ref args) => {
3118 let f = P(self.lower_expr(f));
3119 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3121 ExprKind::MethodCall(ref seg, ref args) => {
3122 let hir_seg = self.lower_path_segment(
3125 ParamMode::Optional,
3127 ParenthesizedGenericArgs::Err,
3128 ImplTraitContext::Disallowed,
3130 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3131 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3133 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3134 let binop = self.lower_binop(binop);
3135 let lhs = P(self.lower_expr(lhs));
3136 let rhs = P(self.lower_expr(rhs));
3137 hir::ExprBinary(binop, lhs, rhs)
3139 ExprKind::Unary(op, ref ohs) => {
3140 let op = self.lower_unop(op);
3141 let ohs = P(self.lower_expr(ohs));
3142 hir::ExprUnary(op, ohs)
3144 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3145 ExprKind::Cast(ref expr, ref ty) => {
3146 let expr = P(self.lower_expr(expr));
3147 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3149 ExprKind::Type(ref expr, ref ty) => {
3150 let expr = P(self.lower_expr(expr));
3151 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3153 ExprKind::AddrOf(m, ref ohs) => {
3154 let m = self.lower_mutability(m);
3155 let ohs = P(self.lower_expr(ohs));
3156 hir::ExprAddrOf(m, ohs)
3158 // More complicated than you might expect because the else branch
3159 // might be `if let`.
3160 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3161 let else_opt = else_opt.as_ref().map(|els| {
3163 ExprKind::IfLet(..) => {
3164 // wrap the if-let expr in a block
3165 let span = els.span;
3166 let els = P(self.lower_expr(els));
3167 let LoweredNodeId { node_id, hir_id } = self.next_id();
3168 let blk = P(hir::Block {
3173 rules: hir::DefaultBlock,
3175 targeted_by_break: false,
3176 recovered: blk.recovered,
3178 P(self.expr_block(blk, ThinVec::new()))
3180 _ => P(self.lower_expr(els)),
3184 let then_blk = self.lower_block(blk, false);
3185 let then_expr = self.expr_block(then_blk, ThinVec::new());
3187 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3189 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3191 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3192 this.lower_block(body, false),
3193 this.lower_label(opt_label),
3196 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3198 this.lower_block(body, false),
3199 this.lower_label(opt_label),
3200 hir::LoopSource::Loop,
3203 ExprKind::Catch(ref body) => {
3204 self.with_catch_scope(body.id, |this| {
3206 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3207 let mut block = this.lower_block(body, true).into_inner();
3208 let tail = block.expr.take().map_or_else(
3210 let LoweredNodeId { node_id, hir_id } = this.next_id();
3211 let span = this.sess.codemap().end_point(unstable_span);
3215 node: hir::ExprTup(hir_vec![]),
3216 attrs: ThinVec::new(),
3220 |x: P<hir::Expr>| x.into_inner(),
3222 block.expr = Some(this.wrap_in_try_constructor(
3223 "from_ok", tail, unstable_span));
3224 hir::ExprBlock(P(block), None)
3227 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3228 P(self.lower_expr(expr)),
3229 arms.iter().map(|x| self.lower_arm(x)).collect(),
3230 hir::MatchSource::Normal,
3232 ExprKind::Closure(capture_clause, movability, ref decl, ref body, fn_decl_span) => {
3233 self.with_new_scopes(|this| {
3234 let mut is_generator = false;
3235 let body_id = this.lower_body(Some(decl), |this| {
3236 let e = this.lower_expr(body);
3237 is_generator = this.is_generator;
3240 let generator_option = if is_generator {
3241 if !decl.inputs.is_empty() {
3246 "generators cannot have explicit arguments"
3248 this.sess.abort_if_errors();
3250 Some(match movability {
3251 Movability::Movable => hir::GeneratorMovability::Movable,
3252 Movability::Static => hir::GeneratorMovability::Static,
3255 if movability == Movability::Static {
3260 "closures cannot be static"
3266 this.lower_capture_clause(capture_clause),
3267 this.lower_fn_decl(decl, None, false),
3274 ExprKind::Block(ref blk, opt_label) => {
3275 hir::ExprBlock(self.lower_block(blk,
3276 opt_label.is_some()),
3277 self.lower_label(opt_label))
3279 ExprKind::Assign(ref el, ref er) => {
3280 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3282 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3283 self.lower_binop(op),
3284 P(self.lower_expr(el)),
3285 P(self.lower_expr(er)),
3287 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3288 ExprKind::Index(ref el, ref er) => {
3289 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3291 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3292 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3293 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3294 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3295 let id = self.next_id();
3296 let e1 = self.lower_expr(e1);
3297 let e2 = self.lower_expr(e2);
3298 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], false));
3299 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3300 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3301 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3302 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3303 hir::ExprCall(new, hir_vec![e1, e2])
3305 ExprKind::Range(ref e1, ref e2, lims) => {
3306 use syntax::ast::RangeLimits::*;
3308 let path = match (e1, e2, lims) {
3309 (&None, &None, HalfOpen) => "RangeFull",
3310 (&Some(..), &None, HalfOpen) => "RangeFrom",
3311 (&None, &Some(..), HalfOpen) => "RangeTo",
3312 (&Some(..), &Some(..), HalfOpen) => "Range",
3313 (&None, &Some(..), Closed) => "RangeToInclusive",
3314 (&Some(..), &Some(..), Closed) => unreachable!(),
3315 (_, &None, Closed) => self.diagnostic()
3316 .span_fatal(e.span, "inclusive range with no end")
3320 let fields = e1.iter()
3321 .map(|e| ("start", e))
3322 .chain(e2.iter().map(|e| ("end", e)))
3324 let expr = P(self.lower_expr(&e));
3326 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3327 let ident = Ident::new(Symbol::intern(s), unstable_span);
3328 self.field(ident, expr, unstable_span)
3330 .collect::<P<[hir::Field]>>();
3332 let is_unit = fields.is_empty();
3334 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3335 let struct_path = iter::once("ops")
3336 .chain(iter::once(path))
3337 .collect::<Vec<_>>();
3338 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
3339 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3341 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3347 hir::ExprPath(struct_path)
3349 hir::ExprStruct(struct_path, fields, None)
3351 span: unstable_span,
3352 attrs: e.attrs.clone(),
3355 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3359 ParamMode::Optional,
3360 ImplTraitContext::Disallowed,
3362 ExprKind::Break(opt_label, ref opt_expr) => {
3363 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3366 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3369 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3373 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3376 ExprKind::Continue(opt_label) => {
3377 hir::ExprAgain(if self.is_in_loop_condition && opt_label.is_none() {
3380 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3383 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3386 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3387 ExprKind::InlineAsm(ref asm) => {
3388 let hir_asm = hir::InlineAsm {
3389 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3390 outputs: asm.outputs
3392 .map(|out| hir::InlineAsmOutput {
3393 constraint: out.constraint.clone(),
3395 is_indirect: out.is_indirect,
3398 asm: asm.asm.clone(),
3399 asm_str_style: asm.asm_str_style,
3400 clobbers: asm.clobbers.clone().into(),
3401 volatile: asm.volatile,
3402 alignstack: asm.alignstack,
3403 dialect: asm.dialect,
3406 let outputs = asm.outputs
3408 .map(|out| self.lower_expr(&out.expr))
3410 let inputs = asm.inputs
3412 .map(|&(_, ref input)| self.lower_expr(input))
3414 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3416 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3421 ParamMode::Optional,
3422 ImplTraitContext::Disallowed,
3424 fields.iter().map(|x| self.lower_field(x)).collect(),
3425 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3427 ExprKind::Paren(ref ex) => {
3428 let mut ex = self.lower_expr(ex);
3429 // include parens in span, but only if it is a super-span.
3430 if e.span.contains(ex.span) {
3433 // merge attributes into the inner expression.
3434 let mut attrs = e.attrs.clone();
3435 attrs.extend::<Vec<_>>(ex.attrs.into());
3440 ExprKind::Yield(ref opt_expr) => {
3441 self.is_generator = true;
3444 .map(|x| self.lower_expr(x))
3445 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3446 hir::ExprYield(P(expr))
3449 // Desugar ExprIfLet
3450 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3451 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3454 // match <sub_expr> {
3456 // _ => [<else_opt> | ()]
3459 let mut arms = vec![];
3461 // `<pat> => <body>`
3463 let body = self.lower_block(body, false);
3464 let body_expr = P(self.expr_block(body, ThinVec::new()));
3465 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3466 arms.push(self.arm(pats, body_expr));
3469 // _ => [<else_opt>|()]
3471 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3472 let wildcard_pattern = self.pat_wild(e.span);
3473 let body = if let Some(else_expr) = wildcard_arm {
3474 P(self.lower_expr(else_expr))
3476 self.expr_tuple(e.span, hir_vec![])
3478 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3481 let contains_else_clause = else_opt.is_some();
3483 let sub_expr = P(self.lower_expr(sub_expr));
3488 hir::MatchSource::IfLetDesugar {
3489 contains_else_clause,
3494 // Desugar ExprWhileLet
3495 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3496 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3499 // [opt_ident]: loop {
3500 // match <sub_expr> {
3506 // Note that the block AND the condition are evaluated in the loop scope.
3507 // This is done to allow `break` from inside the condition of the loop.
3508 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3510 this.lower_block(body, false),
3511 this.expr_break(e.span, ThinVec::new()),
3512 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3516 // `<pat> => <body>`
3518 let body_expr = P(self.expr_block(body, ThinVec::new()));
3519 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3520 self.arm(pats, body_expr)
3525 let pat_under = self.pat_wild(e.span);
3526 self.arm(hir_vec![pat_under], break_expr)
3529 // `match <sub_expr> { ... }`
3530 let arms = hir_vec![pat_arm, break_arm];
3531 let match_expr = self.expr(
3533 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3537 // `[opt_ident]: loop { ... }`
3538 let loop_block = P(self.block_expr(P(match_expr)));
3539 let loop_expr = hir::ExprLoop(
3541 self.lower_label(opt_label),
3542 hir::LoopSource::WhileLet,
3544 // add attributes to the outer returned expr node
3548 // Desugar ExprForLoop
3549 // From: `[opt_ident]: for <pat> in <head> <body>`
3550 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3554 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3556 // [opt_ident]: loop {
3558 // match ::std::iter::Iterator::next(&mut iter) {
3559 // ::std::option::Option::Some(val) => __next = val,
3560 // ::std::option::Option::None => break
3562 // let <pat> = __next;
3563 // StmtExpr(<body>);
3571 let head = self.lower_expr(head);
3572 let head_sp = head.span;
3574 let iter = self.str_to_ident("iter");
3576 let next_ident = self.str_to_ident("__next");
3577 let next_pat = self.pat_ident_binding_mode(
3580 hir::BindingAnnotation::Mutable,
3583 // `::std::option::Option::Some(val) => next = val`
3585 let val_ident = self.str_to_ident("val");
3586 let val_pat = self.pat_ident(pat.span, val_ident);
3587 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3588 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3589 let assign = P(self.expr(
3591 hir::ExprAssign(next_expr, val_expr),
3594 let some_pat = self.pat_some(pat.span, val_pat);
3595 self.arm(hir_vec![some_pat], assign)
3598 // `::std::option::Option::None => break`
3601 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3602 let pat = self.pat_none(e.span);
3603 self.arm(hir_vec![pat], break_expr)
3608 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3610 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3612 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3613 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3614 let next_path = &["iter", "Iterator", "next"];
3615 let next_path = P(self.expr_std_path(head_sp, next_path, ThinVec::new()));
3616 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3617 let arms = hir_vec![pat_arm, break_arm];
3621 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3625 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3627 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
3631 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
3633 // `let <pat> = __next`
3634 let pat = self.lower_pat(pat);
3635 let pat_let = self.stmt_let_pat(
3639 hir::LocalSource::ForLoopDesugar,
3642 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
3643 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3644 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
3646 let loop_block = P(self.block_all(
3648 hir_vec![next_let, match_stmt, pat_let, body_stmt],
3652 // `[opt_ident]: loop { ... }`
3653 let loop_expr = hir::ExprLoop(
3655 self.lower_label(opt_label),
3656 hir::LoopSource::ForLoop,
3658 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3659 let loop_expr = P(hir::Expr {
3664 attrs: ThinVec::new(),
3667 // `mut iter => { ... }`
3668 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
3670 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
3671 let into_iter_expr = {
3672 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
3673 let into_iter = P(self.expr_std_path(head_sp, into_iter_path, ThinVec::new()));
3674 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
3677 let match_expr = P(self.expr_match(
3681 hir::MatchSource::ForLoopDesugar,
3684 // `{ let _result = ...; _result }`
3685 // underscore prevents an unused_variables lint if the head diverges
3686 let result_ident = self.str_to_ident("_result");
3687 let (let_stmt, let_stmt_binding) =
3688 self.stmt_let(e.span, false, result_ident, match_expr);
3690 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
3691 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
3692 // add the attributes to the outer returned expr node
3693 return self.expr_block(block, e.attrs.clone());
3696 // Desugar ExprKind::Try
3698 ExprKind::Try(ref sub_expr) => {
3701 // match Try::into_result(<expr>) {
3702 // Ok(val) => #[allow(unreachable_code)] val,
3703 // Err(err) => #[allow(unreachable_code)]
3704 // // If there is an enclosing `catch {...}`
3705 // break 'catch_target Try::from_error(From::from(err)),
3707 // return Try::from_error(From::from(err)),
3711 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
3713 // Try::into_result(<expr>)
3716 let sub_expr = self.lower_expr(sub_expr);
3718 let path = &["ops", "Try", "into_result"];
3719 let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
3720 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
3723 // #[allow(unreachable_code)]
3725 // allow(unreachable_code)
3727 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
3728 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
3729 let uc_nested = attr::mk_nested_word_item(uc_ident);
3730 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
3732 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
3734 let attrs = vec![attr];
3736 // Ok(val) => #[allow(unreachable_code)] val,
3738 let val_ident = self.str_to_ident("val");
3739 let val_pat = self.pat_ident(e.span, val_ident);
3740 let val_expr = P(self.expr_ident_with_attrs(
3744 ThinVec::from(attrs.clone()),
3746 let ok_pat = self.pat_ok(e.span, val_pat);
3748 self.arm(hir_vec![ok_pat], val_expr)
3751 // Err(err) => #[allow(unreachable_code)]
3752 // return Try::from_error(From::from(err)),
3754 let err_ident = self.str_to_ident("err");
3755 let err_local = self.pat_ident(e.span, err_ident);
3757 let path = &["convert", "From", "from"];
3758 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
3759 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
3761 self.expr_call(e.span, from, hir_vec![err_expr])
3764 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
3765 let thin_attrs = ThinVec::from(attrs);
3766 let catch_scope = self.catch_scopes.last().map(|x| *x);
3767 let ret_expr = if let Some(catch_node) = catch_scope {
3773 target_id: Ok(catch_node),
3775 Some(from_err_expr),
3780 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
3783 let err_pat = self.pat_err(e.span, err_local);
3784 self.arm(hir_vec![err_pat], ret_expr)
3789 hir_vec![err_arm, ok_arm],
3790 hir::MatchSource::TryDesugar,
3794 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
3797 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3804 attrs: e.attrs.clone(),
3808 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
3809 SmallVector::one(match s.node {
3810 StmtKind::Local(ref l) => Spanned {
3811 node: hir::StmtDecl(
3813 node: hir::DeclLocal(self.lower_local(l)),
3816 self.lower_node_id(s.id).node_id,
3820 StmtKind::Item(ref it) => {
3821 // Can only use the ID once.
3822 let mut id = Some(s.id);
3823 return self.lower_item_id(it)
3825 .map(|item_id| Spanned {
3826 node: hir::StmtDecl(
3828 node: hir::DeclItem(item_id),
3832 .map(|id| self.lower_node_id(id).node_id)
3833 .unwrap_or_else(|| self.next_id().node_id),
3839 StmtKind::Expr(ref e) => Spanned {
3840 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3843 StmtKind::Semi(ref e) => Spanned {
3844 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3847 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
3851 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
3853 CaptureBy::Value => hir::CaptureByValue,
3854 CaptureBy::Ref => hir::CaptureByRef,
3858 /// If an `explicit_owner` is given, this method allocates the `HirId` in
3859 /// the address space of that item instead of the item currently being
3860 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
3861 /// lower a `Visibility` value although we haven't lowered the owning
3862 /// `ImplItem` in question yet.
3863 fn lower_visibility(
3866 explicit_owner: Option<NodeId>,
3867 ) -> hir::Visibility {
3869 VisibilityKind::Public => hir::Public,
3870 VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
3871 VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
3872 path: P(self.lower_path(id, path, ParamMode::Explicit)),
3873 id: if let Some(owner) = explicit_owner {
3874 self.lower_node_id_with_owner(id, owner).node_id
3876 self.lower_node_id(id).node_id
3879 VisibilityKind::Inherited => hir::Inherited,
3883 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
3885 Defaultness::Default => hir::Defaultness::Default {
3886 has_value: has_value,
3888 Defaultness::Final => {
3890 hir::Defaultness::Final
3895 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3897 BlockCheckMode::Default => hir::DefaultBlock,
3898 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3902 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3904 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3905 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3906 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3907 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3911 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3913 CompilerGenerated => hir::CompilerGenerated,
3914 UserProvided => hir::UserProvided,
3918 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
3920 ImplPolarity::Positive => hir::ImplPolarity::Positive,
3921 ImplPolarity::Negative => hir::ImplPolarity::Negative,
3925 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3927 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3928 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3932 // Helper methods for building HIR.
3934 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
3943 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
3945 id: self.next_id().node_id,
3949 is_shorthand: false,
3953 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
3954 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
3955 P(self.expr(span, expr_break, attrs))
3962 args: hir::HirVec<hir::Expr>,
3964 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
3967 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
3968 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
3971 fn expr_ident_with_attrs(
3976 attrs: ThinVec<Attribute>,
3978 let expr_path = hir::ExprPath(hir::QPath::Resolved(
3982 def: Def::Local(binding),
3983 segments: hir_vec![hir::PathSegment::from_name(id)],
3987 self.expr(span, expr_path, attrs)
3990 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
3991 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
3997 components: &[&str],
3998 attrs: ThinVec<Attribute>,
4000 let path = self.std_path(span, components, true);
4003 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4012 arms: hir::HirVec<hir::Arm>,
4013 source: hir::MatchSource,
4015 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4018 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4019 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4022 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4023 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4026 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4027 let LoweredNodeId { node_id, hir_id } = self.next_id();
4040 ex: Option<P<hir::Expr>>,
4042 source: hir::LocalSource,
4044 let LoweredNodeId { node_id, hir_id } = self.next_id();
4046 let local = P(hir::Local {
4053 attrs: ThinVec::new(),
4056 let decl = respan(sp, hir::DeclLocal(local));
4057 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4066 ) -> (hir::Stmt, NodeId) {
4067 let pat = if mutbl {
4068 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4070 self.pat_ident(sp, ident)
4072 let pat_id = pat.id;
4074 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4079 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4080 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4086 stmts: hir::HirVec<hir::Stmt>,
4087 expr: Option<P<hir::Expr>>,
4089 let LoweredNodeId { node_id, hir_id } = self.next_id();
4096 rules: hir::DefaultBlock,
4098 targeted_by_break: false,
4103 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4104 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4107 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4108 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4111 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4112 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4115 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4116 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4122 components: &[&str],
4123 subpats: hir::HirVec<P<hir::Pat>>,
4125 let path = self.std_path(span, components, true);
4126 let qpath = hir::QPath::Resolved(None, P(path));
4127 let pt = if subpats.is_empty() {
4128 hir::PatKind::Path(qpath)
4130 hir::PatKind::TupleStruct(qpath, subpats, None)
4135 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4136 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4139 fn pat_ident_binding_mode(
4143 bm: hir::BindingAnnotation,
4145 let LoweredNodeId { node_id, hir_id } = self.next_id();
4150 node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4155 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4156 self.pat(span, hir::PatKind::Wild)
4159 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4160 let LoweredNodeId { node_id, hir_id } = self.next_id();
4169 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4170 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4171 /// The path is also resolved according to `is_value`.
4172 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
4174 .resolve_str_path(span, self.crate_root, components, is_value)
4177 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4179 let node = match qpath {
4180 hir::QPath::Resolved(None, path) => {
4181 // Turn trait object paths into `TyTraitObject` instead.
4182 if let Def::Trait(_) = path.def {
4183 let principal = hir::PolyTraitRef {
4184 bound_generic_params: hir::HirVec::new(),
4185 trait_ref: hir::TraitRef {
4186 path: path.and_then(|path| path),
4192 // The original ID is taken by the `PolyTraitRef`,
4193 // so the `Ty` itself needs a different one.
4194 id = self.next_id();
4195 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4197 hir::TyPath(hir::QPath::Resolved(None, path))
4200 _ => hir::TyPath(qpath),
4210 /// Invoked to create the lifetime argument for a type `&T`
4211 /// with no explicit lifetime.
4212 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4213 match self.anonymous_lifetime_mode {
4214 // Intercept when we are in an impl header and introduce an in-band lifetime.
4215 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4217 AnonymousLifetimeMode::CreateParameter => {
4218 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4220 id: self.next_id().node_id,
4226 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4230 /// Invoked to create the lifetime argument(s) for a path like
4231 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4232 /// sorts of cases are deprecated. This may therefore report a warning or an
4233 /// error, depending on the mode.
4234 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4235 match self.anonymous_lifetime_mode {
4236 // NB. We intentionally ignore the create-parameter mode here
4237 // and instead "pass through" to resolve-lifetimes, which will then
4238 // report an error. This is because we don't want to support
4239 // impl elision for deprecated forms like
4241 // impl Foo for std::cell::Ref<u32> // note lack of '_
4242 AnonymousLifetimeMode::CreateParameter => {}
4244 // This is the normal case.
4245 AnonymousLifetimeMode::PassThrough => {}
4249 .map(|_| self.new_implicit_lifetime(span))
4253 /// Invoked to create the lifetime argument(s) for an elided trait object
4254 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4255 /// when the bound is written, even if it is written with `'_` like in
4256 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4257 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4258 match self.anonymous_lifetime_mode {
4259 // NB. We intentionally ignore the create-parameter mode here.
4260 // and instead "pass through" to resolve-lifetimes, which will apply
4261 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4262 // do not act like other elided lifetimes. In other words, given this:
4264 // impl Foo for Box<dyn Debug>
4266 // we do not introduce a fresh `'_` to serve as the bound, but instead
4267 // ultimately translate to the equivalent of:
4269 // impl Foo for Box<dyn Debug + 'static>
4271 // `resolve_lifetime` has the code to make that happen.
4272 AnonymousLifetimeMode::CreateParameter => {}
4274 // This is the normal case.
4275 AnonymousLifetimeMode::PassThrough => {}
4278 self.new_implicit_lifetime(span)
4281 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4283 id: self.next_id().node_id,
4285 name: hir::LifetimeName::Implicit,
4289 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4290 self.sess.buffer_lint_with_diagnostic(
4291 builtin::BARE_TRAIT_OBJECTS,
4294 "trait objects without an explicit `dyn` are deprecated",
4295 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4299 fn wrap_in_try_constructor(
4301 method: &'static str,
4303 unstable_span: Span,
4305 let path = &["ops", "Try", method];
4306 let from_err = P(self.expr_std_path(unstable_span, path,
4308 P(self.expr_call(e.span, from_err, hir_vec![e]))
4312 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4313 // Sorting by span ensures that we get things in order within a
4314 // file, and also puts the files in a sensible order.
4315 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4316 body_ids.sort_by_key(|b| bodies[b].value.span);