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_path_param(&mut self,
1042 p: &AngleBracketedParam,
1043 itctx: ImplTraitContext)
1046 AngleBracketedParam::Lifetime(lt) => {
1047 PathParam::Lifetime(self.lower_lifetime(<))
1049 AngleBracketedParam::Type(ty) => {
1050 PathParam::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_path_parameters(&mut self, span: Span, parameters: &'v hir::PathParameters) {
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_path_parameters(self, span, parameters);
1331 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1333 hir::intravisit::walk_path_parameters(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 parameters, infer_types) = if let Some(ref parameters) = segment.parameters {
1688 let msg = "parenthesized parameters may only be used with a trait";
1689 match **path_params {
1690 PathParameters::AngleBracketed(ref data) => {
1691 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1693 PathParameters::Parenthesized(ref data) => match parenthesized_generic_args {
1694 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1695 ParenthesizedGenericArgs::Warn => {
1696 self.sess.buffer_lint(
1697 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1702 (hir::PathParameters::none(), true)
1704 ParenthesizedGenericArgs::Err => {
1705 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1706 .span_label(data.span, "only traits may use parentheses")
1708 (hir::PathParameters::none(), true)
1713 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1716 if !parameters.parenthesized && parameters.lifetimes.is_empty() {
1717 path_params.parameters = (0..expected_lifetimes).map(|_| {
1718 PathParam::Lifetime(self.elided_lifetime(path_span))
1719 }).chain(path_params.parameters.into_iter()).collect();
1722 hir::PathSegment::new(
1723 self.lower_ident(segment.ident),
1729 fn lower_angle_bracketed_parameter_data(
1731 data: &AngleBracketedParameterData,
1732 param_mode: ParamMode,
1733 itctx: ImplTraitContext,
1734 ) -> (hir::PathParameters, bool) {
1735 let &AngleBracketedParameterData { ref parameters, ref bindings, .. } = data;
1736 (hir::PathParameters {
1737 parameters: parameters.iter().map(|p| self.lower_path_param(p, itctx)).collect(),
1738 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1739 parenthesized: false,
1741 types.is_empty() && param_mode == ParamMode::Optional)
1744 fn lower_parenthesized_parameter_data(
1746 data: &ParenthesizedParameterData,
1747 ) -> (hir::PathParameters, bool) {
1748 // Switch to `PassThrough` mode for anonymous lifetimes: this
1749 // means that we permit things like `&Ref<T>`, where `Ref` has
1750 // a hidden lifetime parameter. This is needed for backwards
1751 // compatibility, even in contexts like an impl header where
1752 // we generally don't permit such things (see #51008).
1753 self.with_anonymous_lifetime_mode(
1754 AnonymousLifetimeMode::PassThrough,
1756 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1757 let &ParenthesizedParameterData {
1764 .map(|ty| this.lower_ty(ty, DISALLOWED))
1766 let mk_tup = |this: &mut Self, tys, span| {
1767 let LoweredNodeId { node_id, hir_id } = this.next_id();
1769 node: hir::TyTup(tys),
1777 hir::PathParameters {
1778 parameters: hir_vec![PathParam::Type(mk_tup(this, inputs, span))],
1781 id: this.next_id().node_id,
1782 name: Symbol::intern(FN_OUTPUT_NAME),
1785 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1786 .unwrap_or_else(|| mk_tup(this, hir::HirVec::new(), span)),
1787 span: output.as_ref().map_or(span, |ty| ty.span),
1790 parenthesized: true,
1798 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1799 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1805 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1806 pat: self.lower_pat(&l.pat),
1807 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1809 attrs: l.attrs.clone(),
1810 source: hir::LocalSource::Normal,
1814 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1816 Mutability::Mutable => hir::MutMutable,
1817 Mutability::Immutable => hir::MutImmutable,
1821 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1822 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1826 pat: self.lower_pat(&arg.pat),
1830 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1833 .map(|arg| match arg.pat.node {
1834 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1835 _ => respan(arg.pat.span, keywords::Invalid.name()),
1843 fn_def_id: Option<DefId>,
1844 impl_trait_return_allow: bool,
1845 ) -> P<hir::FnDecl> {
1846 // NOTE: The two last parameters here have to do with impl Trait. If fn_def_id is Some,
1847 // then impl Trait arguments are lowered into generic parameters on the given
1848 // fn_def_id, otherwise impl Trait is disallowed. (for now)
1850 // Furthermore, if impl_trait_return_allow is true, then impl Trait may be used in
1851 // return positions as well. This guards against trait declarations and their impls
1852 // where impl Trait is disallowed. (again for now)
1857 if let Some(def_id) = fn_def_id {
1858 self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1860 self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1864 output: match decl.output {
1865 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1866 Some(def_id) if impl_trait_return_allow => {
1867 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1869 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1871 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1873 variadic: decl.variadic,
1874 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1875 TyKind::ImplicitSelf => true,
1876 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1882 fn lower_ty_param_bound(
1885 itctx: ImplTraitContext,
1886 ) -> hir::TyParamBound {
1888 TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound(
1889 self.lower_poly_trait_ref(ty, itctx),
1890 self.lower_trait_bound_modifier(modifier),
1892 RegionTyParamBound(ref lifetime) => {
1893 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
1901 add_bounds: &[TyParamBound],
1902 itctx: ImplTraitContext,
1904 let mut name = self.lower_ident(tp.ident);
1906 // Don't expose `Self` (recovered "keyword used as ident" parse error).
1907 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1908 // Instead, use gensym("Self") to create a distinct name that looks the same.
1909 if name == keywords::SelfType.name() {
1910 name = Symbol::gensym("Self");
1913 let mut bounds = self.lower_bounds(&tp.bounds, itctx);
1914 if !add_bounds.is_empty() {
1917 .chain(self.lower_bounds(add_bounds, itctx).into_iter())
1922 id: self.lower_node_id(tp.id).node_id,
1927 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
1928 span: tp.ident.span,
1929 pure_wrt_drop: attr::contains_name(&tp.attrs, "may_dangle"),
1932 .filter(|attr| attr.check_name("rustc_synthetic"))
1933 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
1935 attrs: self.lower_attrs(&tp.attrs),
1939 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1940 let span = l.ident.span;
1941 match self.lower_ident(l.ident) {
1942 x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
1943 x if x == "'_" => match self.anonymous_lifetime_mode {
1944 AnonymousLifetimeMode::CreateParameter => {
1945 let fresh_name = self.collect_fresh_in_band_lifetime(span);
1946 self.new_named_lifetime(l.id, span, fresh_name)
1949 AnonymousLifetimeMode::PassThrough => {
1950 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1954 self.maybe_collect_in_band_lifetime(span, name);
1955 self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name))
1960 fn new_named_lifetime(
1964 name: hir::LifetimeName,
1965 ) -> hir::Lifetime {
1967 id: self.lower_node_id(id).node_id,
1973 fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef {
1974 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1975 self.is_collecting_in_band_lifetimes = false;
1977 let def = hir::LifetimeDef {
1978 lifetime: self.lower_lifetime(&l.lifetime),
1979 bounds: l.bounds.iter().map(|l| self.lower_lifetime(l)).collect(),
1980 pure_wrt_drop: attr::contains_name(&l.attrs, "may_dangle"),
1984 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1989 fn lower_generic_params(
1991 params: &Vec<GenericParam>,
1992 add_bounds: &NodeMap<Vec<TyParamBound>>,
1993 itctx: ImplTraitContext,
1994 ) -> hir::HirVec<hir::GenericParam> {
1997 .map(|param| match *param {
1998 GenericParam::Lifetime(ref lifetime_def) => {
1999 hir::GenericParam::Lifetime(self.lower_lifetime_def(lifetime_def))
2001 GenericParam::Type(ref ty_param) => hir::GenericParam::Type(self.lower_ty_param(
2003 add_bounds.get(&ty_param.id).map_or(&[][..], |x| &x),
2010 fn lower_generics(&mut self, g: &Generics, itctx: ImplTraitContext) -> hir::Generics {
2011 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2012 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2013 // paths where report_error is called are also the only paths that advance to after
2014 // the match statement, so the error reporting could probably just be moved there.
2015 let mut add_bounds = NodeMap();
2016 for pred in &g.where_clause.predicates {
2017 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2018 'next_bound: for bound in &bound_pred.bounds {
2019 if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
2020 let report_error = |this: &mut Self| {
2021 this.diagnostic().span_err(
2022 bound_pred.bounded_ty.span,
2023 "`?Trait` bounds are only permitted at the \
2024 point where a type parameter is declared",
2027 // Check if the where clause type is a plain type parameter.
2028 match bound_pred.bounded_ty.node {
2029 TyKind::Path(None, ref path)
2030 if path.segments.len() == 1
2031 && bound_pred.bound_generic_params.is_empty() =>
2033 if let Some(Def::TyParam(def_id)) = self.resolver
2034 .get_resolution(bound_pred.bounded_ty.id)
2035 .map(|d| d.base_def())
2037 if let Some(node_id) =
2038 self.resolver.definitions().as_local_node_id(def_id)
2040 for param in &g.params {
2041 if let GenericParam::Type(ref ty_param) = *param {
2042 if node_id == ty_param.id {
2045 .or_insert(Vec::new())
2046 .push(bound.clone());
2047 continue 'next_bound;
2055 _ => report_error(self),
2063 params: self.lower_generic_params(&g.params, &add_bounds, itctx),
2064 where_clause: self.lower_where_clause(&g.where_clause),
2069 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2071 id: self.lower_node_id(wc.id).node_id,
2072 predicates: wc.predicates
2074 .map(|predicate| self.lower_where_predicate(predicate))
2079 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2081 WherePredicate::BoundPredicate(WhereBoundPredicate {
2082 ref bound_generic_params,
2087 self.with_in_scope_lifetime_defs(
2088 bound_generic_params.iter().filter_map(|p| match p {
2089 GenericParam::Lifetime(ld) => Some(ld),
2093 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2094 bound_generic_params: this.lower_generic_params(
2095 bound_generic_params,
2097 ImplTraitContext::Disallowed,
2099 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2102 .filter_map(|bound| match *bound {
2103 // Ignore `?Trait` bounds.
2104 // Tthey were copied into type parameters already.
2105 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
2106 _ => Some(this.lower_ty_param_bound(
2108 ImplTraitContext::Disallowed,
2117 WherePredicate::RegionPredicate(WhereRegionPredicate {
2121 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2123 lifetime: self.lower_lifetime(lifetime),
2126 .map(|bound| self.lower_lifetime(bound))
2129 WherePredicate::EqPredicate(WhereEqPredicate {
2134 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2135 id: self.lower_node_id(id).node_id,
2136 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2137 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2143 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2145 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2149 .map(|f| self.lower_struct_field(f))
2151 self.lower_node_id(id).node_id,
2153 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2157 .map(|f| self.lower_struct_field(f))
2159 self.lower_node_id(id).node_id,
2161 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2165 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2166 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2167 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2168 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2172 ref_id: self.lower_node_id(p.ref_id).node_id,
2176 fn lower_poly_trait_ref(
2179 itctx: ImplTraitContext,
2180 ) -> hir::PolyTraitRef {
2181 let bound_generic_params =
2182 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2183 let trait_ref = self.with_parent_impl_lifetime_defs(
2184 &bound_generic_params
2186 .filter_map(|p| match *p {
2187 hir::GenericParam::Lifetime(ref ld) => Some(ld.clone()),
2190 .collect::<Vec<_>>(),
2191 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2195 bound_generic_params,
2201 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2204 id: self.lower_node_id(f.id).node_id,
2205 ident: match f.ident {
2206 Some(ident) => ident,
2207 // FIXME(jseyfried) positional field hygiene
2208 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2210 vis: self.lower_visibility(&f.vis, None),
2211 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2212 attrs: self.lower_attrs(&f.attrs),
2216 fn lower_field(&mut self, f: &Field) -> hir::Field {
2218 id: self.next_id().node_id,
2220 expr: P(self.lower_expr(&f.expr)),
2222 is_shorthand: f.is_shorthand,
2226 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2228 ty: self.lower_ty(&mt.ty, itctx),
2229 mutbl: self.lower_mutability(mt.mutbl),
2235 bounds: &[TyParamBound],
2236 itctx: ImplTraitContext,
2237 ) -> hir::TyParamBounds {
2240 .map(|bound| self.lower_ty_param_bound(bound, itctx))
2244 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2245 let mut expr = None;
2247 let mut stmts = vec![];
2249 for (index, stmt) in b.stmts.iter().enumerate() {
2250 if index == b.stmts.len() - 1 {
2251 if let StmtKind::Expr(ref e) = stmt.node {
2252 expr = Some(P(self.lower_expr(e)));
2254 stmts.extend(self.lower_stmt(stmt));
2257 stmts.extend(self.lower_stmt(stmt));
2261 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2266 stmts: stmts.into(),
2268 rules: self.lower_block_check_mode(&b.rules),
2271 recovered: b.recovered,
2279 attrs: &hir::HirVec<Attribute>,
2280 vis: &mut hir::Visibility,
2284 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2285 ItemKind::Use(ref use_tree) => {
2286 // Start with an empty prefix
2289 span: use_tree.span,
2292 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2294 ItemKind::Static(ref t, m, ref e) => {
2295 let value = self.lower_body(None, |this| this.lower_expr(e));
2297 self.lower_ty(t, ImplTraitContext::Disallowed),
2298 self.lower_mutability(m),
2302 ItemKind::Const(ref t, ref e) => {
2303 let value = self.lower_body(None, |this| this.lower_expr(e));
2304 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2306 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
2307 let fn_def_id = self.resolver.definitions().local_def_id(id);
2308 self.with_new_scopes(|this| {
2309 let body_id = this.lower_body(Some(decl), |this| {
2310 let body = this.lower_block(body, false);
2311 this.expr_block(body, ThinVec::new())
2313 let (generics, fn_decl) = this.add_in_band_defs(
2316 AnonymousLifetimeMode::PassThrough,
2317 |this| this.lower_fn_decl(decl, Some(fn_def_id), true),
2322 this.lower_unsafety(unsafety),
2323 this.lower_constness(constness),
2330 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2331 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2332 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2333 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2334 self.lower_ty(t, ImplTraitContext::Disallowed),
2335 self.lower_generics(generics, ImplTraitContext::Disallowed),
2337 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2339 variants: enum_definition
2342 .map(|x| self.lower_variant(x))
2345 self.lower_generics(generics, ImplTraitContext::Disallowed),
2347 ItemKind::Struct(ref struct_def, ref generics) => {
2348 let struct_def = self.lower_variant_data(struct_def);
2351 self.lower_generics(generics, ImplTraitContext::Disallowed),
2354 ItemKind::Union(ref vdata, ref generics) => {
2355 let vdata = self.lower_variant_data(vdata);
2358 self.lower_generics(generics, ImplTraitContext::Disallowed),
2370 let def_id = self.resolver.definitions().local_def_id(id);
2372 // Lower the "impl header" first. This ordering is important
2373 // for in-band lifetimes! Consider `'a` here:
2375 // impl Foo<'a> for u32 {
2376 // fn method(&'a self) { .. }
2379 // Because we start by lowering the `Foo<'a> for u32`
2380 // part, we will add `'a` to the list of generics on
2381 // the impl. When we then encounter it later in the
2382 // method, it will not be considered an in-band
2383 // lifetime to be added, but rather a reference to a
2385 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2388 AnonymousLifetimeMode::CreateParameter,
2390 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2391 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2394 if let Some(ref trait_ref) = trait_ref {
2395 if let Def::Trait(def_id) = trait_ref.path.def {
2396 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2400 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2402 (trait_ref, lowered_ty)
2406 let new_impl_items = self.with_in_scope_lifetime_defs(
2407 ast_generics.params.iter().filter_map(|p| match p {
2408 GenericParam::Lifetime(ld) => Some(ld),
2414 .map(|item| this.lower_impl_item_ref(item))
2420 self.lower_unsafety(unsafety),
2421 self.lower_impl_polarity(polarity),
2422 self.lower_defaultness(defaultness, true /* [1] */),
2429 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2430 let bounds = self.lower_bounds(bounds, ImplTraitContext::Disallowed);
2433 .map(|item| self.lower_trait_item_ref(item))
2436 self.lower_is_auto(is_auto),
2437 self.lower_unsafety(unsafety),
2438 self.lower_generics(generics, ImplTraitContext::Disallowed),
2443 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2444 self.lower_generics(generics, ImplTraitContext::Disallowed),
2445 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2447 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2450 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2451 // not cause an assertion failure inside the `lower_defaultness` function
2459 vis: &mut hir::Visibility,
2461 attrs: &hir::HirVec<Attribute>,
2463 let path = &tree.prefix;
2466 UseTreeKind::Simple(rename, id1, id2) => {
2467 *name = tree.ident().name;
2469 // First apply the prefix to the path
2470 let mut path = Path {
2474 .chain(path.segments.iter())
2480 // Correctly resolve `self` imports
2481 if path.segments.len() > 1
2482 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2484 let _ = path.segments.pop();
2485 if rename.is_none() {
2486 *name = path.segments.last().unwrap().ident.name;
2490 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2491 let mut defs = self.expect_full_def_from_use(id);
2492 // we want to return *something* from this function, so hang onto the first item
2494 let mut ret_def = defs.next().unwrap_or(Def::Err);
2496 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2497 let vis = vis.clone();
2498 let name = name.clone();
2499 let span = path.span;
2500 self.resolver.definitions().create_def_with_parent(
2504 DefIndexAddressSpace::High,
2507 self.allocate_hir_id_counter(new_node_id, &path);
2509 self.with_hir_id_owner(new_node_id, |this| {
2510 let new_id = this.lower_node_id(new_node_id);
2511 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2512 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2513 let vis = match vis {
2514 hir::Visibility::Public => hir::Visibility::Public,
2515 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2516 hir::Visibility::Inherited => hir::Visibility::Inherited,
2517 hir::Visibility::Restricted { ref path, id: _ } => {
2518 hir::Visibility::Restricted {
2520 // We are allocating a new NodeId here
2521 id: this.next_id().node_id,
2530 hir_id: new_id.hir_id,
2532 attrs: attrs.clone(),
2541 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2542 hir::ItemUse(path, hir::UseKind::Single)
2544 UseTreeKind::Glob => {
2545 let path = P(self.lower_path(
2551 .chain(path.segments.iter())
2556 ParamMode::Explicit,
2558 hir::ItemUse(path, hir::UseKind::Glob)
2560 UseTreeKind::Nested(ref trees) => {
2565 .chain(path.segments.iter())
2568 span: prefix.span.to(path.span),
2571 // Add all the nested PathListItems in the HIR
2572 for &(ref use_tree, id) in trees {
2573 self.allocate_hir_id_counter(id, &use_tree);
2577 } = self.lower_node_id(id);
2579 let mut vis = vis.clone();
2580 let mut name = name.clone();
2582 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2584 self.with_hir_id_owner(new_id, |this| {
2585 let vis = match vis {
2586 hir::Visibility::Public => hir::Visibility::Public,
2587 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2588 hir::Visibility::Inherited => hir::Visibility::Inherited,
2589 hir::Visibility::Restricted { ref path, id: _ } => {
2590 hir::Visibility::Restricted {
2592 // We are allocating a new NodeId here
2593 id: this.next_id().node_id,
2604 attrs: attrs.clone(),
2607 span: use_tree.span,
2613 // Privatize the degenerate import base, used only to check
2614 // the stability of `use a::{};`, to avoid it showing up as
2615 // a re-export by accident when `pub`, e.g. in documentation.
2616 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2617 *vis = hir::Inherited;
2618 hir::ItemUse(path, hir::UseKind::ListStem)
2623 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2624 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2625 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2627 let (generics, node) = match i.node {
2628 TraitItemKind::Const(ref ty, ref default) => (
2629 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2630 hir::TraitItemKind::Const(
2631 self.lower_ty(ty, ImplTraitContext::Disallowed),
2634 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2637 TraitItemKind::Method(ref sig, None) => {
2638 let names = self.lower_fn_args_to_names(&sig.decl);
2639 self.add_in_band_defs(
2642 AnonymousLifetimeMode::PassThrough,
2644 hir::TraitItemKind::Method(
2645 this.lower_method_sig(sig, trait_item_def_id, false),
2646 hir::TraitMethod::Required(names),
2651 TraitItemKind::Method(ref sig, Some(ref body)) => {
2652 let body_id = self.lower_body(Some(&sig.decl), |this| {
2653 let body = this.lower_block(body, false);
2654 this.expr_block(body, ThinVec::new())
2657 self.add_in_band_defs(
2660 AnonymousLifetimeMode::PassThrough,
2662 hir::TraitItemKind::Method(
2663 this.lower_method_sig(sig, trait_item_def_id, false),
2664 hir::TraitMethod::Provided(body_id),
2669 TraitItemKind::Type(ref bounds, ref default) => (
2670 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2671 hir::TraitItemKind::Type(
2672 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2675 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2678 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2684 name: self.lower_ident(i.ident),
2685 attrs: self.lower_attrs(&i.attrs),
2692 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2693 let (kind, has_default) = match i.node {
2694 TraitItemKind::Const(_, ref default) => {
2695 (hir::AssociatedItemKind::Const, default.is_some())
2697 TraitItemKind::Type(_, ref default) => {
2698 (hir::AssociatedItemKind::Type, default.is_some())
2700 TraitItemKind::Method(ref sig, ref default) => (
2701 hir::AssociatedItemKind::Method {
2702 has_self: sig.decl.has_self(),
2706 TraitItemKind::Macro(..) => unimplemented!(),
2709 id: hir::TraitItemId { node_id: i.id },
2710 name: self.lower_ident(i.ident),
2712 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2717 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2718 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2719 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2721 let (generics, node) = match i.node {
2722 ImplItemKind::Const(ref ty, ref expr) => {
2723 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
2725 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2726 hir::ImplItemKind::Const(
2727 self.lower_ty(ty, ImplTraitContext::Disallowed),
2732 ImplItemKind::Method(ref sig, ref body) => {
2733 let body_id = self.lower_body(Some(&sig.decl), |this| {
2734 let body = this.lower_block(body, false);
2735 this.expr_block(body, ThinVec::new())
2737 let impl_trait_return_allow = !self.is_in_trait_impl;
2739 self.add_in_band_defs(
2742 AnonymousLifetimeMode::PassThrough,
2744 hir::ImplItemKind::Method(
2745 this.lower_method_sig(
2748 impl_trait_return_allow,
2755 ImplItemKind::Type(ref ty) => (
2756 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2757 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2759 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2765 name: self.lower_ident(i.ident),
2766 attrs: self.lower_attrs(&i.attrs),
2768 vis: self.lower_visibility(&i.vis, None),
2769 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2774 // [1] since `default impl` is not yet implemented, this is always true in impls
2777 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
2779 id: hir::ImplItemId { node_id: i.id },
2780 name: self.lower_ident(i.ident),
2782 vis: self.lower_visibility(&i.vis, Some(i.id)),
2783 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2784 kind: match i.node {
2785 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
2786 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
2787 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
2788 has_self: sig.decl.has_self(),
2790 ImplItemKind::Macro(..) => unimplemented!(),
2794 // [1] since `default impl` is not yet implemented, this is always true in impls
2797 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
2800 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
2804 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
2806 ItemKind::Use(ref use_tree) => {
2807 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
2808 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
2811 ItemKind::MacroDef(..) => return SmallVector::new(),
2814 SmallVector::one(hir::ItemId { id: i.id })
2817 fn lower_item_id_use_tree(&mut self,
2820 vec: &mut SmallVector<hir::ItemId>)
2823 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
2824 vec.push(hir::ItemId { id });
2825 self.lower_item_id_use_tree(nested, id, vec);
2827 UseTreeKind::Glob => {}
2828 UseTreeKind::Simple(_, id1, id2) => {
2829 for (_, &id) in self.expect_full_def_from_use(base_id)
2831 .zip([id1, id2].iter())
2833 vec.push(hir::ItemId { id });
2839 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
2840 let mut name = i.ident.name;
2841 let mut vis = self.lower_visibility(&i.vis, None);
2842 let attrs = self.lower_attrs(&i.attrs);
2843 if let ItemKind::MacroDef(ref def) = i.node {
2844 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
2845 let body = self.lower_token_stream(def.stream());
2846 self.exported_macros.push(hir::MacroDef {
2859 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
2861 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2874 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
2875 let node_id = self.lower_node_id(i.id).node_id;
2876 let def_id = self.resolver.definitions().local_def_id(node_id);
2880 attrs: self.lower_attrs(&i.attrs),
2881 node: match i.node {
2882 ForeignItemKind::Fn(ref fdec, ref generics) => {
2883 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
2886 AnonymousLifetimeMode::PassThrough,
2889 // Disallow impl Trait in foreign items
2890 this.lower_fn_decl(fdec, None, false),
2891 this.lower_fn_args_to_names(fdec),
2896 hir::ForeignItemFn(fn_dec, fn_args, generics)
2898 ForeignItemKind::Static(ref t, m) => {
2899 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
2901 ForeignItemKind::Ty => hir::ForeignItemType,
2902 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
2904 vis: self.lower_visibility(&i.vis, None),
2909 fn lower_method_sig(
2913 impl_trait_return_allow: bool,
2914 ) -> hir::MethodSig {
2917 unsafety: self.lower_unsafety(sig.unsafety),
2918 constness: self.lower_constness(sig.constness),
2919 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow),
2923 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
2925 IsAuto::Yes => hir::IsAuto::Yes,
2926 IsAuto::No => hir::IsAuto::No,
2930 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
2932 Unsafety::Unsafe => hir::Unsafety::Unsafe,
2933 Unsafety::Normal => hir::Unsafety::Normal,
2937 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
2939 Constness::Const => hir::Constness::Const,
2940 Constness::NotConst => hir::Constness::NotConst,
2944 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
2946 UnOp::Deref => hir::UnDeref,
2947 UnOp::Not => hir::UnNot,
2948 UnOp::Neg => hir::UnNeg,
2952 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
2954 node: match b.node {
2955 BinOpKind::Add => hir::BiAdd,
2956 BinOpKind::Sub => hir::BiSub,
2957 BinOpKind::Mul => hir::BiMul,
2958 BinOpKind::Div => hir::BiDiv,
2959 BinOpKind::Rem => hir::BiRem,
2960 BinOpKind::And => hir::BiAnd,
2961 BinOpKind::Or => hir::BiOr,
2962 BinOpKind::BitXor => hir::BiBitXor,
2963 BinOpKind::BitAnd => hir::BiBitAnd,
2964 BinOpKind::BitOr => hir::BiBitOr,
2965 BinOpKind::Shl => hir::BiShl,
2966 BinOpKind::Shr => hir::BiShr,
2967 BinOpKind::Eq => hir::BiEq,
2968 BinOpKind::Lt => hir::BiLt,
2969 BinOpKind::Le => hir::BiLe,
2970 BinOpKind::Ne => hir::BiNe,
2971 BinOpKind::Ge => hir::BiGe,
2972 BinOpKind::Gt => hir::BiGt,
2978 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2979 let node = match p.node {
2980 PatKind::Wild => hir::PatKind::Wild,
2981 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2982 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
2983 // `None` can occur in body-less function signatures
2984 def @ None | def @ Some(Def::Local(_)) => {
2985 let canonical_id = match def {
2986 Some(Def::Local(id)) => id,
2989 hir::PatKind::Binding(
2990 self.lower_binding_mode(binding_mode),
2992 respan(ident.span, ident.name),
2993 sub.as_ref().map(|x| self.lower_pat(x)),
2996 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3001 segments: hir_vec![hir::PathSegment::from_name(ident.name)],
3006 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3007 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3008 let qpath = self.lower_qpath(
3012 ParamMode::Optional,
3013 ImplTraitContext::Disallowed,
3015 hir::PatKind::TupleStruct(
3017 pats.iter().map(|x| self.lower_pat(x)).collect(),
3021 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3025 ParamMode::Optional,
3026 ImplTraitContext::Disallowed,
3028 PatKind::Struct(ref path, ref fields, etc) => {
3029 let qpath = self.lower_qpath(
3033 ParamMode::Optional,
3034 ImplTraitContext::Disallowed,
3041 node: hir::FieldPat {
3042 id: self.next_id().node_id,
3043 ident: f.node.ident,
3044 pat: self.lower_pat(&f.node.pat),
3045 is_shorthand: f.node.is_shorthand,
3049 hir::PatKind::Struct(qpath, fs, etc)
3051 PatKind::Tuple(ref elts, ddpos) => {
3052 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3054 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3055 PatKind::Ref(ref inner, mutbl) => {
3056 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3058 PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
3059 P(self.lower_expr(e1)),
3060 P(self.lower_expr(e2)),
3061 self.lower_range_end(end),
3063 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3064 before.iter().map(|x| self.lower_pat(x)).collect(),
3065 slice.as_ref().map(|x| self.lower_pat(x)),
3066 after.iter().map(|x| self.lower_pat(x)).collect(),
3068 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3069 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3072 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3081 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3083 RangeEnd::Included(_) => hir::RangeEnd::Included,
3084 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3088 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3089 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3094 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3098 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3099 let kind = match e.node {
3100 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3101 ExprKind::ObsoleteInPlace(..) => {
3102 self.sess.abort_if_errors();
3103 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3105 ExprKind::Array(ref exprs) => {
3106 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3108 ExprKind::Repeat(ref expr, ref count) => {
3109 let expr = P(self.lower_expr(expr));
3110 let count = self.lower_anon_const(count);
3111 hir::ExprRepeat(expr, count)
3113 ExprKind::Tup(ref elts) => {
3114 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3116 ExprKind::Call(ref f, ref args) => {
3117 let f = P(self.lower_expr(f));
3118 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3120 ExprKind::MethodCall(ref seg, ref args) => {
3121 let hir_seg = self.lower_path_segment(
3124 ParamMode::Optional,
3126 ParenthesizedGenericArgs::Err,
3127 ImplTraitContext::Disallowed,
3129 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3130 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3132 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3133 let binop = self.lower_binop(binop);
3134 let lhs = P(self.lower_expr(lhs));
3135 let rhs = P(self.lower_expr(rhs));
3136 hir::ExprBinary(binop, lhs, rhs)
3138 ExprKind::Unary(op, ref ohs) => {
3139 let op = self.lower_unop(op);
3140 let ohs = P(self.lower_expr(ohs));
3141 hir::ExprUnary(op, ohs)
3143 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3144 ExprKind::Cast(ref expr, ref ty) => {
3145 let expr = P(self.lower_expr(expr));
3146 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3148 ExprKind::Type(ref expr, ref ty) => {
3149 let expr = P(self.lower_expr(expr));
3150 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3152 ExprKind::AddrOf(m, ref ohs) => {
3153 let m = self.lower_mutability(m);
3154 let ohs = P(self.lower_expr(ohs));
3155 hir::ExprAddrOf(m, ohs)
3157 // More complicated than you might expect because the else branch
3158 // might be `if let`.
3159 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3160 let else_opt = else_opt.as_ref().map(|els| {
3162 ExprKind::IfLet(..) => {
3163 // wrap the if-let expr in a block
3164 let span = els.span;
3165 let els = P(self.lower_expr(els));
3166 let LoweredNodeId { node_id, hir_id } = self.next_id();
3167 let blk = P(hir::Block {
3172 rules: hir::DefaultBlock,
3174 targeted_by_break: false,
3175 recovered: blk.recovered,
3177 P(self.expr_block(blk, ThinVec::new()))
3179 _ => P(self.lower_expr(els)),
3183 let then_blk = self.lower_block(blk, false);
3184 let then_expr = self.expr_block(then_blk, ThinVec::new());
3186 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3188 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3190 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3191 this.lower_block(body, false),
3192 this.lower_label(opt_label),
3195 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3197 this.lower_block(body, false),
3198 this.lower_label(opt_label),
3199 hir::LoopSource::Loop,
3202 ExprKind::Catch(ref body) => {
3203 self.with_catch_scope(body.id, |this| {
3205 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3206 let mut block = this.lower_block(body, true).into_inner();
3207 let tail = block.expr.take().map_or_else(
3209 let LoweredNodeId { node_id, hir_id } = this.next_id();
3210 let span = this.sess.codemap().end_point(unstable_span);
3214 node: hir::ExprTup(hir_vec![]),
3215 attrs: ThinVec::new(),
3219 |x: P<hir::Expr>| x.into_inner(),
3221 block.expr = Some(this.wrap_in_try_constructor(
3222 "from_ok", tail, unstable_span));
3223 hir::ExprBlock(P(block), None)
3226 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3227 P(self.lower_expr(expr)),
3228 arms.iter().map(|x| self.lower_arm(x)).collect(),
3229 hir::MatchSource::Normal,
3231 ExprKind::Closure(capture_clause, movability, ref decl, ref body, fn_decl_span) => {
3232 self.with_new_scopes(|this| {
3233 let mut is_generator = false;
3234 let body_id = this.lower_body(Some(decl), |this| {
3235 let e = this.lower_expr(body);
3236 is_generator = this.is_generator;
3239 let generator_option = if is_generator {
3240 if !decl.inputs.is_empty() {
3245 "generators cannot have explicit arguments"
3247 this.sess.abort_if_errors();
3249 Some(match movability {
3250 Movability::Movable => hir::GeneratorMovability::Movable,
3251 Movability::Static => hir::GeneratorMovability::Static,
3254 if movability == Movability::Static {
3259 "closures cannot be static"
3265 this.lower_capture_clause(capture_clause),
3266 this.lower_fn_decl(decl, None, false),
3273 ExprKind::Block(ref blk, opt_label) => {
3274 hir::ExprBlock(self.lower_block(blk,
3275 opt_label.is_some()),
3276 self.lower_label(opt_label))
3278 ExprKind::Assign(ref el, ref er) => {
3279 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3281 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3282 self.lower_binop(op),
3283 P(self.lower_expr(el)),
3284 P(self.lower_expr(er)),
3286 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3287 ExprKind::Index(ref el, ref er) => {
3288 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3290 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3291 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3292 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3293 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3294 let id = self.next_id();
3295 let e1 = self.lower_expr(e1);
3296 let e2 = self.lower_expr(e2);
3297 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], false));
3298 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3299 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3300 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3301 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3302 hir::ExprCall(new, hir_vec![e1, e2])
3304 ExprKind::Range(ref e1, ref e2, lims) => {
3305 use syntax::ast::RangeLimits::*;
3307 let path = match (e1, e2, lims) {
3308 (&None, &None, HalfOpen) => "RangeFull",
3309 (&Some(..), &None, HalfOpen) => "RangeFrom",
3310 (&None, &Some(..), HalfOpen) => "RangeTo",
3311 (&Some(..), &Some(..), HalfOpen) => "Range",
3312 (&None, &Some(..), Closed) => "RangeToInclusive",
3313 (&Some(..), &Some(..), Closed) => unreachable!(),
3314 (_, &None, Closed) => self.diagnostic()
3315 .span_fatal(e.span, "inclusive range with no end")
3319 let fields = e1.iter()
3320 .map(|e| ("start", e))
3321 .chain(e2.iter().map(|e| ("end", e)))
3323 let expr = P(self.lower_expr(&e));
3325 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3326 let ident = Ident::new(Symbol::intern(s), unstable_span);
3327 self.field(ident, expr, unstable_span)
3329 .collect::<P<[hir::Field]>>();
3331 let is_unit = fields.is_empty();
3333 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3334 let struct_path = iter::once("ops")
3335 .chain(iter::once(path))
3336 .collect::<Vec<_>>();
3337 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
3338 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3340 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3346 hir::ExprPath(struct_path)
3348 hir::ExprStruct(struct_path, fields, None)
3350 span: unstable_span,
3351 attrs: e.attrs.clone(),
3354 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3358 ParamMode::Optional,
3359 ImplTraitContext::Disallowed,
3361 ExprKind::Break(opt_label, ref opt_expr) => {
3362 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3365 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3368 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3372 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3375 ExprKind::Continue(opt_label) => {
3376 hir::ExprAgain(if self.is_in_loop_condition && opt_label.is_none() {
3379 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3382 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3385 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3386 ExprKind::InlineAsm(ref asm) => {
3387 let hir_asm = hir::InlineAsm {
3388 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3389 outputs: asm.outputs
3391 .map(|out| hir::InlineAsmOutput {
3392 constraint: out.constraint.clone(),
3394 is_indirect: out.is_indirect,
3397 asm: asm.asm.clone(),
3398 asm_str_style: asm.asm_str_style,
3399 clobbers: asm.clobbers.clone().into(),
3400 volatile: asm.volatile,
3401 alignstack: asm.alignstack,
3402 dialect: asm.dialect,
3405 let outputs = asm.outputs
3407 .map(|out| self.lower_expr(&out.expr))
3409 let inputs = asm.inputs
3411 .map(|&(_, ref input)| self.lower_expr(input))
3413 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3415 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3420 ParamMode::Optional,
3421 ImplTraitContext::Disallowed,
3423 fields.iter().map(|x| self.lower_field(x)).collect(),
3424 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3426 ExprKind::Paren(ref ex) => {
3427 let mut ex = self.lower_expr(ex);
3428 // include parens in span, but only if it is a super-span.
3429 if e.span.contains(ex.span) {
3432 // merge attributes into the inner expression.
3433 let mut attrs = e.attrs.clone();
3434 attrs.extend::<Vec<_>>(ex.attrs.into());
3439 ExprKind::Yield(ref opt_expr) => {
3440 self.is_generator = true;
3443 .map(|x| self.lower_expr(x))
3444 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3445 hir::ExprYield(P(expr))
3448 // Desugar ExprIfLet
3449 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3450 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3453 // match <sub_expr> {
3455 // _ => [<else_opt> | ()]
3458 let mut arms = vec![];
3460 // `<pat> => <body>`
3462 let body = self.lower_block(body, false);
3463 let body_expr = P(self.expr_block(body, ThinVec::new()));
3464 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3465 arms.push(self.arm(pats, body_expr));
3468 // _ => [<else_opt>|()]
3470 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3471 let wildcard_pattern = self.pat_wild(e.span);
3472 let body = if let Some(else_expr) = wildcard_arm {
3473 P(self.lower_expr(else_expr))
3475 self.expr_tuple(e.span, hir_vec![])
3477 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3480 let contains_else_clause = else_opt.is_some();
3482 let sub_expr = P(self.lower_expr(sub_expr));
3487 hir::MatchSource::IfLetDesugar {
3488 contains_else_clause,
3493 // Desugar ExprWhileLet
3494 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3495 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3498 // [opt_ident]: loop {
3499 // match <sub_expr> {
3505 // Note that the block AND the condition are evaluated in the loop scope.
3506 // This is done to allow `break` from inside the condition of the loop.
3507 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3509 this.lower_block(body, false),
3510 this.expr_break(e.span, ThinVec::new()),
3511 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3515 // `<pat> => <body>`
3517 let body_expr = P(self.expr_block(body, ThinVec::new()));
3518 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3519 self.arm(pats, body_expr)
3524 let pat_under = self.pat_wild(e.span);
3525 self.arm(hir_vec![pat_under], break_expr)
3528 // `match <sub_expr> { ... }`
3529 let arms = hir_vec![pat_arm, break_arm];
3530 let match_expr = self.expr(
3532 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3536 // `[opt_ident]: loop { ... }`
3537 let loop_block = P(self.block_expr(P(match_expr)));
3538 let loop_expr = hir::ExprLoop(
3540 self.lower_label(opt_label),
3541 hir::LoopSource::WhileLet,
3543 // add attributes to the outer returned expr node
3547 // Desugar ExprForLoop
3548 // From: `[opt_ident]: for <pat> in <head> <body>`
3549 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3553 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3555 // [opt_ident]: loop {
3557 // match ::std::iter::Iterator::next(&mut iter) {
3558 // ::std::option::Option::Some(val) => __next = val,
3559 // ::std::option::Option::None => break
3561 // let <pat> = __next;
3562 // StmtExpr(<body>);
3570 let head = self.lower_expr(head);
3571 let head_sp = head.span;
3573 let iter = self.str_to_ident("iter");
3575 let next_ident = self.str_to_ident("__next");
3576 let next_pat = self.pat_ident_binding_mode(
3579 hir::BindingAnnotation::Mutable,
3582 // `::std::option::Option::Some(val) => next = val`
3584 let val_ident = self.str_to_ident("val");
3585 let val_pat = self.pat_ident(pat.span, val_ident);
3586 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3587 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3588 let assign = P(self.expr(
3590 hir::ExprAssign(next_expr, val_expr),
3593 let some_pat = self.pat_some(pat.span, val_pat);
3594 self.arm(hir_vec![some_pat], assign)
3597 // `::std::option::Option::None => break`
3600 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3601 let pat = self.pat_none(e.span);
3602 self.arm(hir_vec![pat], break_expr)
3607 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3609 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3611 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3612 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3613 let next_path = &["iter", "Iterator", "next"];
3614 let next_path = P(self.expr_std_path(head_sp, next_path, ThinVec::new()));
3615 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3616 let arms = hir_vec![pat_arm, break_arm];
3620 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3624 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3626 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
3630 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
3632 // `let <pat> = __next`
3633 let pat = self.lower_pat(pat);
3634 let pat_let = self.stmt_let_pat(
3638 hir::LocalSource::ForLoopDesugar,
3641 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
3642 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3643 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
3645 let loop_block = P(self.block_all(
3647 hir_vec![next_let, match_stmt, pat_let, body_stmt],
3651 // `[opt_ident]: loop { ... }`
3652 let loop_expr = hir::ExprLoop(
3654 self.lower_label(opt_label),
3655 hir::LoopSource::ForLoop,
3657 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3658 let loop_expr = P(hir::Expr {
3663 attrs: ThinVec::new(),
3666 // `mut iter => { ... }`
3667 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
3669 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
3670 let into_iter_expr = {
3671 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
3672 let into_iter = P(self.expr_std_path(head_sp, into_iter_path, ThinVec::new()));
3673 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
3676 let match_expr = P(self.expr_match(
3680 hir::MatchSource::ForLoopDesugar,
3683 // `{ let _result = ...; _result }`
3684 // underscore prevents an unused_variables lint if the head diverges
3685 let result_ident = self.str_to_ident("_result");
3686 let (let_stmt, let_stmt_binding) =
3687 self.stmt_let(e.span, false, result_ident, match_expr);
3689 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
3690 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
3691 // add the attributes to the outer returned expr node
3692 return self.expr_block(block, e.attrs.clone());
3695 // Desugar ExprKind::Try
3697 ExprKind::Try(ref sub_expr) => {
3700 // match Try::into_result(<expr>) {
3701 // Ok(val) => #[allow(unreachable_code)] val,
3702 // Err(err) => #[allow(unreachable_code)]
3703 // // If there is an enclosing `catch {...}`
3704 // break 'catch_target Try::from_error(From::from(err)),
3706 // return Try::from_error(From::from(err)),
3710 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
3712 // Try::into_result(<expr>)
3715 let sub_expr = self.lower_expr(sub_expr);
3717 let path = &["ops", "Try", "into_result"];
3718 let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
3719 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
3722 // #[allow(unreachable_code)]
3724 // allow(unreachable_code)
3726 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
3727 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
3728 let uc_nested = attr::mk_nested_word_item(uc_ident);
3729 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
3731 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
3733 let attrs = vec![attr];
3735 // Ok(val) => #[allow(unreachable_code)] val,
3737 let val_ident = self.str_to_ident("val");
3738 let val_pat = self.pat_ident(e.span, val_ident);
3739 let val_expr = P(self.expr_ident_with_attrs(
3743 ThinVec::from(attrs.clone()),
3745 let ok_pat = self.pat_ok(e.span, val_pat);
3747 self.arm(hir_vec![ok_pat], val_expr)
3750 // Err(err) => #[allow(unreachable_code)]
3751 // return Try::from_error(From::from(err)),
3753 let err_ident = self.str_to_ident("err");
3754 let err_local = self.pat_ident(e.span, err_ident);
3756 let path = &["convert", "From", "from"];
3757 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
3758 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
3760 self.expr_call(e.span, from, hir_vec![err_expr])
3763 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
3764 let thin_attrs = ThinVec::from(attrs);
3765 let catch_scope = self.catch_scopes.last().map(|x| *x);
3766 let ret_expr = if let Some(catch_node) = catch_scope {
3772 target_id: Ok(catch_node),
3774 Some(from_err_expr),
3779 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
3782 let err_pat = self.pat_err(e.span, err_local);
3783 self.arm(hir_vec![err_pat], ret_expr)
3788 hir_vec![err_arm, ok_arm],
3789 hir::MatchSource::TryDesugar,
3793 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
3796 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3803 attrs: e.attrs.clone(),
3807 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
3808 SmallVector::one(match s.node {
3809 StmtKind::Local(ref l) => Spanned {
3810 node: hir::StmtDecl(
3812 node: hir::DeclLocal(self.lower_local(l)),
3815 self.lower_node_id(s.id).node_id,
3819 StmtKind::Item(ref it) => {
3820 // Can only use the ID once.
3821 let mut id = Some(s.id);
3822 return self.lower_item_id(it)
3824 .map(|item_id| Spanned {
3825 node: hir::StmtDecl(
3827 node: hir::DeclItem(item_id),
3831 .map(|id| self.lower_node_id(id).node_id)
3832 .unwrap_or_else(|| self.next_id().node_id),
3838 StmtKind::Expr(ref e) => Spanned {
3839 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3842 StmtKind::Semi(ref e) => Spanned {
3843 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3846 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
3850 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
3852 CaptureBy::Value => hir::CaptureByValue,
3853 CaptureBy::Ref => hir::CaptureByRef,
3857 /// If an `explicit_owner` is given, this method allocates the `HirId` in
3858 /// the address space of that item instead of the item currently being
3859 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
3860 /// lower a `Visibility` value although we haven't lowered the owning
3861 /// `ImplItem` in question yet.
3862 fn lower_visibility(
3865 explicit_owner: Option<NodeId>,
3866 ) -> hir::Visibility {
3868 VisibilityKind::Public => hir::Public,
3869 VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
3870 VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
3871 path: P(self.lower_path(id, path, ParamMode::Explicit)),
3872 id: if let Some(owner) = explicit_owner {
3873 self.lower_node_id_with_owner(id, owner).node_id
3875 self.lower_node_id(id).node_id
3878 VisibilityKind::Inherited => hir::Inherited,
3882 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
3884 Defaultness::Default => hir::Defaultness::Default {
3885 has_value: has_value,
3887 Defaultness::Final => {
3889 hir::Defaultness::Final
3894 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3896 BlockCheckMode::Default => hir::DefaultBlock,
3897 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3901 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3903 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3904 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3905 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3906 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3910 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3912 CompilerGenerated => hir::CompilerGenerated,
3913 UserProvided => hir::UserProvided,
3917 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
3919 ImplPolarity::Positive => hir::ImplPolarity::Positive,
3920 ImplPolarity::Negative => hir::ImplPolarity::Negative,
3924 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3926 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3927 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3931 // Helper methods for building HIR.
3933 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
3942 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
3944 id: self.next_id().node_id,
3948 is_shorthand: false,
3952 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
3953 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
3954 P(self.expr(span, expr_break, attrs))
3961 args: hir::HirVec<hir::Expr>,
3963 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
3966 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
3967 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
3970 fn expr_ident_with_attrs(
3975 attrs: ThinVec<Attribute>,
3977 let expr_path = hir::ExprPath(hir::QPath::Resolved(
3981 def: Def::Local(binding),
3982 segments: hir_vec![hir::PathSegment::from_name(id)],
3986 self.expr(span, expr_path, attrs)
3989 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
3990 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
3996 components: &[&str],
3997 attrs: ThinVec<Attribute>,
3999 let path = self.std_path(span, components, true);
4002 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4011 arms: hir::HirVec<hir::Arm>,
4012 source: hir::MatchSource,
4014 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4017 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4018 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4021 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4022 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4025 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4026 let LoweredNodeId { node_id, hir_id } = self.next_id();
4039 ex: Option<P<hir::Expr>>,
4041 source: hir::LocalSource,
4043 let LoweredNodeId { node_id, hir_id } = self.next_id();
4045 let local = P(hir::Local {
4052 attrs: ThinVec::new(),
4055 let decl = respan(sp, hir::DeclLocal(local));
4056 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4065 ) -> (hir::Stmt, NodeId) {
4066 let pat = if mutbl {
4067 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4069 self.pat_ident(sp, ident)
4071 let pat_id = pat.id;
4073 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4078 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4079 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4085 stmts: hir::HirVec<hir::Stmt>,
4086 expr: Option<P<hir::Expr>>,
4088 let LoweredNodeId { node_id, hir_id } = self.next_id();
4095 rules: hir::DefaultBlock,
4097 targeted_by_break: false,
4102 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4103 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4106 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4107 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4110 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4111 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4114 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4115 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4121 components: &[&str],
4122 subpats: hir::HirVec<P<hir::Pat>>,
4124 let path = self.std_path(span, components, true);
4125 let qpath = hir::QPath::Resolved(None, P(path));
4126 let pt = if subpats.is_empty() {
4127 hir::PatKind::Path(qpath)
4129 hir::PatKind::TupleStruct(qpath, subpats, None)
4134 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4135 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4138 fn pat_ident_binding_mode(
4142 bm: hir::BindingAnnotation,
4144 let LoweredNodeId { node_id, hir_id } = self.next_id();
4149 node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4154 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4155 self.pat(span, hir::PatKind::Wild)
4158 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4159 let LoweredNodeId { node_id, hir_id } = self.next_id();
4168 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4169 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4170 /// The path is also resolved according to `is_value`.
4171 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
4173 .resolve_str_path(span, self.crate_root, components, is_value)
4176 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4178 let node = match qpath {
4179 hir::QPath::Resolved(None, path) => {
4180 // Turn trait object paths into `TyTraitObject` instead.
4181 if let Def::Trait(_) = path.def {
4182 let principal = hir::PolyTraitRef {
4183 bound_generic_params: hir::HirVec::new(),
4184 trait_ref: hir::TraitRef {
4185 path: path.and_then(|path| path),
4191 // The original ID is taken by the `PolyTraitRef`,
4192 // so the `Ty` itself needs a different one.
4193 id = self.next_id();
4194 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4196 hir::TyPath(hir::QPath::Resolved(None, path))
4199 _ => hir::TyPath(qpath),
4209 /// Invoked to create the lifetime argument for a type `&T`
4210 /// with no explicit lifetime.
4211 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4212 match self.anonymous_lifetime_mode {
4213 // Intercept when we are in an impl header and introduce an in-band lifetime.
4214 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4216 AnonymousLifetimeMode::CreateParameter => {
4217 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4219 id: self.next_id().node_id,
4225 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4229 /// Invoked to create the lifetime argument(s) for a path like
4230 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4231 /// sorts of cases are deprecated. This may therefore report a warning or an
4232 /// error, depending on the mode.
4233 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4234 match self.anonymous_lifetime_mode {
4235 // NB. We intentionally ignore the create-parameter mode here
4236 // and instead "pass through" to resolve-lifetimes, which will then
4237 // report an error. This is because we don't want to support
4238 // impl elision for deprecated forms like
4240 // impl Foo for std::cell::Ref<u32> // note lack of '_
4241 AnonymousLifetimeMode::CreateParameter => {}
4243 // This is the normal case.
4244 AnonymousLifetimeMode::PassThrough => {}
4248 .map(|_| self.new_implicit_lifetime(span))
4252 /// Invoked to create the lifetime argument(s) for an elided trait object
4253 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4254 /// when the bound is written, even if it is written with `'_` like in
4255 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4256 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4257 match self.anonymous_lifetime_mode {
4258 // NB. We intentionally ignore the create-parameter mode here.
4259 // and instead "pass through" to resolve-lifetimes, which will apply
4260 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4261 // do not act like other elided lifetimes. In other words, given this:
4263 // impl Foo for Box<dyn Debug>
4265 // we do not introduce a fresh `'_` to serve as the bound, but instead
4266 // ultimately translate to the equivalent of:
4268 // impl Foo for Box<dyn Debug + 'static>
4270 // `resolve_lifetime` has the code to make that happen.
4271 AnonymousLifetimeMode::CreateParameter => {}
4273 // This is the normal case.
4274 AnonymousLifetimeMode::PassThrough => {}
4277 self.new_implicit_lifetime(span)
4280 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4282 id: self.next_id().node_id,
4284 name: hir::LifetimeName::Implicit,
4288 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4289 self.sess.buffer_lint_with_diagnostic(
4290 builtin::BARE_TRAIT_OBJECTS,
4293 "trait objects without an explicit `dyn` are deprecated",
4294 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4298 fn wrap_in_try_constructor(
4300 method: &'static str,
4302 unstable_span: Span,
4304 let path = &["ops", "Try", method];
4305 let from_err = P(self.expr_std_path(unstable_span, path,
4307 P(self.expr_call(e.span, from_err, hir_vec![e]))
4311 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4312 // Sorting by span ensures that we get things in order within a
4313 // file, and also puts the files in a sensible order.
4314 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4315 body_ids.sort_by_key(|b| bodies[b].value.span);