From 1b26be575020c26b400b918342ac5c0c9ec76c58 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Wed, 21 Mar 2018 04:24:27 -0400 Subject: [PATCH 1/8] rustfmt lowering.rs --- src/librustc/hir/lowering.rs | 2207 +++++++++++++++++++--------------- 1 file changed, 1249 insertions(+), 958 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index f6bdfde15fc5f..f86e003f3630f 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -43,8 +43,8 @@ use dep_graph::DepGraph; use hir; use hir::HirVec; -use hir::map::{Definitions, DefKey, DefPathData}; -use hir::def_id::{DefIndex, DefId, CRATE_DEF_INDEX, DefIndexAddressSpace}; +use hir::map::{DefKey, DefPathData, Definitions}; +use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX}; use hir::def::{Def, PathResolution}; use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES}; use middle::cstore::CrateStore; @@ -63,10 +63,10 @@ use syntax::errors; use syntax::ext::hygiene::{Mark, SyntaxContext}; use syntax::print::pprust; use syntax::ptr::P; -use syntax::codemap::{self, respan, Spanned, CompilerDesugaringKind}; +use syntax::codemap::{self, respan, CompilerDesugaringKind, Spanned}; use syntax::std_inject; -use syntax::symbol::{Symbol, keywords}; -use syntax::tokenstream::{TokenStream, TokenTree, Delimited}; +use syntax::symbol::{keywords, Symbol}; +use syntax::tokenstream::{Delimited, TokenStream, TokenTree}; use syntax::parse::token::Token; use syntax::util::small_vector::SmallVector; use syntax::visit::{self, Visitor}; @@ -80,13 +80,13 @@ pub struct LoweringContext<'a> { // Use to assign ids to hir nodes that do not directly correspond to an ast node sess: &'a Session, - cstore: &'a dyn CrateStore, + cstore: &'a CrateStore, // As we walk the AST we must keep track of the current 'parent' def id (in // the form of a DefIndex) so that if we create a new node which introduces // a definition, then we can properly create the def id. parent_def: Option, - resolver: &'a mut dyn Resolver, + resolver: &'a mut Resolver, name_map: FxHashMap, /// The items being lowered are collected here. @@ -154,8 +154,13 @@ pub trait Resolver { /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves /// it based on `is_value`. - fn resolve_str_path(&mut self, span: Span, crate_root: Option<&str>, - components: &[&str], is_value: bool) -> hir::Path; + fn resolve_str_path( + &mut self, + span: Span, + crate_root: Option<&str>, + components: &[&str], + is_value: bool, + ) -> hir::Path; } #[derive(Clone, Copy, Debug)] @@ -176,12 +181,13 @@ enum ImplTraitContext { Disallowed, } -pub fn lower_crate(sess: &Session, - cstore: &dyn CrateStore, - dep_graph: &DepGraph, - krate: &Crate, - resolver: &mut dyn Resolver) - -> hir::Crate { +pub fn lower_crate( + sess: &Session, + cstore: &CrateStore, + dep_graph: &DepGraph, + krate: &Crate, + resolver: &mut Resolver, +) -> hir::Crate { // We're constructing the HIR here; we don't care what we will // read, since we haven't even constructed the *input* to // incr. comp. yet. @@ -222,7 +228,7 @@ enum ParamMode { /// Any path in a type context. Explicit, /// The `module::Type` in `module::Type::method` in an expression. - Optional + Optional, } struct LoweredNodeId { @@ -252,13 +258,15 @@ impl<'a> LoweringContext<'a> { self.lctx.allocate_hir_id_counter(item.id, item); match item.node { - ItemKind::Struct(_, ref generics) | - ItemKind::Union(_, ref generics) | - ItemKind::Enum(_, ref generics) | - ItemKind::Ty(_, ref generics) | - ItemKind::Trait(_, _, ref generics, ..) => { + ItemKind::Struct(_, ref generics) + | ItemKind::Union(_, ref generics) + | ItemKind::Enum(_, ref generics) + | ItemKind::Ty(_, ref generics) + | ItemKind::Trait(_, _, ref generics, ..) => { let def_id = self.lctx.resolver.definitions().local_def_id(item.id); - let count = generics.params.iter() + let count = generics + .params + .iter() .filter(|param| param.is_lifetime_param()) .count(); self.lctx.type_def_lifetime_params.insert(def_id, count); @@ -285,7 +293,8 @@ impl<'a> LoweringContext<'a> { impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> { fn with_trait_impl_ref(&mut self, trait_impl_ref: &Option, f: F) - where F: FnOnce(&mut Self) + where + F: FnOnce(&mut Self), { let old = self.lctx.is_in_trait_impl; self.lctx.is_in_trait_impl = if let &None = trait_impl_ref { @@ -311,22 +320,24 @@ impl<'a> LoweringContext<'a> { if item_lowered { let item_lifetimes = match self.lctx.items.get(&item.id).unwrap().node { - hir::Item_::ItemImpl(_,_,_,ref generics,..) | - hir::Item_::ItemTrait(_,_,ref generics,..) => - generics.lifetimes().cloned().collect::>(), + hir::Item_::ItemImpl(_, _, _, ref generics, ..) + | hir::Item_::ItemTrait(_, _, ref generics, ..) => { + generics.lifetimes().cloned().collect::>() + } _ => Vec::new(), }; - self.lctx.with_parent_impl_lifetime_defs(&item_lifetimes, |this| { - let this = &mut ItemLowerer { lctx: this }; - if let ItemKind::Impl(_,_,_,_,ref opt_trait_ref,_,_) = item.node { - this.with_trait_impl_ref(opt_trait_ref, |this| { - visit::walk_item(this, item) - }); - } else { - visit::walk_item(this, item); - } - }); + self.lctx + .with_parent_impl_lifetime_defs(&item_lifetimes, |this| { + let this = &mut ItemLowerer { lctx: this }; + if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node { + this.with_trait_impl_ref(opt_trait_ref, |this| { + visit::walk_item(this, item) + }); + } else { + visit::walk_item(this, item); + } + }); } } @@ -379,27 +390,26 @@ impl<'a> LoweringContext<'a> { } } - fn allocate_hir_id_counter(&mut self, - owner: NodeId, - debug: &T) { + fn allocate_hir_id_counter(&mut self, owner: NodeId, debug: &T) { if self.item_local_id_counters.insert(owner, 0).is_some() { - bug!("Tried to allocate item_local_id_counter for {:?} twice", debug); + bug!( + "Tried to allocate item_local_id_counter for {:?} twice", + debug + ); } // Always allocate the first HirId for the owner itself self.lower_node_id_with_owner(owner, owner); } - fn lower_node_id_generic(&mut self, - ast_node_id: NodeId, - alloc_hir_id: F) - -> LoweredNodeId - where F: FnOnce(&mut Self) -> hir::HirId + fn lower_node_id_generic(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId + where + F: FnOnce(&mut Self) -> hir::HirId, { if ast_node_id == DUMMY_NODE_ID { return LoweredNodeId { node_id: DUMMY_NODE_ID, hir_id: hir::DUMMY_HIR_ID, - } + }; } let min_size = ast_node_id.as_usize() + 1; @@ -427,11 +437,12 @@ impl<'a> LoweringContext<'a> { } fn with_hir_id_owner(&mut self, owner: NodeId, f: F) - where F: FnOnce(&mut Self) + where + F: FnOnce(&mut Self), { let counter = self.item_local_id_counters - .insert(owner, HIR_ID_COUNTER_LOCKED) - .unwrap(); + .insert(owner, HIR_ID_COUNTER_LOCKED) + .unwrap(); let def_index = self.resolver.definitions().opt_def_index(owner).unwrap(); self.current_hir_id_owner.push((def_index, counter)); f(self); @@ -440,7 +451,9 @@ impl<'a> LoweringContext<'a> { debug_assert!(def_index == new_def_index); debug_assert!(new_counter >= counter); - let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap(); + let prev = self.item_local_id_counters + .insert(owner, new_counter) + .unwrap(); debug_assert!(prev == HIR_ID_COUNTER_LOCKED); } @@ -452,9 +465,8 @@ impl<'a> LoweringContext<'a> { /// properly. Calling the method twice with the same NodeId is fine though. fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId { self.lower_node_id_generic(ast_node_id, |this| { - let &mut (def_index, ref mut local_id_counter) = this.current_hir_id_owner - .last_mut() - .unwrap(); + let &mut (def_index, ref mut local_id_counter) = + this.current_hir_id_owner.last_mut().unwrap(); let local_id = *local_id_counter; *local_id_counter += 1; hir::HirId { @@ -464,14 +476,9 @@ impl<'a> LoweringContext<'a> { }) } - fn lower_node_id_with_owner(&mut self, - ast_node_id: NodeId, - owner: NodeId) - -> LoweredNodeId { + fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId { self.lower_node_id_generic(ast_node_id, |this| { - let local_id_counter = this.item_local_id_counters - .get_mut(&owner) - .unwrap(); + let local_id_counter = this.item_local_id_counters.get_mut(&owner).unwrap(); let local_id = *local_id_counter; // We want to be sure not to modify the counter in the map while it @@ -489,8 +496,7 @@ impl<'a> LoweringContext<'a> { }) } - fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) - -> hir::BodyId { + fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId { let body = hir::Body { arguments: decl.map_or(hir_vec![], |decl| { decl.inputs.iter().map(|x| self.lower_arg(x)).collect() @@ -524,8 +530,7 @@ impl<'a> LoweringContext<'a> { Symbol::gensym(s) } - fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span - { + fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span { let mark = Mark::fresh(Mark::root()); mark.set_expn_info(codemap::ExpnInfo { call_site: span, @@ -545,8 +550,10 @@ impl<'a> LoweringContext<'a> { fn collect_in_band_defs( &mut self, parent_id: Option, - f: F - ) -> (Vec, T) where F: FnOnce(&mut LoweringContext) -> T + f: F, + ) -> (Vec, T) + where + F: FnOnce(&mut LoweringContext) -> T, { assert!(!self.is_collecting_in_band_lifetimes); assert!(self.lifetimes_to_define.is_empty()); @@ -562,7 +569,9 @@ impl<'a> LoweringContext<'a> { let lifetimes_to_define = self.lifetimes_to_define.split_off(0); let mut params = match parent_id { - Some(parent_id) => lifetimes_to_define.into_iter().map(|(span, name)| { + Some(parent_id) => lifetimes_to_define + .into_iter() + .map(|(span, name)| { let def_node_id = self.next_id().node_id; // Add a definition for the in-band lifetime def @@ -572,7 +581,7 @@ impl<'a> LoweringContext<'a> { DefPathData::LifetimeDef(name.as_str()), DefIndexAddressSpace::High, Mark::root(), - span + span, ); hir::GenericParam::Lifetime(hir::LifetimeDef { @@ -585,11 +594,16 @@ impl<'a> LoweringContext<'a> { pure_wrt_drop: false, in_band: true, }) - }).collect(), + }) + .collect(), None => Vec::new(), }; - params.extend(in_band_ty_params.into_iter().map(|tp| hir::GenericParam::Type(tp))); + params.extend( + in_band_ty_params + .into_iter() + .map(|tp| hir::GenericParam::Type(tp)), + ); (params, res) } @@ -598,11 +612,9 @@ impl<'a> LoweringContext<'a> { // This is used to track which lifetimes have already been defined, and // which are new in-band lifetimes that need to have a definition created // for them. - fn with_in_scope_lifetime_defs( - &mut self, - lt_defs: &[LifetimeDef], - f: F - ) -> T where F: FnOnce(&mut LoweringContext) -> T + fn with_in_scope_lifetime_defs(&mut self, lt_defs: &[LifetimeDef], f: F) -> T + where + F: FnOnce(&mut LoweringContext) -> T, { let old_len = self.in_scope_lifetimes.len(); let lt_def_names = lt_defs.iter().map(|lt_def| lt_def.lifetime.ident.name); @@ -619,11 +631,9 @@ impl<'a> LoweringContext<'a> { // This should only be used with generics that have already had their // in-band lifetimes added. In practice, this means that this function is // only used when lowering a child item of a trait or impl. - fn with_parent_impl_lifetime_defs( - &mut self, - lt_defs: &[hir::LifetimeDef], - f: F - ) -> T where F: FnOnce(&mut LoweringContext) -> T + fn with_parent_impl_lifetime_defs(&mut self, lt_defs: &[hir::LifetimeDef], f: F) -> T + where + F: FnOnce(&mut LoweringContext) -> T, { let old_len = self.in_scope_lifetimes.len(); let lt_def_names = lt_defs.iter().map(|lt_def| lt_def.lifetime.name.name()); @@ -641,41 +651,50 @@ impl<'a> LoweringContext<'a> { &mut self, generics: &Generics, parent_id: Option, - f: F + f: F, ) -> (hir::Generics, T) - where F: FnOnce(&mut LoweringContext) -> T + where + F: FnOnce(&mut LoweringContext) -> T, { - let (in_band_defs, (mut lowered_generics, res)) = - self.with_in_scope_lifetime_defs( - &generics.params - .iter() - .filter_map(|p| match *p { - GenericParam::Lifetime(ref ld) => Some(ld.clone()), - _ => None, - }) - .collect::>(), - |this| { - this.collect_in_band_defs(parent_id, |this| { - (this.lower_generics(generics), f(this)) - }) - } - ); + let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs( + &generics + .params + .iter() + .filter_map(|p| match *p { + GenericParam::Lifetime(ref ld) => Some(ld.clone()), + _ => None, + }) + .collect::>(), + |this| { + this.collect_in_band_defs(parent_id, |this| { + (this.lower_generics(generics), f(this)) + }) + }, + ); - lowered_generics.params = - lowered_generics.params.iter().cloned().chain(in_band_defs).collect(); + lowered_generics.params = lowered_generics + .params + .iter() + .cloned() + .chain(in_band_defs) + .collect(); (lowered_generics, res) } fn with_catch_scope(&mut self, catch_id: NodeId, f: F) -> T - where F: FnOnce(&mut LoweringContext) -> T + where + F: FnOnce(&mut LoweringContext) -> T, { let len = self.catch_scopes.len(); self.catch_scopes.push(catch_id); let result = f(self); - assert_eq!(len + 1, self.catch_scopes.len(), - "catch scopes should be added and removed in stack order"); + assert_eq!( + len + 1, + self.catch_scopes.len(), + "catch scopes should be added and removed in stack order" + ); self.catch_scopes.pop().unwrap(); @@ -683,17 +702,19 @@ impl<'a> LoweringContext<'a> { } fn lower_body(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId - where F: FnOnce(&mut LoweringContext) -> hir::Expr + where + F: FnOnce(&mut LoweringContext) -> hir::Expr, { let prev = mem::replace(&mut self.is_generator, false); let result = f(self); let r = self.record_body(result, decl); self.is_generator = prev; - return r + return r; } fn with_loop_scope(&mut self, loop_id: NodeId, f: F) -> T - where F: FnOnce(&mut LoweringContext) -> T + where + F: FnOnce(&mut LoweringContext) -> T, { // We're no longer in the base loop's condition; we're in another loop. let was_in_loop_condition = self.is_in_loop_condition; @@ -703,8 +724,11 @@ impl<'a> LoweringContext<'a> { self.loop_scopes.push(loop_id); let result = f(self); - assert_eq!(len + 1, self.loop_scopes.len(), - "Loop scopes should be added and removed in stack order"); + assert_eq!( + len + 1, + self.loop_scopes.len(), + "Loop scopes should be added and removed in stack order" + ); self.loop_scopes.pop().unwrap(); @@ -714,7 +738,8 @@ impl<'a> LoweringContext<'a> { } fn with_loop_condition_scope(&mut self, f: F) -> T - where F: FnOnce(&mut LoweringContext) -> T + where + F: FnOnce(&mut LoweringContext) -> T, { let was_in_loop_condition = self.is_in_loop_condition; self.is_in_loop_condition = true; @@ -727,7 +752,8 @@ impl<'a> LoweringContext<'a> { } fn with_new_scopes(&mut self, f: F) -> T - where F: FnOnce(&mut LoweringContext) -> T + where + F: FnOnce(&mut LoweringContext) -> T, { let was_in_loop_condition = self.is_in_loop_condition; self.is_in_loop_condition = false; @@ -744,7 +770,8 @@ impl<'a> LoweringContext<'a> { } fn with_parent_def(&mut self, parent_id: NodeId, f: F) -> T - where F: FnOnce(&mut LoweringContext) -> T + where + F: FnOnce(&mut LoweringContext) -> T, { let old_def = self.parent_def; self.parent_def = { @@ -771,16 +798,19 @@ impl<'a> LoweringContext<'a> { if ident.ctxt == SyntaxContext::empty() { return ident.name; } - *self.name_map.entry(ident).or_insert_with(|| Symbol::from_ident(ident)) + *self.name_map + .entry(ident) + .or_insert_with(|| Symbol::from_ident(ident)) } fn lower_label(&mut self, label: Option