1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Lowers the AST to the HIR.
13 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
14 //! much like a fold. Where lowering involves a bit more work things get more
15 //! interesting and there are some invariants you should know about. These mostly
16 //! concern spans and ids.
18 //! Spans are assigned to AST nodes during parsing and then are modified during
19 //! expansion to indicate the origin of a node and the process it went through
20 //! being expanded. Ids are assigned to AST nodes just before lowering.
22 //! For the simpler lowering steps, ids and spans should be preserved. Unlike
23 //! expansion we do not preserve the process of lowering in the spans, so spans
24 //! should not be modified here. When creating a new node (as opposed to
25 //! 'folding' an existing one), then you create a new id using `next_id()`.
27 //! You must ensure that ids are unique. That means that you should only use the
28 //! id from an AST node in a single HIR node (you can assume that AST node ids
29 //! are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
30 //! If you do, you must then set the new node's id to a fresh one.
32 //! Spans are used for error messages and for tools to map semantics back to
33 //! source code. It is therefore not as important with spans as ids to be strict
34 //! about use (you can't break the compiler by screwing up a span). Obviously, a
35 //! HIR node can only have a single span. But multiple nodes can have the same
36 //! span and spans don't need to be kept in order, etc. Where code is preserved
37 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
38 //! new it is probably best to give a span for the whole AST node being lowered.
39 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
40 //! get confused if the spans from leaf AST nodes occur in multiple places
41 //! in the HIR, especially for multiple identifiers.
43 use dep_graph::DepGraph;
44 use hir::{self, ParamName};
46 use hir::map::{DefKey, DefPathData, Definitions};
47 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
48 use hir::def::{Def, PathResolution, PerNS};
50 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES};
51 use middle::cstore::CrateStore;
52 use rustc_data_structures::indexed_vec::IndexVec;
54 use util::common::FN_OUTPUT_NAME;
55 use util::nodemap::{DefIdMap, NodeMap};
57 use std::collections::{BTreeMap, HashSet};
65 use syntax::ext::hygiene::{Mark, SyntaxContext};
66 use syntax::print::pprust;
68 use syntax::codemap::{self, respan, CompilerDesugaringKind, Spanned};
69 use syntax::std_inject;
70 use syntax::symbol::{keywords, Symbol};
71 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
72 use syntax::parse::token::Token;
73 use syntax::util::small_vector::SmallVector;
74 use syntax::visit::{self, Visitor};
77 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
79 pub struct LoweringContext<'a> {
80 crate_root: Option<&'static str>,
82 // Use to assign ids to hir nodes that do not directly correspond to an ast node
85 cstore: &'a CrateStore,
87 resolver: &'a mut Resolver,
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::GenericParam>,
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, ParamName)>,
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<Ident>,
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>,
170 params: Option<P<hir::GenericArgs>>,
175 #[derive(Clone, Copy, Debug)]
176 enum ImplTraitContext {
177 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
178 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
179 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
181 /// We store a DefId here so we can look up necessary information later
184 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
185 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
186 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
188 /// We store a DefId here so we can look up necessary information later
191 /// `impl Trait` is not accepted in this position.
198 dep_graph: &DepGraph,
200 resolver: &mut Resolver,
202 // We're constructing the HIR here; we don't care what we will
203 // read, since we haven't even constructed the *input* to
205 dep_graph.assert_ignored();
208 crate_root: std_inject::injected_crate_name(),
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| match param.kind {
327 ast::GenericParamKind::Lifetime { .. } => true,
331 self.lctx.type_def_lifetime_params.insert(def_id, count);
335 visit::walk_item(self, item);
338 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
339 self.lctx.allocate_hir_id_counter(item.id, item);
340 visit::walk_trait_item(self, item);
343 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
344 self.lctx.allocate_hir_id_counter(item.id, item);
345 visit::walk_impl_item(self, item);
349 struct ItemLowerer<'lcx, 'interner: 'lcx> {
350 lctx: &'lcx mut LoweringContext<'interner>,
353 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
354 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
356 F: FnOnce(&mut Self),
358 let old = self.lctx.is_in_trait_impl;
359 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
365 self.lctx.is_in_trait_impl = old;
369 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
370 fn visit_item(&mut self, item: &'lcx Item) {
371 let mut item_lowered = true;
372 self.lctx.with_hir_id_owner(item.id, |lctx| {
373 if let Some(hir_item) = lctx.lower_item(item) {
374 lctx.items.insert(item.id, hir_item);
376 item_lowered = false;
381 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
382 hir::Item_::ItemImpl(_, _, _, ref generics, ..)
383 | hir::Item_::ItemTrait(_, _, ref generics, ..) => {
384 generics.params.clone()
389 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
390 let this = &mut ItemLowerer { lctx: this };
391 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
392 this.with_trait_impl_ref(opt_trait_ref, |this| {
393 visit::walk_item(this, item)
396 visit::walk_item(this, item);
402 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
403 self.lctx.with_hir_id_owner(item.id, |lctx| {
404 let id = hir::TraitItemId { node_id: item.id };
405 let hir_item = lctx.lower_trait_item(item);
406 lctx.trait_items.insert(id, hir_item);
409 visit::walk_trait_item(self, item);
412 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
413 self.lctx.with_hir_id_owner(item.id, |lctx| {
414 let id = hir::ImplItemId { node_id: item.id };
415 let hir_item = lctx.lower_impl_item(item);
416 lctx.impl_items.insert(id, hir_item);
418 visit::walk_impl_item(self, item);
422 self.lower_node_id(CRATE_NODE_ID);
423 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
425 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
426 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
428 let module = self.lower_mod(&c.module);
429 let attrs = self.lower_attrs(&c.attrs);
430 let body_ids = body_ids(&self.bodies);
434 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
440 exported_macros: hir::HirVec::from(self.exported_macros),
442 trait_items: self.trait_items,
443 impl_items: self.impl_items,
446 trait_impls: self.trait_impls,
447 trait_auto_impl: self.trait_auto_impl,
451 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
452 if self.item_local_id_counters.insert(owner, 0).is_some() {
454 "Tried to allocate item_local_id_counter for {:?} twice",
458 // Always allocate the first HirId for the owner itself
459 self.lower_node_id_with_owner(owner, owner)
462 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
464 F: FnOnce(&mut Self) -> hir::HirId,
466 if ast_node_id == DUMMY_NODE_ID {
467 return LoweredNodeId {
468 node_id: DUMMY_NODE_ID,
469 hir_id: hir::DUMMY_HIR_ID,
473 let min_size = ast_node_id.as_usize() + 1;
475 if min_size > self.node_id_to_hir_id.len() {
476 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
479 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
481 if existing_hir_id == hir::DUMMY_HIR_ID {
482 // Generate a new HirId
483 let hir_id = alloc_hir_id(self);
484 self.node_id_to_hir_id[ast_node_id] = hir_id;
486 node_id: ast_node_id,
491 node_id: ast_node_id,
492 hir_id: existing_hir_id,
497 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
499 F: FnOnce(&mut Self) -> T,
501 let counter = self.item_local_id_counters
502 .insert(owner, HIR_ID_COUNTER_LOCKED)
503 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
504 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
505 self.current_hir_id_owner.push((def_index, counter));
507 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
509 debug_assert!(def_index == new_def_index);
510 debug_assert!(new_counter >= counter);
512 let prev = self.item_local_id_counters
513 .insert(owner, new_counter)
515 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
519 /// This method allocates a new HirId for the given NodeId and stores it in
520 /// the LoweringContext's NodeId => HirId map.
521 /// Take care not to call this method if the resulting HirId is then not
522 /// actually used in the HIR, as that would trigger an assertion in the
523 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
524 /// properly. Calling the method twice with the same NodeId is fine though.
525 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
526 self.lower_node_id_generic(ast_node_id, |this| {
527 let &mut (def_index, ref mut local_id_counter) =
528 this.current_hir_id_owner.last_mut().unwrap();
529 let local_id = *local_id_counter;
530 *local_id_counter += 1;
533 local_id: hir::ItemLocalId(local_id),
538 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
539 self.lower_node_id_generic(ast_node_id, |this| {
540 let local_id_counter = this
541 .item_local_id_counters
543 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
544 let local_id = *local_id_counter;
546 // We want to be sure not to modify the counter in the map while it
547 // is also on the stack. Otherwise we'll get lost updates when writing
548 // back from the stack to the map.
549 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
551 *local_id_counter += 1;
555 .opt_def_index(owner)
556 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
557 that do not belong to the current owner");
561 local_id: hir::ItemLocalId(local_id),
566 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
567 let body = hir::Body {
568 arguments: decl.map_or(hir_vec![], |decl| {
569 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
571 is_generator: self.is_generator,
575 self.bodies.insert(id, body);
579 fn next_id(&mut self) -> LoweredNodeId {
580 self.lower_node_id(self.sess.next_node_id())
583 fn expect_full_def(&mut self, id: NodeId) -> Def {
584 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
585 if pr.unresolved_segments() != 0 {
586 bug!("path not fully resolved: {:?}", pr);
592 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
593 self.resolver.get_import(id).present_items().map(|pr| {
594 if pr.unresolved_segments() != 0 {
595 bug!("path not fully resolved: {:?}", pr);
601 fn diagnostic(&self) -> &errors::Handler {
602 self.sess.diagnostic()
605 fn str_to_ident(&self, s: &'static str) -> Ident {
606 Ident::with_empty_ctxt(Symbol::gensym(s))
609 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
610 let mark = Mark::fresh(Mark::root());
611 mark.set_expn_info(codemap::ExpnInfo {
613 def_site: Some(span),
614 format: codemap::CompilerDesugaring(reason),
615 allow_internal_unstable: true,
616 allow_internal_unsafe: false,
617 local_inner_macros: false,
618 edition: codemap::hygiene::default_edition(),
620 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
623 fn with_anonymous_lifetime_mode<R>(
625 anonymous_lifetime_mode: AnonymousLifetimeMode,
626 op: impl FnOnce(&mut Self) -> R,
628 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
629 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
630 let result = op(self);
631 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
635 /// Creates a new hir::GenericParam for every new lifetime and
636 /// type parameter encountered while evaluating `f`. Definitions
637 /// are created with the parent provided. If no `parent_id` is
638 /// provided, no definitions will be returned.
640 /// Presuming that in-band lifetimes are enabled, then
641 /// `self.anonymous_lifetime_mode` will be updated to match the
642 /// argument while `f` is running (and restored afterwards).
643 fn collect_in_band_defs<T, F>(
646 anonymous_lifetime_mode: AnonymousLifetimeMode,
648 ) -> (Vec<hir::GenericParam>, T)
650 F: FnOnce(&mut LoweringContext) -> T,
652 assert!(!self.is_collecting_in_band_lifetimes);
653 assert!(self.lifetimes_to_define.is_empty());
654 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
656 self.is_collecting_in_band_lifetimes = self.sess.features_untracked().in_band_lifetimes;
657 if self.is_collecting_in_band_lifetimes {
658 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
661 assert!(self.in_band_ty_params.is_empty());
664 self.is_collecting_in_band_lifetimes = false;
665 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
667 let in_band_ty_params = self.in_band_ty_params.split_off(0);
668 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
670 let params = lifetimes_to_define
672 .map(|(span, hir_name)| {
673 let def_node_id = self.next_id().node_id;
675 // Get the name we'll use to make the def-path. Note
676 // that collisions are ok here and this shouldn't
677 // really show up for end-user.
678 let str_name = match hir_name {
679 ParamName::Plain(ident) => ident.as_interned_str(),
680 ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_interned_str(),
683 // Add a definition for the in-band lifetime def
684 self.resolver.definitions().create_def_with_parent(
687 DefPathData::LifetimeParam(str_name),
688 DefIndexAddressSpace::High,
699 pure_wrt_drop: false,
700 kind: hir::GenericParamKind::Lifetime { in_band: true }
703 .chain(in_band_ty_params.into_iter())
709 /// When there is a reference to some lifetime `'a`, and in-band
710 /// lifetimes are enabled, then we want to push that lifetime into
711 /// the vector of names to define later. In that case, it will get
712 /// added to the appropriate generics.
713 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
714 if !self.is_collecting_in_band_lifetimes {
718 if self.in_scope_lifetimes.contains(&ident.modern()) {
722 let hir_name = ParamName::Plain(ident);
724 if self.lifetimes_to_define.iter()
725 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
729 self.lifetimes_to_define.push((ident.span, hir_name));
732 /// When we have either an elided or `'_` lifetime in an impl
733 /// header, we convert it to
734 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
735 assert!(self.is_collecting_in_band_lifetimes);
736 let index = self.lifetimes_to_define.len();
737 let hir_name = ParamName::Fresh(index);
738 self.lifetimes_to_define.push((span, hir_name));
742 // Evaluates `f` with the lifetimes in `params` in-scope.
743 // This is used to track which lifetimes have already been defined, and
744 // which are new in-band lifetimes that need to have a definition created
746 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &Vec<GenericParam>, f: F) -> T
748 F: FnOnce(&mut LoweringContext) -> T,
750 let old_len = self.in_scope_lifetimes.len();
751 let lt_def_names = params.iter().filter_map(|param| match param.kind {
752 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
755 self.in_scope_lifetimes.extend(lt_def_names);
759 self.in_scope_lifetimes.truncate(old_len);
763 // Same as the method above, but accepts `hir::GenericParam`s
764 // instead of `ast::GenericParam`s.
765 // This should only be used with generics that have already had their
766 // in-band lifetimes added. In practice, this means that this function is
767 // only used when lowering a child item of a trait or impl.
768 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
769 params: &HirVec<hir::GenericParam>,
772 F: FnOnce(&mut LoweringContext) -> T,
774 let old_len = self.in_scope_lifetimes.len();
775 let lt_def_names = params.iter().filter_map(|param| match param.kind {
776 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
779 self.in_scope_lifetimes.extend(lt_def_names);
783 self.in_scope_lifetimes.truncate(old_len);
787 /// Appends in-band lifetime defs and argument-position `impl
788 /// Trait` defs to the existing set of generics.
790 /// Presuming that in-band lifetimes are enabled, then
791 /// `self.anonymous_lifetime_mode` will be updated to match the
792 /// argument while `f` is running (and restored afterwards).
793 fn add_in_band_defs<F, T>(
797 anonymous_lifetime_mode: AnonymousLifetimeMode,
799 ) -> (hir::Generics, T)
801 F: FnOnce(&mut LoweringContext) -> T,
803 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
806 let itctx = ImplTraitContext::Universal(parent_id);
807 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
808 (this.lower_generics(generics, itctx), f(this))
813 lowered_generics.params = lowered_generics
820 (lowered_generics, res)
823 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
825 F: FnOnce(&mut LoweringContext) -> T,
827 let len = self.catch_scopes.len();
828 self.catch_scopes.push(catch_id);
830 let result = f(self);
833 self.catch_scopes.len(),
834 "catch scopes should be added and removed in stack order"
837 self.catch_scopes.pop().unwrap();
844 capture_clause: CaptureBy,
845 closure_node_id: NodeId,
847 body: impl FnOnce(&mut LoweringContext) -> hir::Expr,
849 let prev_is_generator = mem::replace(&mut self.is_generator, true);
850 let body_expr = body(self);
851 let span = body_expr.span;
852 let output = match ret_ty {
853 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
854 None => FunctionRetTy::Default(span),
861 let body_id = self.record_body(body_expr, Some(&decl));
862 self.is_generator = prev_is_generator;
864 let capture_clause = self.lower_capture_clause(capture_clause);
865 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
866 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
867 let generator = hir::Expr {
869 hir_id: closure_hir_id,
870 node: hir::ExprClosure(capture_clause, decl, body_id, span,
871 Some(hir::GeneratorMovability::Static)),
873 attrs: ThinVec::new(),
876 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
877 let gen_future = self.expr_std_path(
878 unstable_span, &["future", "from_generator"], None, ThinVec::new());
879 hir::ExprCall(P(gen_future), hir_vec![generator])
882 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
884 F: FnOnce(&mut LoweringContext) -> hir::Expr,
886 let prev = mem::replace(&mut self.is_generator, false);
887 let result = f(self);
888 let r = self.record_body(result, decl);
889 self.is_generator = prev;
893 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
895 F: FnOnce(&mut LoweringContext) -> T,
897 // We're no longer in the base loop's condition; we're in another loop.
898 let was_in_loop_condition = self.is_in_loop_condition;
899 self.is_in_loop_condition = false;
901 let len = self.loop_scopes.len();
902 self.loop_scopes.push(loop_id);
904 let result = f(self);
907 self.loop_scopes.len(),
908 "Loop scopes should be added and removed in stack order"
911 self.loop_scopes.pop().unwrap();
913 self.is_in_loop_condition = was_in_loop_condition;
918 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
920 F: FnOnce(&mut LoweringContext) -> T,
922 let was_in_loop_condition = self.is_in_loop_condition;
923 self.is_in_loop_condition = true;
925 let result = f(self);
927 self.is_in_loop_condition = was_in_loop_condition;
932 fn with_new_scopes<T, F>(&mut self, f: F) -> T
934 F: FnOnce(&mut LoweringContext) -> T,
936 let was_in_loop_condition = self.is_in_loop_condition;
937 self.is_in_loop_condition = false;
939 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
940 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
941 let result = f(self);
942 self.catch_scopes = catch_scopes;
943 self.loop_scopes = loop_scopes;
945 self.is_in_loop_condition = was_in_loop_condition;
950 fn def_key(&mut self, id: DefId) -> DefKey {
952 self.resolver.definitions().def_key(id.index)
954 self.cstore.def_key(id)
958 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
959 label.map(|label| hir::Label {
964 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
966 Some((id, label)) => {
967 let target_id = if let Def::Label(loop_id) = self.expect_full_def(id) {
968 Ok(self.lower_node_id(loop_id).node_id)
970 Err(hir::LoopIdError::UnresolvedLabel)
973 label: self.lower_label(Some(label)),
978 let target_id = self.loop_scopes
980 .map(|innermost_loop_id| *innermost_loop_id)
981 .map(|id| Ok(self.lower_node_id(id).node_id))
982 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
993 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
996 .map(|a| self.lower_attr(a))
1001 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1005 path: attr.path.clone(),
1006 tokens: self.lower_token_stream(attr.tokens.clone()),
1007 is_sugared_doc: attr.is_sugared_doc,
1012 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1015 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1019 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1021 TokenTree::Token(span, token) => self.lower_token(token, span),
1022 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1025 delim: delimited.delim,
1026 tts: self.lower_token_stream(delimited.tts.into()).into(),
1032 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1034 Token::Interpolated(_) => {}
1035 other => return TokenTree::Token(span, other).into(),
1038 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1039 self.lower_token_stream(tts)
1042 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1044 attrs: self.lower_attrs(&arm.attrs),
1045 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1046 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1047 body: P(self.lower_expr(&arm.body)),
1051 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1053 id: self.lower_node_id(b.id).node_id,
1055 ty: self.lower_ty(&b.ty, itctx),
1060 fn lower_generic_arg(&mut self,
1061 arg: &ast::GenericArg,
1062 itctx: ImplTraitContext)
1063 -> hir::GenericArg {
1065 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1066 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1070 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1071 P(self.lower_ty_direct(t, itctx))
1074 fn lower_ty_direct(&mut self, t: &Ty, itctx: ImplTraitContext) -> hir::Ty {
1075 let kind = match t.node {
1076 TyKind::Infer => hir::TyInfer,
1077 TyKind::Err => hir::TyErr,
1078 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1079 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1080 TyKind::Rptr(ref region, ref mt) => {
1081 let span = t.span.shrink_to_lo();
1082 let lifetime = match *region {
1083 Some(ref lt) => self.lower_lifetime(lt),
1084 None => self.elided_ref_lifetime(span),
1086 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1088 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1091 this.with_anonymous_lifetime_mode(
1092 AnonymousLifetimeMode::PassThrough,
1094 hir::TyBareFn(P(hir::BareFnTy {
1095 generic_params: this.lower_generic_params(
1098 ImplTraitContext::Disallowed,
1100 unsafety: this.lower_unsafety(f.unsafety),
1102 decl: this.lower_fn_decl(&f.decl, None, false, None),
1103 arg_names: this.lower_fn_args_to_names(&f.decl),
1109 TyKind::Never => hir::TyNever,
1110 TyKind::Tup(ref tys) => {
1111 hir::TyTup(tys.iter().map(|ty| self.lower_ty_direct(ty, itctx)).collect())
1113 TyKind::Paren(ref ty) => {
1114 return self.lower_ty_direct(ty, itctx);
1116 TyKind::Path(ref qself, ref path) => {
1117 let id = self.lower_node_id(t.id);
1118 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1119 let ty = self.ty_path(id, t.span, qpath);
1120 if let hir::TyTraitObject(..) = ty.node {
1121 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1125 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1128 def: self.expect_full_def(t.id),
1129 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1133 TyKind::Array(ref ty, ref length) => {
1134 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1136 TyKind::Typeof(ref expr) => {
1137 hir::TyTypeof(self.lower_anon_const(expr))
1139 TyKind::TraitObject(ref bounds, kind) => {
1140 let mut lifetime_bound = None;
1143 .filter_map(|bound| match *bound {
1144 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1145 Some(self.lower_poly_trait_ref(ty, itctx))
1147 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1148 GenericBound::Outlives(ref lifetime) => {
1149 if lifetime_bound.is_none() {
1150 lifetime_bound = Some(self.lower_lifetime(lifetime));
1156 let lifetime_bound =
1157 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1158 if kind != TraitObjectSyntax::Dyn {
1159 self.maybe_lint_bare_trait(t.span, t.id, false);
1161 hir::TyTraitObject(bounds, lifetime_bound)
1163 TyKind::ImplTrait(def_node_id, ref bounds) => {
1166 ImplTraitContext::Existential(fn_def_id) => {
1167 self.lower_existential_impl_trait(
1168 span, fn_def_id, def_node_id,
1169 |this| this.lower_param_bounds(bounds, itctx),
1172 ImplTraitContext::Universal(_def_id) => {
1173 self.lower_node_id(def_node_id);
1174 // Add a definition for the in-band TyParam
1175 let def_index = self
1178 .opt_def_index(def_node_id)
1181 let hir_bounds = self.lower_param_bounds(bounds, itctx);
1182 // Set the name to `impl Bound1 + Bound2`
1183 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1184 self.in_band_ty_params.push(hir::GenericParam {
1186 name: ParamName::Plain(ident),
1187 pure_wrt_drop: false,
1191 kind: hir::GenericParamKind::Type {
1193 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1197 hir::TyPath(hir::QPath::Resolved(
1201 def: Def::TyParam(DefId::local(def_index)),
1202 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1206 ImplTraitContext::Disallowed => {
1211 "`impl Trait` not allowed outside of function \
1212 and inherent method return types"
1218 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1221 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1230 fn lower_existential_impl_trait(
1234 exist_ty_node_id: NodeId,
1235 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1237 // Make sure we know that some funky desugaring has been going on here.
1238 // This is a first: there is code in other places like for loop
1239 // desugaring that explicitly states that we don't want to track that.
1240 // Not tracking it makes lints in rustc and clippy very fragile as
1241 // frequently opened issues show.
1242 let exist_ty_span = self.allow_internal_unstable(
1243 CompilerDesugaringKind::ExistentialReturnType,
1247 let exist_ty_def_index = self
1250 .opt_def_index(exist_ty_node_id)
1254 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1256 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1258 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1264 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1265 let exist_ty_item_kind = hir::ItemExistential(hir::ExistTy {
1266 generics: hir::Generics {
1267 params: lifetime_defs,
1268 where_clause: hir::WhereClause {
1269 id: lctx.next_id().node_id,
1270 predicates: Vec::new().into(),
1275 impl_trait_fn: Some(fn_def_id),
1277 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1278 // Generate an `existential type Foo: Trait;` declaration
1279 trace!("creating existential type with id {:#?}", exist_ty_id);
1281 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1282 let exist_ty_item = hir::Item {
1283 id: exist_ty_id.node_id,
1284 hir_id: exist_ty_id.hir_id,
1285 name: keywords::Invalid.name(),
1286 attrs: Default::default(),
1287 node: exist_ty_item_kind,
1288 vis: respan(span.shrink_to_lo(), hir::VisibilityInherited),
1289 span: exist_ty_span,
1292 // Insert the item into the global list. This usually happens
1293 // automatically for all AST items. But this existential type item
1294 // does not actually exist in the AST.
1295 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1297 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1298 hir::TyImplTraitExistential(
1300 id: exist_ty_id.node_id
1302 DefId::local(exist_ty_def_index),
1308 fn lifetimes_from_impl_trait_bounds(
1310 exist_ty_id: NodeId,
1311 parent_index: DefIndex,
1312 bounds: &hir::GenericBounds,
1313 ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1314 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1315 // appear in the bounds, excluding lifetimes that are created within the bounds.
1316 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1317 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1318 context: &'r mut LoweringContext<'a>,
1320 exist_ty_id: NodeId,
1321 collect_elided_lifetimes: bool,
1322 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1323 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1324 output_lifetimes: Vec<hir::Lifetime>,
1325 output_lifetime_params: Vec<hir::GenericParam>,
1328 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1329 fn nested_visit_map<'this>(
1331 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1332 hir::intravisit::NestedVisitorMap::None
1335 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1336 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1337 if parameters.parenthesized {
1338 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1339 self.collect_elided_lifetimes = false;
1340 hir::intravisit::walk_generic_args(self, span, parameters);
1341 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1343 hir::intravisit::walk_generic_args(self, span, parameters);
1347 fn visit_ty(&mut self, t: &'v hir::Ty) {
1348 // Don't collect elided lifetimes used inside of `fn()` syntax
1349 if let hir::Ty_::TyBareFn(_) = t.node {
1350 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1351 self.collect_elided_lifetimes = false;
1353 // Record the "stack height" of `for<'a>` lifetime bindings
1354 // to be able to later fully undo their introduction.
1355 let old_len = self.currently_bound_lifetimes.len();
1356 hir::intravisit::walk_ty(self, t);
1357 self.currently_bound_lifetimes.truncate(old_len);
1359 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1361 hir::intravisit::walk_ty(self, t)
1365 fn visit_poly_trait_ref(
1367 trait_ref: &'v hir::PolyTraitRef,
1368 modifier: hir::TraitBoundModifier,
1370 // Record the "stack height" of `for<'a>` lifetime bindings
1371 // to be able to later fully undo their introduction.
1372 let old_len = self.currently_bound_lifetimes.len();
1373 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1374 self.currently_bound_lifetimes.truncate(old_len);
1377 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1378 // Record the introduction of 'a in `for<'a> ...`
1379 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1380 // Introduce lifetimes one at a time so that we can handle
1381 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1382 let lt_name = hir::LifetimeName::Param(param.name);
1383 self.currently_bound_lifetimes.push(lt_name);
1386 hir::intravisit::walk_generic_param(self, param);
1389 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1390 let name = match lifetime.name {
1391 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1392 if self.collect_elided_lifetimes {
1393 // Use `'_` for both implicit and underscore lifetimes in
1394 // `abstract type Foo<'_>: SomeTrait<'_>;`
1395 hir::LifetimeName::Underscore
1400 hir::LifetimeName::Param(_) => lifetime.name,
1401 hir::LifetimeName::Static => return,
1404 if !self.currently_bound_lifetimes.contains(&name)
1405 && !self.already_defined_lifetimes.contains(&name) {
1406 self.already_defined_lifetimes.insert(name);
1408 self.output_lifetimes.push(hir::Lifetime {
1409 id: self.context.next_id().node_id,
1410 span: lifetime.span,
1414 // We need to manually create the ids here, because the
1415 // definitions will go into the explicit `existential type`
1416 // declaration and thus need to have their owner set to that item
1417 let def_node_id = self.context.sess.next_node_id();
1418 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1419 self.context.resolver.definitions().create_def_with_parent(
1422 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1423 DefIndexAddressSpace::High,
1428 let name = match name {
1429 hir::LifetimeName::Underscore => {
1430 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident())
1432 hir::LifetimeName::Param(param_name) => param_name,
1433 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1436 self.output_lifetime_params.push(hir::GenericParam {
1439 span: lifetime.span,
1440 pure_wrt_drop: false,
1443 kind: hir::GenericParamKind::Lifetime {
1451 let mut lifetime_collector = ImplTraitLifetimeCollector {
1453 parent: parent_index,
1455 collect_elided_lifetimes: true,
1456 currently_bound_lifetimes: Vec::new(),
1457 already_defined_lifetimes: HashSet::new(),
1458 output_lifetimes: Vec::new(),
1459 output_lifetime_params: Vec::new(),
1462 for bound in bounds {
1463 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1467 lifetime_collector.output_lifetimes.into(),
1468 lifetime_collector.output_lifetime_params.into(),
1472 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1477 .map(|x| self.lower_foreign_item(x))
1482 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1489 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1491 node: hir::Variant_ {
1492 name: v.node.ident.name,
1493 attrs: self.lower_attrs(&v.node.attrs),
1494 data: self.lower_variant_data(&v.node.data),
1495 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1504 qself: &Option<QSelf>,
1506 param_mode: ParamMode,
1507 itctx: ImplTraitContext,
1509 let qself_position = qself.as_ref().map(|q| q.position);
1510 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx));
1512 let resolution = self.resolver
1514 .unwrap_or(PathResolution::new(Def::Err));
1516 let proj_start = p.segments.len() - resolution.unresolved_segments();
1517 let path = P(hir::Path {
1518 def: resolution.base_def(),
1519 segments: p.segments[..proj_start]
1522 .map(|(i, segment)| {
1523 let param_mode = match (qself_position, param_mode) {
1524 (Some(j), ParamMode::Optional) if i < j => {
1525 // This segment is part of the trait path in a
1526 // qualified path - one of `a`, `b` or `Trait`
1527 // in `<X as a::b::Trait>::T::U::method`.
1533 // Figure out if this is a type/trait segment,
1534 // which may need lifetime elision performed.
1535 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1536 krate: def_id.krate,
1537 index: this.def_key(def_id).parent.expect("missing parent"),
1539 let type_def_id = match resolution.base_def() {
1540 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1541 Some(parent_def_id(self, def_id))
1543 Def::Variant(def_id) if i + 1 == proj_start => {
1544 Some(parent_def_id(self, def_id))
1547 | Def::Union(def_id)
1549 | Def::TyAlias(def_id)
1550 | Def::Trait(def_id) if i + 1 == proj_start =>
1556 let parenthesized_generic_args = match resolution.base_def() {
1557 // `a::b::Trait(Args)`
1558 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1559 // `a::b::Trait(Args)::TraitItem`
1560 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1561 if i + 2 == proj_start =>
1563 ParenthesizedGenericArgs::Ok
1565 // Avoid duplicated errors
1566 Def::Err => ParenthesizedGenericArgs::Ok,
1572 | Def::Variant(..) if i + 1 == proj_start =>
1574 ParenthesizedGenericArgs::Err
1576 // A warning for now, for compatibility reasons
1577 _ => ParenthesizedGenericArgs::Warn,
1580 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1581 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1584 assert!(!def_id.is_local());
1586 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1587 let n = item_generics.own_counts().lifetimes;
1588 self.type_def_lifetime_params.insert(def_id, n);
1591 self.lower_path_segment(
1596 parenthesized_generic_args,
1604 // Simple case, either no projections, or only fully-qualified.
1605 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1606 if resolution.unresolved_segments() == 0 {
1607 return hir::QPath::Resolved(qself, path);
1610 // Create the innermost type that we're projecting from.
1611 let mut ty = if path.segments.is_empty() {
1612 // If the base path is empty that means there exists a
1613 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1614 qself.expect("missing QSelf for <T>::...")
1616 // Otherwise, the base path is an implicit `Self` type path,
1617 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1618 // `<I as Iterator>::Item::default`.
1619 let new_id = self.next_id();
1620 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1623 // Anything after the base path are associated "extensions",
1624 // out of which all but the last one are associated types,
1625 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1626 // * base path is `std::vec::Vec<T>`
1627 // * "extensions" are `IntoIter`, `Item` and `clone`
1628 // * type nodes are:
1629 // 1. `std::vec::Vec<T>` (created above)
1630 // 2. `<std::vec::Vec<T>>::IntoIter`
1631 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1632 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1633 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1634 let segment = P(self.lower_path_segment(
1639 ParenthesizedGenericArgs::Warn,
1642 let qpath = hir::QPath::TypeRelative(ty, segment);
1644 // It's finished, return the extension of the right node type.
1645 if i == p.segments.len() - 1 {
1649 // Wrap the associated extension in another type node.
1650 let new_id = self.next_id();
1651 ty = P(self.ty_path(new_id, p.span, qpath));
1654 // Should've returned in the for loop above.
1657 "lower_qpath: no final extension segment in {}..{}",
1663 fn lower_path_extra(
1667 ident: Option<Ident>,
1668 param_mode: ParamMode,
1672 segments: p.segments
1675 self.lower_path_segment(
1680 ParenthesizedGenericArgs::Err,
1681 ImplTraitContext::Disallowed,
1684 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1690 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1691 let def = self.expect_full_def(id);
1692 self.lower_path_extra(def, p, None, param_mode)
1695 fn lower_path_segment(
1698 segment: &PathSegment,
1699 param_mode: ParamMode,
1700 expected_lifetimes: usize,
1701 parenthesized_generic_args: ParenthesizedGenericArgs,
1702 itctx: ImplTraitContext,
1703 ) -> hir::PathSegment {
1704 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1705 let msg = "parenthesized parameters may only be used with a trait";
1706 match **generic_args {
1707 GenericArgs::AngleBracketed(ref data) => {
1708 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1710 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1711 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1712 ParenthesizedGenericArgs::Warn => {
1713 self.sess.buffer_lint(
1714 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1719 (hir::GenericArgs::none(), true)
1721 ParenthesizedGenericArgs::Err => {
1722 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1723 .span_label(data.span, "only traits may use parentheses")
1725 (hir::GenericArgs::none(), true)
1730 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1733 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1734 GenericArg::Lifetime(_) => true,
1737 if !generic_args.parenthesized && !has_lifetimes {
1739 self.elided_path_lifetimes(path_span, expected_lifetimes)
1741 .map(|lt| GenericArg::Lifetime(lt))
1742 .chain(generic_args.args.into_iter())
1746 hir::PathSegment::new(
1753 fn lower_angle_bracketed_parameter_data(
1755 data: &AngleBracketedArgs,
1756 param_mode: ParamMode,
1757 itctx: ImplTraitContext,
1758 ) -> (hir::GenericArgs, bool) {
1759 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1760 let has_types = args.iter().any(|arg| match arg {
1761 ast::GenericArg::Type(_) => true,
1765 args: args.iter().map(|a| self.lower_generic_arg(a, itctx)).collect(),
1766 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1767 parenthesized: false,
1769 !has_types && param_mode == ParamMode::Optional)
1772 fn lower_parenthesized_parameter_data(
1774 data: &ParenthesisedArgs,
1775 ) -> (hir::GenericArgs, bool) {
1776 // Switch to `PassThrough` mode for anonymous lifetimes: this
1777 // means that we permit things like `&Ref<T>`, where `Ref` has
1778 // a hidden lifetime parameter. This is needed for backwards
1779 // compatibility, even in contexts like an impl header where
1780 // we generally don't permit such things (see #51008).
1781 self.with_anonymous_lifetime_mode(
1782 AnonymousLifetimeMode::PassThrough,
1784 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1785 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1786 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1787 let mk_tup = |this: &mut Self, tys, span| {
1788 let LoweredNodeId { node_id, hir_id } = this.next_id();
1789 hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span }
1794 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1797 id: this.next_id().node_id,
1798 ident: Ident::from_str(FN_OUTPUT_NAME),
1801 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1802 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1803 span: output.as_ref().map_or(span, |ty| ty.span),
1806 parenthesized: true,
1814 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1815 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1821 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1822 pat: self.lower_pat(&l.pat),
1823 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1825 attrs: l.attrs.clone(),
1826 source: hir::LocalSource::Normal,
1830 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1832 Mutability::Mutable => hir::MutMutable,
1833 Mutability::Immutable => hir::MutImmutable,
1837 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1838 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1842 pat: self.lower_pat(&arg.pat),
1846 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1849 .map(|arg| match arg.pat.node {
1850 PatKind::Ident(_, ident, _) => ident,
1851 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1856 // Lowers a function declaration.
1858 // decl: the unlowered (ast) function declaration.
1859 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1860 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1861 // make_ret_async is also `Some`.
1862 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1863 // This guards against trait declarations and implementations where impl Trait is
1865 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1866 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1867 // return type impl Trait item.
1871 fn_def_id: Option<DefId>,
1872 impl_trait_return_allow: bool,
1873 make_ret_async: Option<NodeId>,
1874 ) -> P<hir::FnDecl> {
1875 let inputs = decl.inputs
1878 if let Some(def_id) = fn_def_id {
1879 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(def_id))
1881 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
1884 .collect::<HirVec<_>>();
1886 let output = if let Some(ret_id) = make_ret_async {
1887 self.lower_async_fn_ret_ty(
1888 &inputs, &decl.output, fn_def_id.expect("make_ret_async but no fn_def_id"), ret_id)
1891 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1892 Some(def_id) if impl_trait_return_allow => {
1893 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1895 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1897 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1904 variadic: decl.variadic,
1905 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1906 TyKind::ImplicitSelf => true,
1907 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1913 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
1915 // fn_span: the span of the async function declaration. Used for error reporting.
1916 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
1917 // output: unlowered output type (`T` in `-> T`)
1918 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
1919 fn lower_async_fn_ret_ty(
1922 output: &FunctionRetTy,
1924 return_impl_trait_id: NodeId,
1925 ) -> hir::FunctionRetTy {
1926 // Get lifetimes used in the input arguments to the function. Our output type must also
1927 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
1928 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
1929 // is a subset of the other. We really want some new lifetime that is a subset of all input
1930 // lifetimes, but that doesn't exist at the moment.
1932 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
1933 context: &'r mut LoweringContext<'a>,
1934 // Lifetimes bound by HRTB
1935 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1936 // Whether to count elided lifetimes.
1937 // Disabled inside of `Fn` or `fn` syntax.
1938 collect_elided_lifetimes: bool,
1939 // The lifetime found.
1940 // Multiple different or elided lifetimes cannot appear in async fn for now.
1941 output_lifetime: Option<(hir::LifetimeName, Span)>,
1944 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
1945 fn nested_visit_map<'this>(
1947 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1948 hir::intravisit::NestedVisitorMap::None
1951 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1952 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1953 if parameters.parenthesized {
1954 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1955 self.collect_elided_lifetimes = false;
1956 hir::intravisit::walk_generic_args(self, span, parameters);
1957 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1959 hir::intravisit::walk_generic_args(self, span, parameters);
1963 fn visit_ty(&mut self, t: &'v hir::Ty) {
1964 // Don't collect elided lifetimes used inside of `fn()` syntax
1965 if let &hir::Ty_::TyBareFn(_) = &t.node {
1966 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1967 self.collect_elided_lifetimes = false;
1969 // Record the "stack height" of `for<'a>` lifetime bindings
1970 // to be able to later fully undo their introduction.
1971 let old_len = self.currently_bound_lifetimes.len();
1972 hir::intravisit::walk_ty(self, t);
1973 self.currently_bound_lifetimes.truncate(old_len);
1975 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1977 hir::intravisit::walk_ty(self, t);
1981 fn visit_poly_trait_ref(
1983 trait_ref: &'v hir::PolyTraitRef,
1984 modifier: hir::TraitBoundModifier,
1986 // Record the "stack height" of `for<'a>` lifetime bindings
1987 // to be able to later fully undo their introduction.
1988 let old_len = self.currently_bound_lifetimes.len();
1989 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1990 self.currently_bound_lifetimes.truncate(old_len);
1993 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1994 // Record the introduction of 'a in `for<'a> ...`
1995 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1996 // Introduce lifetimes one at a time so that we can handle
1997 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1998 let lt_name = hir::LifetimeName::Param(param.name);
1999 self.currently_bound_lifetimes.push(lt_name);
2002 hir::intravisit::walk_generic_param(self, param);
2005 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2006 let name = match lifetime.name {
2007 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2008 if self.collect_elided_lifetimes {
2009 // Use `'_` for both implicit and underscore lifetimes in
2010 // `abstract type Foo<'_>: SomeTrait<'_>;`
2011 hir::LifetimeName::Underscore
2016 hir::LifetimeName::Param(_) => lifetime.name,
2017 hir::LifetimeName::Static => return,
2020 if !self.currently_bound_lifetimes.contains(&name) {
2021 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2022 // We don't currently have a reliable way to desugar `async fn` with
2023 // multiple potentially unrelated input lifetimes into
2024 // `-> impl Trait + 'lt`, so we report an error in this case.
2025 if current_lt_name != name {
2028 current_lt_span.between(lifetime.span),
2030 "multiple different lifetimes used in arguments of `async fn`",
2032 .span_label(current_lt_span, "first lifetime here")
2033 .span_label(lifetime.span, "different lifetime here")
2034 .help("`async fn` can only accept borrowed values \
2035 with identical lifetimes")
2037 } else if current_lt_name.is_elided() && name.is_elided() {
2040 current_lt_span.between(lifetime.span),
2042 "multiple elided lifetimes used in arguments of `async fn`",
2044 .span_label(current_lt_span, "first lifetime here")
2045 .span_label(lifetime.span, "different lifetime here")
2046 .help("consider giving these arguments named lifetimes")
2050 self.output_lifetime = Some((name, lifetime.span));
2056 let bound_lifetime = {
2057 let mut lifetime_collector = AsyncFnLifetimeCollector {
2059 currently_bound_lifetimes: Vec::new(),
2060 collect_elided_lifetimes: true,
2061 output_lifetime: None,
2065 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2067 lifetime_collector.output_lifetime
2070 let span = match output {
2071 FunctionRetTy::Ty(ty) => ty.span,
2072 FunctionRetTy::Default(span) => *span,
2075 let impl_trait_ty = self.lower_existential_impl_trait(
2076 span, fn_def_id, return_impl_trait_id, |this| {
2077 let output_ty = match output {
2078 FunctionRetTy::Ty(ty) =>
2079 this.lower_ty(ty, ImplTraitContext::Existential(fn_def_id)),
2080 FunctionRetTy::Default(span) => {
2081 let LoweredNodeId { node_id, hir_id } = this.next_id();
2085 node: hir::TyTup(hir_vec![]),
2092 let future_params = P(hir::GenericArgs {
2094 bindings: hir_vec![hir::TypeBinding {
2095 ident: Ident::from_str(FN_OUTPUT_NAME),
2097 id: this.next_id().node_id,
2100 parenthesized: false,
2104 this.std_path(span, &["future", "Future"], Some(future_params), false);
2106 let mut bounds = vec![
2107 hir::GenericBound::Trait(
2109 trait_ref: hir::TraitRef {
2111 ref_id: this.next_id().node_id,
2113 bound_generic_params: hir_vec![],
2116 hir::TraitBoundModifier::None
2120 if let Some((name, span)) = bound_lifetime {
2121 bounds.push(hir::GenericBound::Outlives(
2122 hir::Lifetime { id: this.next_id().node_id, name, span }));
2125 hir::HirVec::from(bounds)
2128 let LoweredNodeId { node_id, hir_id } = self.next_id();
2129 let impl_trait_ty = P(hir::Ty {
2131 node: impl_trait_ty,
2136 hir::FunctionRetTy::Return(impl_trait_ty)
2139 fn lower_param_bound(
2142 itctx: ImplTraitContext,
2143 ) -> hir::GenericBound {
2145 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2146 self.lower_poly_trait_ref(ty, itctx),
2147 self.lower_trait_bound_modifier(modifier),
2149 GenericBound::Outlives(ref lifetime) => {
2150 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2155 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2156 let span = l.ident.span;
2158 ident if ident.name == keywords::StaticLifetime.name() =>
2159 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2160 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2161 match self.anonymous_lifetime_mode {
2162 AnonymousLifetimeMode::CreateParameter => {
2163 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2164 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2167 AnonymousLifetimeMode::PassThrough => {
2168 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2172 self.maybe_collect_in_band_lifetime(ident);
2173 let param_name = ParamName::Plain(ident);
2174 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2179 fn new_named_lifetime(
2183 name: hir::LifetimeName,
2184 ) -> hir::Lifetime {
2186 id: self.lower_node_id(id).node_id,
2192 fn lower_generic_params(
2194 params: &Vec<GenericParam>,
2195 add_bounds: &NodeMap<Vec<GenericBound>>,
2196 itctx: ImplTraitContext,
2197 ) -> hir::HirVec<hir::GenericParam> {
2198 params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect()
2201 fn lower_generic_param(&mut self,
2202 param: &GenericParam,
2203 add_bounds: &NodeMap<Vec<GenericBound>>,
2204 itctx: ImplTraitContext)
2205 -> hir::GenericParam {
2206 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx);
2208 GenericParamKind::Lifetime => {
2209 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2210 self.is_collecting_in_band_lifetimes = false;
2212 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2213 let param_name = match lt.name {
2214 hir::LifetimeName::Param(param_name) => param_name,
2215 _ => hir::ParamName::Plain(lt.name.ident()),
2217 let param = hir::GenericParam {
2221 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2222 attrs: self.lower_attrs(¶m.attrs),
2224 kind: hir::GenericParamKind::Lifetime { in_band: false }
2227 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2231 GenericParamKind::Type { ref default, .. } => {
2232 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2233 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2234 // Instead, use gensym("Self") to create a distinct name that looks the same.
2235 let ident = if param.ident.name == keywords::SelfType.name() {
2236 param.ident.gensym()
2241 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2242 if !add_bounds.is_empty() {
2243 bounds = bounds.into_iter()
2244 .chain(self.lower_param_bounds(add_bounds, itctx).into_iter())
2249 id: self.lower_node_id(param.id).node_id,
2250 name: hir::ParamName::Plain(ident),
2251 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2252 attrs: self.lower_attrs(¶m.attrs),
2255 kind: hir::GenericParamKind::Type {
2256 default: default.as_ref().map(|x| {
2257 self.lower_ty(x, ImplTraitContext::Disallowed)
2259 synthetic: param.attrs.iter()
2260 .filter(|attr| attr.check_name("rustc_synthetic"))
2261 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2271 generics: &Generics,
2272 itctx: ImplTraitContext)
2275 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2276 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2277 // paths where report_error is called are also the only paths that advance to after
2278 // the match statement, so the error reporting could probably just be moved there.
2279 let mut add_bounds = NodeMap();
2280 for pred in &generics.where_clause.predicates {
2281 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2282 'next_bound: for bound in &bound_pred.bounds {
2283 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2284 let report_error = |this: &mut Self| {
2285 this.diagnostic().span_err(
2286 bound_pred.bounded_ty.span,
2287 "`?Trait` bounds are only permitted at the \
2288 point where a type parameter is declared",
2291 // Check if the where clause type is a plain type parameter.
2292 match bound_pred.bounded_ty.node {
2293 TyKind::Path(None, ref path)
2294 if path.segments.len() == 1
2295 && bound_pred.bound_generic_params.is_empty() =>
2297 if let Some(Def::TyParam(def_id)) = self.resolver
2298 .get_resolution(bound_pred.bounded_ty.id)
2299 .map(|d| d.base_def())
2301 if let Some(node_id) =
2302 self.resolver.definitions().as_local_node_id(def_id)
2304 for param in &generics.params {
2306 GenericParamKind::Type { .. } => {
2307 if node_id == param.id {
2308 add_bounds.entry(param.id)
2309 .or_insert(Vec::new())
2310 .push(bound.clone());
2311 continue 'next_bound;
2321 _ => report_error(self),
2329 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2330 where_clause: self.lower_where_clause(&generics.where_clause),
2331 span: generics.span,
2335 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2337 id: self.lower_node_id(wc.id).node_id,
2338 predicates: wc.predicates
2340 .map(|predicate| self.lower_where_predicate(predicate))
2345 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2347 WherePredicate::BoundPredicate(WhereBoundPredicate {
2348 ref bound_generic_params,
2353 self.with_in_scope_lifetime_defs(
2354 &bound_generic_params,
2356 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2357 bound_generic_params: this.lower_generic_params(
2358 bound_generic_params,
2360 ImplTraitContext::Disallowed,
2362 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2365 .filter_map(|bound| match *bound {
2366 // Ignore `?Trait` bounds.
2367 // Tthey were copied into type parameters already.
2368 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2369 _ => Some(this.lower_param_bound(
2371 ImplTraitContext::Disallowed,
2380 WherePredicate::RegionPredicate(WhereRegionPredicate {
2384 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2386 lifetime: self.lower_lifetime(lifetime),
2387 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2389 WherePredicate::EqPredicate(WhereEqPredicate {
2394 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2395 id: self.lower_node_id(id).node_id,
2396 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2397 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2403 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2405 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2409 .map(|f| self.lower_struct_field(f))
2411 self.lower_node_id(id).node_id,
2413 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2417 .map(|f| self.lower_struct_field(f))
2419 self.lower_node_id(id).node_id,
2421 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2425 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2426 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2427 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2428 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2432 ref_id: self.lower_node_id(p.ref_id).node_id,
2436 fn lower_poly_trait_ref(
2439 itctx: ImplTraitContext,
2440 ) -> hir::PolyTraitRef {
2441 let bound_generic_params =
2442 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2443 let trait_ref = self.with_parent_impl_lifetime_defs(
2444 &bound_generic_params,
2445 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2449 bound_generic_params,
2455 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2458 id: self.lower_node_id(f.id).node_id,
2459 ident: match f.ident {
2460 Some(ident) => ident,
2461 // FIXME(jseyfried) positional field hygiene
2462 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2464 vis: self.lower_visibility(&f.vis, None),
2465 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2466 attrs: self.lower_attrs(&f.attrs),
2470 fn lower_field(&mut self, f: &Field) -> hir::Field {
2472 id: self.next_id().node_id,
2474 expr: P(self.lower_expr(&f.expr)),
2476 is_shorthand: f.is_shorthand,
2480 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2482 ty: self.lower_ty(&mt.ty, itctx),
2483 mutbl: self.lower_mutability(mt.mutbl),
2487 fn lower_param_bounds(&mut self, bounds: &[GenericBound], itctx: ImplTraitContext)
2488 -> hir::GenericBounds {
2489 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx)).collect()
2492 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2493 let mut expr = None;
2495 let mut stmts = vec![];
2497 for (index, stmt) in b.stmts.iter().enumerate() {
2498 if index == b.stmts.len() - 1 {
2499 if let StmtKind::Expr(ref e) = stmt.node {
2500 expr = Some(P(self.lower_expr(e)));
2502 stmts.extend(self.lower_stmt(stmt));
2505 stmts.extend(self.lower_stmt(stmt));
2509 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2514 stmts: stmts.into(),
2516 rules: self.lower_block_check_mode(&b.rules),
2519 recovered: b.recovered,
2527 attrs: &hir::HirVec<Attribute>,
2528 vis: &mut hir::Visibility,
2532 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2533 ItemKind::Use(ref use_tree) => {
2534 // Start with an empty prefix
2537 span: use_tree.span,
2540 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2542 ItemKind::Static(ref t, m, ref e) => {
2543 let value = self.lower_body(None, |this| this.lower_expr(e));
2545 self.lower_ty(t, ImplTraitContext::Disallowed),
2546 self.lower_mutability(m),
2550 ItemKind::Const(ref t, ref e) => {
2551 let value = self.lower_body(None, |this| this.lower_expr(e));
2552 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2554 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2555 let fn_def_id = self.resolver.definitions().local_def_id(id);
2557 self.with_new_scopes(|this| {
2558 // Note: we don't need to change the return type from `T` to
2559 // `impl Future<Output = T>` here because lower_body
2560 // only cares about the input argument patterns in the function
2561 // declaration (decl), not the return types.
2562 let body_id = this.lower_body(Some(decl), |this| {
2563 if let IsAsync::Async { closure_id, .. } = header.asyncness {
2564 let async_expr = this.make_async_expr(
2565 CaptureBy::Value, closure_id, None,
2567 let body = this.lower_block(body, false);
2568 this.expr_block(body, ThinVec::new())
2570 this.expr(body.span, async_expr, ThinVec::new())
2572 let body = this.lower_block(body, false);
2573 this.expr_block(body, ThinVec::new())
2577 let (generics, fn_decl) = this.add_in_band_defs(
2580 AnonymousLifetimeMode::PassThrough,
2581 |this| this.lower_fn_decl(
2582 decl, Some(fn_def_id), true, header.asyncness.opt_return_id())
2587 this.lower_fn_header(header),
2593 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2594 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2595 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2596 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2597 self.lower_ty(t, ImplTraitContext::Disallowed),
2598 self.lower_generics(generics, ImplTraitContext::Disallowed),
2600 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2602 variants: enum_definition
2605 .map(|x| self.lower_variant(x))
2608 self.lower_generics(generics, ImplTraitContext::Disallowed),
2610 ItemKind::Struct(ref struct_def, ref generics) => {
2611 let struct_def = self.lower_variant_data(struct_def);
2614 self.lower_generics(generics, ImplTraitContext::Disallowed),
2617 ItemKind::Union(ref vdata, ref generics) => {
2618 let vdata = self.lower_variant_data(vdata);
2621 self.lower_generics(generics, ImplTraitContext::Disallowed),
2633 let def_id = self.resolver.definitions().local_def_id(id);
2635 // Lower the "impl header" first. This ordering is important
2636 // for in-band lifetimes! Consider `'a` here:
2638 // impl Foo<'a> for u32 {
2639 // fn method(&'a self) { .. }
2642 // Because we start by lowering the `Foo<'a> for u32`
2643 // part, we will add `'a` to the list of generics on
2644 // the impl. When we then encounter it later in the
2645 // method, it will not be considered an in-band
2646 // lifetime to be added, but rather a reference to a
2648 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2651 AnonymousLifetimeMode::CreateParameter,
2653 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2654 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2657 if let Some(ref trait_ref) = trait_ref {
2658 if let Def::Trait(def_id) = trait_ref.path.def {
2659 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2663 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2665 (trait_ref, lowered_ty)
2669 let new_impl_items = self.with_in_scope_lifetime_defs(
2670 &ast_generics.params,
2674 .map(|item| this.lower_impl_item_ref(item))
2680 self.lower_unsafety(unsafety),
2681 self.lower_impl_polarity(polarity),
2682 self.lower_defaultness(defaultness, true /* [1] */),
2689 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2690 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2693 .map(|item| self.lower_trait_item_ref(item))
2696 self.lower_is_auto(is_auto),
2697 self.lower_unsafety(unsafety),
2698 self.lower_generics(generics, ImplTraitContext::Disallowed),
2703 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2704 self.lower_generics(generics, ImplTraitContext::Disallowed),
2705 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2707 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2710 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2711 // not cause an assertion failure inside the `lower_defaultness` function
2719 vis: &mut hir::Visibility,
2721 attrs: &hir::HirVec<Attribute>,
2723 let path = &tree.prefix;
2726 UseTreeKind::Simple(rename, id1, id2) => {
2727 *name = tree.ident().name;
2729 // First apply the prefix to the path
2730 let mut path = Path {
2734 .chain(path.segments.iter())
2740 // Correctly resolve `self` imports
2741 if path.segments.len() > 1
2742 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2744 let _ = path.segments.pop();
2745 if rename.is_none() {
2746 *name = path.segments.last().unwrap().ident.name;
2750 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2751 let mut defs = self.expect_full_def_from_use(id);
2752 // we want to return *something* from this function, so hang onto the first item
2754 let mut ret_def = defs.next().unwrap_or(Def::Err);
2756 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2757 let vis = vis.clone();
2758 let name = name.clone();
2759 let span = path.span;
2760 self.resolver.definitions().create_def_with_parent(
2764 DefIndexAddressSpace::High,
2767 self.allocate_hir_id_counter(new_node_id, &path);
2769 self.with_hir_id_owner(new_node_id, |this| {
2770 let new_id = this.lower_node_id(new_node_id);
2771 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2772 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2773 let vis_kind = match vis.node {
2774 hir::VisibilityPublic => hir::VisibilityPublic,
2775 hir::VisibilityCrate(sugar) => hir::VisibilityCrate(sugar),
2776 hir::VisibilityInherited => hir::VisibilityInherited,
2777 hir::VisibilityRestricted { ref path, id: _ } => {
2778 hir::VisibilityRestricted {
2780 // We are allocating a new NodeId here
2781 id: this.next_id().node_id,
2785 let vis = respan(vis.span, vis_kind);
2791 hir_id: new_id.hir_id,
2793 attrs: attrs.clone(),
2802 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2803 hir::ItemUse(path, hir::UseKind::Single)
2805 UseTreeKind::Glob => {
2806 let path = P(self.lower_path(
2812 .chain(path.segments.iter())
2817 ParamMode::Explicit,
2819 hir::ItemUse(path, hir::UseKind::Glob)
2821 UseTreeKind::Nested(ref trees) => {
2826 .chain(path.segments.iter())
2829 span: prefix.span.to(path.span),
2832 // Add all the nested PathListItems in the HIR
2833 for &(ref use_tree, id) in trees {
2834 self.allocate_hir_id_counter(id, &use_tree);
2838 } = self.lower_node_id(id);
2840 let mut vis = vis.clone();
2841 let mut name = name.clone();
2843 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2845 self.with_hir_id_owner(new_id, |this| {
2846 let vis_kind = match vis.node {
2847 hir::VisibilityPublic => hir::VisibilityPublic,
2848 hir::VisibilityCrate(sugar) => hir::VisibilityCrate(sugar),
2849 hir::VisibilityInherited => hir::VisibilityInherited,
2850 hir::VisibilityRestricted { ref path, id: _ } => {
2851 hir::VisibilityRestricted {
2853 // We are allocating a new NodeId here
2854 id: this.next_id().node_id,
2858 let vis = respan(vis.span, vis_kind);
2866 attrs: attrs.clone(),
2869 span: use_tree.span,
2875 // Privatize the degenerate import base, used only to check
2876 // the stability of `use a::{};`, to avoid it showing up as
2877 // a re-export by accident when `pub`, e.g. in documentation.
2878 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2879 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityInherited);
2880 hir::ItemUse(path, hir::UseKind::ListStem)
2885 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2886 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2887 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2889 let (generics, node) = match i.node {
2890 TraitItemKind::Const(ref ty, ref default) => (
2891 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2892 hir::TraitItemKind::Const(
2893 self.lower_ty(ty, ImplTraitContext::Disallowed),
2896 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2899 TraitItemKind::Method(ref sig, None) => {
2900 let names = self.lower_fn_args_to_names(&sig.decl);
2901 self.add_in_band_defs(
2904 AnonymousLifetimeMode::PassThrough,
2906 hir::TraitItemKind::Method(
2907 this.lower_method_sig(sig, trait_item_def_id, false, None),
2908 hir::TraitMethod::Required(names),
2913 TraitItemKind::Method(ref sig, Some(ref body)) => {
2914 let body_id = self.lower_body(Some(&sig.decl), |this| {
2915 let body = this.lower_block(body, false);
2916 this.expr_block(body, ThinVec::new())
2919 self.add_in_band_defs(
2922 AnonymousLifetimeMode::PassThrough,
2924 hir::TraitItemKind::Method(
2925 this.lower_method_sig(sig, trait_item_def_id, false, None),
2926 hir::TraitMethod::Provided(body_id),
2931 TraitItemKind::Type(ref bounds, ref default) => (
2932 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2933 hir::TraitItemKind::Type(
2934 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2937 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2940 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2947 attrs: self.lower_attrs(&i.attrs),
2954 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2955 let (kind, has_default) = match i.node {
2956 TraitItemKind::Const(_, ref default) => {
2957 (hir::AssociatedItemKind::Const, default.is_some())
2959 TraitItemKind::Type(_, ref default) => {
2960 (hir::AssociatedItemKind::Type, default.is_some())
2962 TraitItemKind::Method(ref sig, ref default) => (
2963 hir::AssociatedItemKind::Method {
2964 has_self: sig.decl.has_self(),
2968 TraitItemKind::Macro(..) => unimplemented!(),
2971 id: hir::TraitItemId { node_id: i.id },
2974 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2979 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2980 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2981 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2983 let (generics, node) = match i.node {
2984 ImplItemKind::Const(ref ty, ref expr) => {
2985 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
2987 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2988 hir::ImplItemKind::Const(
2989 self.lower_ty(ty, ImplTraitContext::Disallowed),
2994 ImplItemKind::Method(ref sig, ref body) => {
2995 let body_id = self.lower_body(Some(&sig.decl), |this| {
2996 if let IsAsync::Async { closure_id, .. } = sig.header.asyncness {
2997 let async_expr = this.make_async_expr(
2998 CaptureBy::Value, closure_id, None,
3000 let body = this.lower_block(body, false);
3001 this.expr_block(body, ThinVec::new())
3003 this.expr(body.span, async_expr, ThinVec::new())
3005 let body = this.lower_block(body, false);
3006 this.expr_block(body, ThinVec::new())
3009 let impl_trait_return_allow = !self.is_in_trait_impl;
3011 self.add_in_band_defs(
3014 AnonymousLifetimeMode::PassThrough,
3016 hir::ImplItemKind::Method(
3017 this.lower_method_sig(
3020 impl_trait_return_allow,
3021 sig.header.asyncness.opt_return_id(),
3028 ImplItemKind::Type(ref ty) => (
3029 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3030 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3032 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3039 attrs: self.lower_attrs(&i.attrs),
3041 vis: self.lower_visibility(&i.vis, None),
3042 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3047 // [1] since `default impl` is not yet implemented, this is always true in impls
3050 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3052 id: hir::ImplItemId { node_id: i.id },
3055 vis: self.lower_visibility(&i.vis, Some(i.id)),
3056 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3057 kind: match i.node {
3058 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3059 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3060 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3061 has_self: sig.decl.has_self(),
3063 ImplItemKind::Macro(..) => unimplemented!(),
3067 // [1] since `default impl` is not yet implemented, this is always true in impls
3070 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3073 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3077 /// Lowers `impl Trait` items and appends them to the list
3078 fn lower_impl_trait_ids(
3082 ids: &mut SmallVector<hir::ItemId>,
3084 if let Some(id) = header.asyncness.opt_return_id() {
3085 ids.push(hir::ItemId { id });
3087 struct IdVisitor<'a> { ids: &'a mut SmallVector<hir::ItemId> }
3088 impl<'a, 'b> Visitor<'a> for IdVisitor<'b> {
3089 fn visit_ty(&mut self, ty: &'a Ty) {
3095 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
3098 visit::walk_ty(self, ty);
3100 fn visit_path_segment(
3103 path_segment: &'v PathSegment,
3105 if let Some(ref p) = path_segment.args {
3106 if let GenericArgs::Parenthesized(_) = **p {
3110 visit::walk_path_segment(self, path_span, path_segment)
3113 let mut visitor = IdVisitor { ids };
3115 FunctionRetTy::Default(_) => {},
3116 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3120 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
3122 ItemKind::Use(ref use_tree) => {
3123 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
3124 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3127 ItemKind::MacroDef(..) => SmallVector::new(),
3128 ItemKind::Fn(ref decl, ref header, ..) => {
3129 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3130 self.lower_impl_trait_ids(decl, header, &mut ids);
3133 ItemKind::Impl(.., None, _, ref items) => {
3134 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3136 if let ImplItemKind::Method(ref sig, _) = item.node {
3137 self.lower_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3142 _ => SmallVector::one(hir::ItemId { id: i.id }),
3146 fn lower_item_id_use_tree(&mut self,
3149 vec: &mut SmallVector<hir::ItemId>)
3152 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3153 vec.push(hir::ItemId { id });
3154 self.lower_item_id_use_tree(nested, id, vec);
3156 UseTreeKind::Glob => {}
3157 UseTreeKind::Simple(_, id1, id2) => {
3158 for (_, &id) in self.expect_full_def_from_use(base_id)
3160 .zip([id1, id2].iter())
3162 vec.push(hir::ItemId { id });
3168 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3169 let mut name = i.ident.name;
3170 let mut vis = self.lower_visibility(&i.vis, None);
3171 let attrs = self.lower_attrs(&i.attrs);
3172 if let ItemKind::MacroDef(ref def) = i.node {
3173 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
3174 let body = self.lower_token_stream(def.stream());
3175 self.exported_macros.push(hir::MacroDef {
3188 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3190 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3203 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3204 let node_id = self.lower_node_id(i.id).node_id;
3205 let def_id = self.resolver.definitions().local_def_id(node_id);
3209 attrs: self.lower_attrs(&i.attrs),
3210 node: match i.node {
3211 ForeignItemKind::Fn(ref fdec, ref generics) => {
3212 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3215 AnonymousLifetimeMode::PassThrough,
3218 // Disallow impl Trait in foreign items
3219 this.lower_fn_decl(fdec, None, false, None),
3220 this.lower_fn_args_to_names(fdec),
3225 hir::ForeignItemFn(fn_dec, fn_args, generics)
3227 ForeignItemKind::Static(ref t, m) => {
3228 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3230 ForeignItemKind::Ty => hir::ForeignItemType,
3231 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3233 vis: self.lower_visibility(&i.vis, None),
3238 fn lower_method_sig(
3242 impl_trait_return_allow: bool,
3243 is_async: Option<NodeId>,
3244 ) -> hir::MethodSig {
3246 header: self.lower_fn_header(sig.header),
3247 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow, is_async),
3251 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3253 IsAuto::Yes => hir::IsAuto::Yes,
3254 IsAuto::No => hir::IsAuto::No,
3258 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3260 unsafety: self.lower_unsafety(h.unsafety),
3261 asyncness: self.lower_asyncness(h.asyncness),
3262 constness: self.lower_constness(h.constness),
3267 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3269 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3270 Unsafety::Normal => hir::Unsafety::Normal,
3274 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3276 Constness::Const => hir::Constness::Const,
3277 Constness::NotConst => hir::Constness::NotConst,
3281 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3283 IsAsync::Async { .. } => hir::IsAsync::Async,
3284 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3288 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3290 UnOp::Deref => hir::UnDeref,
3291 UnOp::Not => hir::UnNot,
3292 UnOp::Neg => hir::UnNeg,
3296 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3298 node: match b.node {
3299 BinOpKind::Add => hir::BiAdd,
3300 BinOpKind::Sub => hir::BiSub,
3301 BinOpKind::Mul => hir::BiMul,
3302 BinOpKind::Div => hir::BiDiv,
3303 BinOpKind::Rem => hir::BiRem,
3304 BinOpKind::And => hir::BiAnd,
3305 BinOpKind::Or => hir::BiOr,
3306 BinOpKind::BitXor => hir::BiBitXor,
3307 BinOpKind::BitAnd => hir::BiBitAnd,
3308 BinOpKind::BitOr => hir::BiBitOr,
3309 BinOpKind::Shl => hir::BiShl,
3310 BinOpKind::Shr => hir::BiShr,
3311 BinOpKind::Eq => hir::BiEq,
3312 BinOpKind::Lt => hir::BiLt,
3313 BinOpKind::Le => hir::BiLe,
3314 BinOpKind::Ne => hir::BiNe,
3315 BinOpKind::Ge => hir::BiGe,
3316 BinOpKind::Gt => hir::BiGt,
3322 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3323 let node = match p.node {
3324 PatKind::Wild => hir::PatKind::Wild,
3325 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3326 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3327 // `None` can occur in body-less function signatures
3328 def @ None | def @ Some(Def::Local(_)) => {
3329 let canonical_id = match def {
3330 Some(Def::Local(id)) => id,
3333 hir::PatKind::Binding(
3334 self.lower_binding_mode(binding_mode),
3337 sub.as_ref().map(|x| self.lower_pat(x)),
3340 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3345 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3350 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3351 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3352 let qpath = self.lower_qpath(
3356 ParamMode::Optional,
3357 ImplTraitContext::Disallowed,
3359 hir::PatKind::TupleStruct(
3361 pats.iter().map(|x| self.lower_pat(x)).collect(),
3365 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3369 ParamMode::Optional,
3370 ImplTraitContext::Disallowed,
3372 PatKind::Struct(ref path, ref fields, etc) => {
3373 let qpath = self.lower_qpath(
3377 ParamMode::Optional,
3378 ImplTraitContext::Disallowed,
3385 node: hir::FieldPat {
3386 id: self.next_id().node_id,
3387 ident: f.node.ident,
3388 pat: self.lower_pat(&f.node.pat),
3389 is_shorthand: f.node.is_shorthand,
3393 hir::PatKind::Struct(qpath, fs, etc)
3395 PatKind::Tuple(ref elts, ddpos) => {
3396 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3398 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3399 PatKind::Ref(ref inner, mutbl) => {
3400 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3402 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3403 P(self.lower_expr(e1)),
3404 P(self.lower_expr(e2)),
3405 self.lower_range_end(end),
3407 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3408 before.iter().map(|x| self.lower_pat(x)).collect(),
3409 slice.as_ref().map(|x| self.lower_pat(x)),
3410 after.iter().map(|x| self.lower_pat(x)).collect(),
3412 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3413 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3416 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3425 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3427 RangeEnd::Included(_) => hir::RangeEnd::Included,
3428 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3432 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3433 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3438 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3442 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3443 let kind = match e.node {
3444 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3445 ExprKind::ObsoleteInPlace(..) => {
3446 self.sess.abort_if_errors();
3447 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3449 ExprKind::Array(ref exprs) => {
3450 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3452 ExprKind::Repeat(ref expr, ref count) => {
3453 let expr = P(self.lower_expr(expr));
3454 let count = self.lower_anon_const(count);
3455 hir::ExprRepeat(expr, count)
3457 ExprKind::Tup(ref elts) => {
3458 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3460 ExprKind::Call(ref f, ref args) => {
3461 let f = P(self.lower_expr(f));
3462 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3464 ExprKind::MethodCall(ref seg, ref args) => {
3465 let hir_seg = self.lower_path_segment(
3468 ParamMode::Optional,
3470 ParenthesizedGenericArgs::Err,
3471 ImplTraitContext::Disallowed,
3473 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3474 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3476 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3477 let binop = self.lower_binop(binop);
3478 let lhs = P(self.lower_expr(lhs));
3479 let rhs = P(self.lower_expr(rhs));
3480 hir::ExprBinary(binop, lhs, rhs)
3482 ExprKind::Unary(op, ref ohs) => {
3483 let op = self.lower_unop(op);
3484 let ohs = P(self.lower_expr(ohs));
3485 hir::ExprUnary(op, ohs)
3487 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3488 ExprKind::Cast(ref expr, ref ty) => {
3489 let expr = P(self.lower_expr(expr));
3490 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3492 ExprKind::Type(ref expr, ref ty) => {
3493 let expr = P(self.lower_expr(expr));
3494 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3496 ExprKind::AddrOf(m, ref ohs) => {
3497 let m = self.lower_mutability(m);
3498 let ohs = P(self.lower_expr(ohs));
3499 hir::ExprAddrOf(m, ohs)
3501 // More complicated than you might expect because the else branch
3502 // might be `if let`.
3503 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3504 let else_opt = else_opt.as_ref().map(|els| {
3506 ExprKind::IfLet(..) => {
3507 // wrap the if-let expr in a block
3508 let span = els.span;
3509 let els = P(self.lower_expr(els));
3510 let LoweredNodeId { node_id, hir_id } = self.next_id();
3511 let blk = P(hir::Block {
3516 rules: hir::DefaultBlock,
3518 targeted_by_break: false,
3519 recovered: blk.recovered,
3521 P(self.expr_block(blk, ThinVec::new()))
3523 _ => P(self.lower_expr(els)),
3527 let then_blk = self.lower_block(blk, false);
3528 let then_expr = self.expr_block(then_blk, ThinVec::new());
3530 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3532 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3534 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3535 this.lower_block(body, false),
3536 this.lower_label(opt_label),
3539 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3541 this.lower_block(body, false),
3542 this.lower_label(opt_label),
3543 hir::LoopSource::Loop,
3546 ExprKind::Catch(ref body) => {
3547 self.with_catch_scope(body.id, |this| {
3549 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3550 let mut block = this.lower_block(body, true).into_inner();
3551 let tail = block.expr.take().map_or_else(
3553 let LoweredNodeId { node_id, hir_id } = this.next_id();
3554 let span = this.sess.codemap().end_point(unstable_span);
3558 node: hir::ExprTup(hir_vec![]),
3559 attrs: ThinVec::new(),
3563 |x: P<hir::Expr>| x.into_inner(),
3565 block.expr = Some(this.wrap_in_try_constructor(
3566 "from_ok", tail, unstable_span));
3567 hir::ExprBlock(P(block), None)
3570 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3571 P(self.lower_expr(expr)),
3572 arms.iter().map(|x| self.lower_arm(x)).collect(),
3573 hir::MatchSource::Normal,
3575 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3576 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3577 this.with_new_scopes(|this| {
3578 let block = this.lower_block(block, false);
3579 this.expr_block(block, ThinVec::new())
3584 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3586 if let IsAsync::Async { closure_id, .. } = asyncness {
3587 let outer_decl = FnDecl {
3588 inputs: decl.inputs.clone(),
3589 output: FunctionRetTy::Default(fn_decl_span),
3592 // We need to lower the declaration outside the new scope, because we
3593 // have to conserve the state of being inside a loop condition for the
3594 // closure argument types.
3595 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3597 self.with_new_scopes(|this| {
3598 // FIXME(cramertj) allow `async` non-`move` closures with
3599 if capture_clause == CaptureBy::Ref &&
3600 !decl.inputs.is_empty()
3606 "`async` non-`move` closures with arguments \
3607 are not currently supported",
3609 .help("consider using `let` statements to manually capture \
3610 variables by reference before entering an \
3611 `async move` closure")
3615 // Transform `async |x: u8| -> X { ... }` into
3616 // `|x: u8| future_from_generator(|| -> X { ... })`
3617 let body_id = this.lower_body(Some(&outer_decl), |this| {
3618 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3621 let async_body = this.make_async_expr(
3622 capture_clause, closure_id, async_ret_ty,
3624 this.with_new_scopes(|this| this.lower_expr(body))
3626 this.expr(fn_decl_span, async_body, ThinVec::new())
3629 this.lower_capture_clause(capture_clause),
3637 // Lower outside new scope to preserve `is_in_loop_condition`.
3638 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3640 self.with_new_scopes(|this| {
3641 let mut is_generator = false;
3642 let body_id = this.lower_body(Some(decl), |this| {
3643 let e = this.lower_expr(body);
3644 is_generator = this.is_generator;
3647 let generator_option = if is_generator {
3648 if !decl.inputs.is_empty() {
3653 "generators cannot have explicit arguments"
3655 this.sess.abort_if_errors();
3657 Some(match movability {
3658 Movability::Movable => hir::GeneratorMovability::Movable,
3659 Movability::Static => hir::GeneratorMovability::Static,
3662 if movability == Movability::Static {
3667 "closures cannot be static"
3673 this.lower_capture_clause(capture_clause),
3682 ExprKind::Block(ref blk, opt_label) => {
3683 hir::ExprBlock(self.lower_block(blk,
3684 opt_label.is_some()),
3685 self.lower_label(opt_label))
3687 ExprKind::Assign(ref el, ref er) => {
3688 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3690 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3691 self.lower_binop(op),
3692 P(self.lower_expr(el)),
3693 P(self.lower_expr(er)),
3695 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3696 ExprKind::Index(ref el, ref er) => {
3697 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3699 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3700 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3701 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3702 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3703 let id = self.next_id();
3704 let e1 = self.lower_expr(e1);
3705 let e2 = self.lower_expr(e2);
3706 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], None, false));
3707 let ty = P(self.ty_path(id, span, hir::QPath::Resolved(None, ty_path)));
3708 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3709 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3710 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3711 hir::ExprCall(new, hir_vec![e1, e2])
3713 ExprKind::Range(ref e1, ref e2, lims) => {
3714 use syntax::ast::RangeLimits::*;
3716 let path = match (e1, e2, lims) {
3717 (&None, &None, HalfOpen) => "RangeFull",
3718 (&Some(..), &None, HalfOpen) => "RangeFrom",
3719 (&None, &Some(..), HalfOpen) => "RangeTo",
3720 (&Some(..), &Some(..), HalfOpen) => "Range",
3721 (&None, &Some(..), Closed) => "RangeToInclusive",
3722 (&Some(..), &Some(..), Closed) => unreachable!(),
3723 (_, &None, Closed) => self.diagnostic()
3724 .span_fatal(e.span, "inclusive range with no end")
3728 let fields = e1.iter()
3729 .map(|e| ("start", e))
3730 .chain(e2.iter().map(|e| ("end", e)))
3732 let expr = P(self.lower_expr(&e));
3734 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3735 let ident = Ident::new(Symbol::intern(s), unstable_span);
3736 self.field(ident, expr, unstable_span)
3738 .collect::<P<[hir::Field]>>();
3740 let is_unit = fields.is_empty();
3742 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3743 let struct_path = iter::once("ops")
3744 .chain(iter::once(path))
3745 .collect::<Vec<_>>();
3746 let struct_path = self.std_path(unstable_span, &struct_path, None, is_unit);
3747 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3749 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3755 hir::ExprPath(struct_path)
3757 hir::ExprStruct(struct_path, fields, None)
3759 span: unstable_span,
3760 attrs: e.attrs.clone(),
3763 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3767 ParamMode::Optional,
3768 ImplTraitContext::Disallowed,
3770 ExprKind::Break(opt_label, ref opt_expr) => {
3771 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3774 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3777 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3781 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3784 ExprKind::Continue(opt_label) => {
3785 hir::ExprContinue(if self.is_in_loop_condition && opt_label.is_none() {
3788 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3791 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3794 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3795 ExprKind::InlineAsm(ref asm) => {
3796 let hir_asm = hir::InlineAsm {
3797 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3798 outputs: asm.outputs
3800 .map(|out| hir::InlineAsmOutput {
3801 constraint: out.constraint.clone(),
3803 is_indirect: out.is_indirect,
3806 asm: asm.asm.clone(),
3807 asm_str_style: asm.asm_str_style,
3808 clobbers: asm.clobbers.clone().into(),
3809 volatile: asm.volatile,
3810 alignstack: asm.alignstack,
3811 dialect: asm.dialect,
3814 let outputs = asm.outputs
3816 .map(|out| self.lower_expr(&out.expr))
3818 let inputs = asm.inputs
3820 .map(|&(_, ref input)| self.lower_expr(input))
3822 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3824 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3829 ParamMode::Optional,
3830 ImplTraitContext::Disallowed,
3832 fields.iter().map(|x| self.lower_field(x)).collect(),
3833 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3835 ExprKind::Paren(ref ex) => {
3836 let mut ex = self.lower_expr(ex);
3837 // include parens in span, but only if it is a super-span.
3838 if e.span.contains(ex.span) {
3841 // merge attributes into the inner expression.
3842 let mut attrs = e.attrs.clone();
3843 attrs.extend::<Vec<_>>(ex.attrs.into());
3848 ExprKind::Yield(ref opt_expr) => {
3849 self.is_generator = true;
3852 .map(|x| self.lower_expr(x))
3853 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3854 hir::ExprYield(P(expr))
3857 // Desugar ExprIfLet
3858 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3859 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3862 // match <sub_expr> {
3864 // _ => [<else_opt> | ()]
3867 let mut arms = vec![];
3869 // `<pat> => <body>`
3871 let body = self.lower_block(body, false);
3872 let body_expr = P(self.expr_block(body, ThinVec::new()));
3873 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3874 arms.push(self.arm(pats, body_expr));
3877 // _ => [<else_opt>|()]
3879 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3880 let wildcard_pattern = self.pat_wild(e.span);
3881 let body = if let Some(else_expr) = wildcard_arm {
3882 P(self.lower_expr(else_expr))
3884 self.expr_tuple(e.span, hir_vec![])
3886 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3889 let contains_else_clause = else_opt.is_some();
3891 let sub_expr = P(self.lower_expr(sub_expr));
3896 hir::MatchSource::IfLetDesugar {
3897 contains_else_clause,
3902 // Desugar ExprWhileLet
3903 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3904 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3907 // [opt_ident]: loop {
3908 // match <sub_expr> {
3914 // Note that the block AND the condition are evaluated in the loop scope.
3915 // This is done to allow `break` from inside the condition of the loop.
3916 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3918 this.lower_block(body, false),
3919 this.expr_break(e.span, ThinVec::new()),
3920 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3924 // `<pat> => <body>`
3926 let body_expr = P(self.expr_block(body, ThinVec::new()));
3927 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3928 self.arm(pats, body_expr)
3933 let pat_under = self.pat_wild(e.span);
3934 self.arm(hir_vec![pat_under], break_expr)
3937 // `match <sub_expr> { ... }`
3938 let arms = hir_vec![pat_arm, break_arm];
3939 let match_expr = self.expr(
3941 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3945 // `[opt_ident]: loop { ... }`
3946 let loop_block = P(self.block_expr(P(match_expr)));
3947 let loop_expr = hir::ExprLoop(
3949 self.lower_label(opt_label),
3950 hir::LoopSource::WhileLet,
3952 // add attributes to the outer returned expr node
3956 // Desugar ExprForLoop
3957 // From: `[opt_ident]: for <pat> in <head> <body>`
3958 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3962 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3964 // [opt_ident]: loop {
3966 // match ::std::iter::Iterator::next(&mut iter) {
3967 // ::std::option::Option::Some(val) => __next = val,
3968 // ::std::option::Option::None => break
3970 // let <pat> = __next;
3971 // StmtExpr(<body>);
3979 let head = self.lower_expr(head);
3980 let head_sp = head.span;
3982 let iter = self.str_to_ident("iter");
3984 let next_ident = self.str_to_ident("__next");
3985 let next_pat = self.pat_ident_binding_mode(
3988 hir::BindingAnnotation::Mutable,
3991 // `::std::option::Option::Some(val) => next = val`
3993 let val_ident = self.str_to_ident("val");
3994 let val_pat = self.pat_ident(pat.span, val_ident);
3995 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3996 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3997 let assign = P(self.expr(
3999 hir::ExprAssign(next_expr, val_expr),
4002 let some_pat = self.pat_some(pat.span, val_pat);
4003 self.arm(hir_vec![some_pat], assign)
4006 // `::std::option::Option::None => break`
4009 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4010 let pat = self.pat_none(e.span);
4011 self.arm(hir_vec![pat], break_expr)
4016 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4018 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4020 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4021 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4022 let next_path = &["iter", "Iterator", "next"];
4023 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4024 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4025 let arms = hir_vec![pat_arm, break_arm];
4029 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
4033 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
4035 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4039 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4041 // `let <pat> = __next`
4042 let pat = self.lower_pat(pat);
4043 let pat_let = self.stmt_let_pat(
4047 hir::LocalSource::ForLoopDesugar,
4050 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4051 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4052 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
4054 let loop_block = P(self.block_all(
4056 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4060 // `[opt_ident]: loop { ... }`
4061 let loop_expr = hir::ExprLoop(
4063 self.lower_label(opt_label),
4064 hir::LoopSource::ForLoop,
4066 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4067 let loop_expr = P(hir::Expr {
4072 attrs: ThinVec::new(),
4075 // `mut iter => { ... }`
4076 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4078 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4079 let into_iter_expr = {
4080 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4081 let into_iter = P(self.expr_std_path(
4082 head_sp, into_iter_path, None, ThinVec::new()));
4083 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4086 let match_expr = P(self.expr_match(
4090 hir::MatchSource::ForLoopDesugar,
4093 // `{ let _result = ...; _result }`
4094 // underscore prevents an unused_variables lint if the head diverges
4095 let result_ident = self.str_to_ident("_result");
4096 let (let_stmt, let_stmt_binding) =
4097 self.stmt_let(e.span, false, result_ident, match_expr);
4099 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4100 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4101 // add the attributes to the outer returned expr node
4102 return self.expr_block(block, e.attrs.clone());
4105 // Desugar ExprKind::Try
4107 ExprKind::Try(ref sub_expr) => {
4110 // match Try::into_result(<expr>) {
4111 // Ok(val) => #[allow(unreachable_code)] val,
4112 // Err(err) => #[allow(unreachable_code)]
4113 // // If there is an enclosing `catch {...}`
4114 // break 'catch_target Try::from_error(From::from(err)),
4116 // return Try::from_error(From::from(err)),
4120 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4122 // Try::into_result(<expr>)
4125 let sub_expr = self.lower_expr(sub_expr);
4127 let path = &["ops", "Try", "into_result"];
4128 let path = P(self.expr_std_path(
4129 unstable_span, path, None, ThinVec::new()));
4130 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4133 // #[allow(unreachable_code)]
4135 // allow(unreachable_code)
4137 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4138 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4139 let uc_nested = attr::mk_nested_word_item(uc_ident);
4140 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4142 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4144 let attrs = vec![attr];
4146 // Ok(val) => #[allow(unreachable_code)] val,
4148 let val_ident = self.str_to_ident("val");
4149 let val_pat = self.pat_ident(e.span, val_ident);
4150 let val_expr = P(self.expr_ident_with_attrs(
4154 ThinVec::from(attrs.clone()),
4156 let ok_pat = self.pat_ok(e.span, val_pat);
4158 self.arm(hir_vec![ok_pat], val_expr)
4161 // Err(err) => #[allow(unreachable_code)]
4162 // return Try::from_error(From::from(err)),
4164 let err_ident = self.str_to_ident("err");
4165 let err_local = self.pat_ident(e.span, err_ident);
4167 let path = &["convert", "From", "from"];
4168 let from = P(self.expr_std_path(
4169 e.span, path, None, ThinVec::new()));
4170 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4172 self.expr_call(e.span, from, hir_vec![err_expr])
4175 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4176 let thin_attrs = ThinVec::from(attrs);
4177 let catch_scope = self.catch_scopes.last().map(|x| *x);
4178 let ret_expr = if let Some(catch_node) = catch_scope {
4184 target_id: Ok(catch_node),
4186 Some(from_err_expr),
4191 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
4194 let err_pat = self.pat_err(e.span, err_local);
4195 self.arm(hir_vec![err_pat], ret_expr)
4200 hir_vec![err_arm, ok_arm],
4201 hir::MatchSource::TryDesugar,
4205 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4208 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4215 attrs: e.attrs.clone(),
4219 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
4220 SmallVector::one(match s.node {
4221 StmtKind::Local(ref l) => Spanned {
4222 node: hir::StmtDecl(
4224 node: hir::DeclLocal(self.lower_local(l)),
4227 self.lower_node_id(s.id).node_id,
4231 StmtKind::Item(ref it) => {
4232 // Can only use the ID once.
4233 let mut id = Some(s.id);
4234 return self.lower_item_id(it)
4236 .map(|item_id| Spanned {
4237 node: hir::StmtDecl(
4239 node: hir::DeclItem(item_id),
4243 .map(|id| self.lower_node_id(id).node_id)
4244 .unwrap_or_else(|| self.next_id().node_id),
4250 StmtKind::Expr(ref e) => Spanned {
4251 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4254 StmtKind::Semi(ref e) => Spanned {
4255 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4258 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4262 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4264 CaptureBy::Value => hir::CaptureByValue,
4265 CaptureBy::Ref => hir::CaptureByRef,
4269 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4270 /// the address space of that item instead of the item currently being
4271 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4272 /// lower a `Visibility` value although we haven't lowered the owning
4273 /// `ImplItem` in question yet.
4274 fn lower_visibility(
4277 explicit_owner: Option<NodeId>,
4278 ) -> hir::Visibility {
4279 let node = match v.node {
4280 VisibilityKind::Public => hir::VisibilityPublic,
4281 VisibilityKind::Crate(sugar) => hir::VisibilityCrate(sugar),
4282 VisibilityKind::Restricted { ref path, id } => hir::VisibilityRestricted {
4283 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4284 id: if let Some(owner) = explicit_owner {
4285 self.lower_node_id_with_owner(id, owner).node_id
4287 self.lower_node_id(id).node_id
4290 VisibilityKind::Inherited => hir::VisibilityInherited,
4292 respan(v.span, node)
4295 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4297 Defaultness::Default => hir::Defaultness::Default {
4298 has_value: has_value,
4300 Defaultness::Final => {
4302 hir::Defaultness::Final
4307 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4309 BlockCheckMode::Default => hir::DefaultBlock,
4310 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4314 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4316 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4317 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4318 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4319 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4323 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4325 CompilerGenerated => hir::CompilerGenerated,
4326 UserProvided => hir::UserProvided,
4330 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4332 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4333 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4337 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4339 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4340 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4344 // Helper methods for building HIR.
4346 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4355 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4357 id: self.next_id().node_id,
4361 is_shorthand: false,
4365 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4366 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
4367 P(self.expr(span, expr_break, attrs))
4374 args: hir::HirVec<hir::Expr>,
4376 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
4379 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4380 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4383 fn expr_ident_with_attrs(
4388 attrs: ThinVec<Attribute>,
4390 let expr_path = hir::ExprPath(hir::QPath::Resolved(
4394 def: Def::Local(binding),
4395 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4399 self.expr(span, expr_path, attrs)
4402 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4403 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
4409 components: &[&str],
4410 params: Option<P<hir::GenericArgs>>,
4411 attrs: ThinVec<Attribute>,
4413 let path = self.std_path(span, components, params, true);
4416 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4425 arms: hir::HirVec<hir::Arm>,
4426 source: hir::MatchSource,
4428 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4431 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4432 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4435 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4436 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4439 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4440 let LoweredNodeId { node_id, hir_id } = self.next_id();
4453 ex: Option<P<hir::Expr>>,
4455 source: hir::LocalSource,
4457 let LoweredNodeId { node_id, hir_id } = self.next_id();
4459 let local = P(hir::Local {
4466 attrs: ThinVec::new(),
4469 let decl = respan(sp, hir::DeclLocal(local));
4470 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4479 ) -> (hir::Stmt, NodeId) {
4480 let pat = if mutbl {
4481 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4483 self.pat_ident(sp, ident)
4485 let pat_id = pat.id;
4487 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4492 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4493 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4499 stmts: hir::HirVec<hir::Stmt>,
4500 expr: Option<P<hir::Expr>>,
4502 let LoweredNodeId { node_id, hir_id } = self.next_id();
4509 rules: hir::DefaultBlock,
4511 targeted_by_break: false,
4516 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4517 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4520 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4521 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4524 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4525 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4528 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4529 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4535 components: &[&str],
4536 subpats: hir::HirVec<P<hir::Pat>>,
4538 let path = self.std_path(span, components, None, true);
4539 let qpath = hir::QPath::Resolved(None, P(path));
4540 let pt = if subpats.is_empty() {
4541 hir::PatKind::Path(qpath)
4543 hir::PatKind::TupleStruct(qpath, subpats, None)
4548 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4549 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4552 fn pat_ident_binding_mode(
4556 bm: hir::BindingAnnotation,
4558 let LoweredNodeId { node_id, hir_id } = self.next_id();
4563 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4568 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4569 self.pat(span, hir::PatKind::Wild)
4572 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4573 let LoweredNodeId { node_id, hir_id } = self.next_id();
4582 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4583 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4584 /// The path is also resolved according to `is_value`.
4588 components: &[&str],
4589 params: Option<P<hir::GenericArgs>>,
4593 .resolve_str_path(span, self.crate_root, components, params, is_value)
4596 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4598 let node = match qpath {
4599 hir::QPath::Resolved(None, path) => {
4600 // Turn trait object paths into `TyTraitObject` instead.
4601 if let Def::Trait(_) = path.def {
4602 let principal = hir::PolyTraitRef {
4603 bound_generic_params: hir::HirVec::new(),
4604 trait_ref: hir::TraitRef {
4605 path: path.and_then(|path| path),
4611 // The original ID is taken by the `PolyTraitRef`,
4612 // so the `Ty` itself needs a different one.
4613 id = self.next_id();
4614 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4616 hir::TyPath(hir::QPath::Resolved(None, path))
4619 _ => hir::TyPath(qpath),
4629 /// Invoked to create the lifetime argument for a type `&T`
4630 /// with no explicit lifetime.
4631 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4632 match self.anonymous_lifetime_mode {
4633 // Intercept when we are in an impl header and introduce an in-band lifetime.
4634 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4636 AnonymousLifetimeMode::CreateParameter => {
4637 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4639 id: self.next_id().node_id,
4641 name: hir::LifetimeName::Param(fresh_name),
4645 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4649 /// Invoked to create the lifetime argument(s) for a path like
4650 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4651 /// sorts of cases are deprecated. This may therefore report a warning or an
4652 /// error, depending on the mode.
4653 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4654 match self.anonymous_lifetime_mode {
4655 // NB. We intentionally ignore the create-parameter mode here
4656 // and instead "pass through" to resolve-lifetimes, which will then
4657 // report an error. This is because we don't want to support
4658 // impl elision for deprecated forms like
4660 // impl Foo for std::cell::Ref<u32> // note lack of '_
4661 AnonymousLifetimeMode::CreateParameter => {}
4663 // This is the normal case.
4664 AnonymousLifetimeMode::PassThrough => {}
4668 .map(|_| self.new_implicit_lifetime(span))
4672 /// Invoked to create the lifetime argument(s) for an elided trait object
4673 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4674 /// when the bound is written, even if it is written with `'_` like in
4675 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4676 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4677 match self.anonymous_lifetime_mode {
4678 // NB. We intentionally ignore the create-parameter mode here.
4679 // and instead "pass through" to resolve-lifetimes, which will apply
4680 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4681 // do not act like other elided lifetimes. In other words, given this:
4683 // impl Foo for Box<dyn Debug>
4685 // we do not introduce a fresh `'_` to serve as the bound, but instead
4686 // ultimately translate to the equivalent of:
4688 // impl Foo for Box<dyn Debug + 'static>
4690 // `resolve_lifetime` has the code to make that happen.
4691 AnonymousLifetimeMode::CreateParameter => {}
4693 // This is the normal case.
4694 AnonymousLifetimeMode::PassThrough => {}
4697 self.new_implicit_lifetime(span)
4700 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4702 id: self.next_id().node_id,
4704 name: hir::LifetimeName::Implicit,
4708 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4709 self.sess.buffer_lint_with_diagnostic(
4710 builtin::BARE_TRAIT_OBJECTS,
4713 "trait objects without an explicit `dyn` are deprecated",
4714 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4718 fn wrap_in_try_constructor(
4720 method: &'static str,
4722 unstable_span: Span,
4724 let path = &["ops", "Try", method];
4725 let from_err = P(self.expr_std_path(unstable_span, path, None,
4727 P(self.expr_call(e.span, from_err, hir_vec![e]))
4731 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4732 // Sorting by span ensures that we get things in order within a
4733 // file, and also puts the files in a sensible order.
4734 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4735 body_ids.sort_by_key(|b| bodies[b].value.span);